File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.438: download - view: text, annotated - select for diffs
Thu Mar 30 14:08:18 2017 UTC (7 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Option to search institutional directory not needed in user search
  when displaying user's access logs.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.438 2017/03/30 14:08:18 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: 
   75: my $loginscript; # piece of javascript used in two separate instances
   76: my $authformnop;
   77: my $authformkrb;
   78: my $authformint;
   79: my $authformfsys;
   80: my $authformloc;
   81: 
   82: sub initialize_authen_forms {
   83:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   84:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   85:     my %param = ( formname => $formname,
   86:                   kerb_def_dom => $krbdefdom,
   87:                   kerb_def_auth => $krbdef,
   88:                   domain => $dom,
   89:                 );
   90:     my %abv_auth = &auth_abbrev();
   91:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   92:         my $long_auth = $1;
   93:         my $curr_autharg = $2;
   94:         my %abv_auth = &auth_abbrev();
   95:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   96:         if ($long_auth =~ /^krb(4|5)$/) {
   97:             $param{'curr_kerb_ver'} = $1;
   98:             $param{'curr_autharg'} = $curr_autharg;
   99:         }
  100:         if ($mode eq 'modifyuser') {
  101:             $param{'mode'} = $mode;
  102:         }
  103:     }
  104:     $loginscript  = &Apache::loncommon::authform_header(%param);
  105:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  106:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  107:     $authformint  = &Apache::loncommon::authform_internal(%param);
  108:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  109:     $authformloc  = &Apache::loncommon::authform_local(%param);
  110: }
  111: 
  112: sub auth_abbrev {
  113:     my %abv_auth = (
  114:                      krb5      => 'krb',
  115:                      krb4      => 'krb',
  116:                      internal  => 'int',
  117:                      localauth => 'loc',
  118:                      unix      => 'fsys',
  119:                    );
  120:     return %abv_auth;
  121: }
  122: 
  123: # ====================================================
  124: 
  125: sub user_quotas {
  126:     my ($ccuname,$ccdomain) = @_;
  127:     my %lt = &Apache::lonlocal::texthash(
  128:                    'usrt'      => "User Tools",
  129:                    'cust'      => "Custom quota",
  130:                    'chqu'      => "Change quota",
  131:     );
  132:    
  133:     my $quota_javascript = <<"END_SCRIPT";
  134: <script type="text/javascript">
  135: // <![CDATA[
  136: function quota_changes(caller,context) {
  137:     var customoff = document.getElementById('custom_'+context+'quota_off');
  138:     var customon = document.getElementById('custom_'+context+'quota_on');
  139:     var number = document.getElementById(context+'quota');
  140:     if (caller == "custom") {
  141:         if (customoff) {
  142:             if (customoff.checked) {
  143:                 number.value = "";
  144:             }
  145:         }
  146:     }
  147:     if (caller == "quota") {
  148:         if (customon) {
  149:             customon.checked = true;
  150:         }
  151:     }
  152:     return;
  153: }
  154: // ]]>
  155: </script>
  156: END_SCRIPT
  157:     my $longinsttype;
  158:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  159:     my $output = $quota_javascript."\n".
  160:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  161:                  &Apache::loncommon::start_data_table();
  162: 
  163:     if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
  164:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  165:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  166:     }
  167: 
  168:     my %titles = &Apache::lonlocal::texthash (
  169:                     portfolio => "Disk space allocated to user's portfolio files",
  170:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  171:                  );
  172:     foreach my $name ('portfolio','author') {
  173:         my ($currquota,$quotatype,$inststatus,$defquota) =
  174:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  175:         if ($longinsttype eq '') { 
  176:             if ($inststatus ne '') {
  177:                 if ($usertypes->{$inststatus} ne '') {
  178:                     $longinsttype = $usertypes->{$inststatus};
  179:                 }
  180:             }
  181:         }
  182:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  183:         $custom_on = ' ';
  184:         $custom_off = ' checked="checked" ';
  185:         if ($quotatype eq 'custom') {
  186:             $custom_on = $custom_off;
  187:             $custom_off = ' ';
  188:             $showquota = $currquota;
  189:             if ($longinsttype eq '') {
  190:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  191:                               .' MB.',$defquota);
  192:             } else {
  193:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  194:                                    " MB, as determined by the user's institutional".
  195:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  196:             }
  197:         } else {
  198:             if ($longinsttype eq '') {
  199:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  200:                               .' MB.',$defquota);
  201:             } else {
  202:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  203:                                    " MB, is determined by the user's institutional".
  204:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  205:             }
  206:         }
  207: 
  208:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  209:             $output .= '<tr class="LC_info_row">'."\n".
  210:                        '    <td>'.$titles{$name}.'</td>'."\n".
  211:                        '  </tr>'."\n".
  212:                        &Apache::loncommon::start_data_table_row()."\n".
  213:                        '  <td><span class="LC_nobreak">'.
  214:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  215:                        $defaultinfo.'</td>'."\n".
  216:                        &Apache::loncommon::end_data_table_row()."\n".
  217:                        &Apache::loncommon::start_data_table_row()."\n".
  218:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  219:                        ': <label>'.
  220:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  221:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  222:                        ' /><span class="LC_nobreak">'.
  223:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  224:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  225:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  226:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  227:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  228:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  229:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  230:                        &Apache::loncommon::end_data_table_row()."\n";
  231:         }
  232:     }
  233:     $output .= &Apache::loncommon::end_data_table();
  234:     return $output;
  235: }
  236: 
  237: sub build_tools_display {
  238:     my ($ccuname,$ccdomain,$context) = @_;
  239:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  240:         $colspan,$isadv,%domconfig);
  241:     my %lt = &Apache::lonlocal::texthash (
  242:                    'blog'       => "Personal User Blog",
  243:                    'aboutme'    => "Personal Information Page",
  244:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  245:                    'portfolio'  => "Personal User Portfolio",
  246:                    'avai'       => "Available",
  247:                    'cusa'       => "availability",
  248:                    'chse'       => "Change setting",
  249:                    'usde'       => "Use default",
  250:                    'uscu'       => "Use custom",
  251:                    'official'   => 'Can request creation of official courses',
  252:                    'unofficial' => 'Can request creation of unofficial courses',
  253:                    'community'  => 'Can request creation of communities',
  254:                    'textbook'   => 'Can request creation of textbook courses',
  255:                    'placement'  => 'Can request creation of placement tests',
  256:                    'requestauthor'  => 'Can request author space',
  257:     );
  258:     if ($context eq 'requestcourses') {
  259:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  260:                       'requestcourses.official','requestcourses.unofficial',
  261:                       'requestcourses.community','requestcourses.textbook',
  262:                       'requestcourses.placement');
  263:         @usertools = ('official','unofficial','community','textbook','placement');
  264:         @options =('norequest','approval','autolimit','validate');
  265:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  266:         %reqtitles = &courserequest_titles();
  267:         %reqdisplay = &courserequest_display();
  268:         $colspan = ' colspan="2"';
  269:         %domconfig =
  270:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  271:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  272:     } elsif ($context eq 'requestauthor') {
  273:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  274:                                                     'requestauthor');
  275:         @usertools = ('requestauthor');
  276:         @options =('norequest','approval','automatic');
  277:         %reqtitles = &requestauthor_titles();
  278:         %reqdisplay = &requestauthor_display();
  279:         $colspan = ' colspan="2"';
  280:         %domconfig =
  281:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  282:     } else {
  283:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  284:                           'tools.aboutme','tools.portfolio','tools.blog',
  285:                           'tools.webdav');
  286:         @usertools = ('aboutme','blog','webdav','portfolio');
  287:     }
  288:     foreach my $item (@usertools) {
  289:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  290:             $currdisp,$custdisp,$custradio);
  291:         $cust_off = 'checked="checked" ';
  292:         $tool_on = 'checked="checked" ';
  293:         $curr_access =  
  294:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  295:                                               $context);
  296:         if ($context eq 'requestauthor') {
  297:             if ($userenv{$context} ne '') {
  298:                 $cust_on = ' checked="checked" ';
  299:                 $cust_off = '';
  300:             }  
  301:         } elsif ($userenv{$context.'.'.$item} ne '') {
  302:             $cust_on = ' checked="checked" ';
  303:             $cust_off = '';
  304:         }
  305:         if ($context eq 'requestcourses') {
  306:             if ($userenv{$context.'.'.$item} eq '') {
  307:                 $custom_access = &mt('Currently from default setting.');
  308:             } else {
  309:                 $custom_access = &mt('Currently from custom setting.');
  310:             }
  311:         } elsif ($context eq 'requestauthor') {
  312:             if ($userenv{$context} eq '') {
  313:                 $custom_access = &mt('Currently from default setting.');
  314:             } else {
  315:                 $custom_access = &mt('Currently from custom setting.');
  316:             }
  317:         } else {
  318:             if ($userenv{$context.'.'.$item} eq '') {
  319:                 $custom_access =
  320:                     &mt('Availability determined currently from default setting.');
  321:                 if (!$curr_access) {
  322:                     $tool_off = 'checked="checked" ';
  323:                     $tool_on = '';
  324:                 }
  325:             } else {
  326:                 $custom_access =
  327:                     &mt('Availability determined currently from custom setting.');
  328:                 if ($userenv{$context.'.'.$item} == 0) {
  329:                     $tool_off = 'checked="checked" ';
  330:                     $tool_on = '';
  331:                 }
  332:             }
  333:         }
  334:         $output .= '  <tr class="LC_info_row">'."\n".
  335:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  336:                    '  </tr>'."\n".
  337:                    &Apache::loncommon::start_data_table_row()."\n";
  338:   
  339:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  340:             my ($curroption,$currlimit);
  341:             my $envkey = $context.'.'.$item;
  342:             if ($context eq 'requestauthor') {
  343:                 $envkey = $context;
  344:             }
  345:             if ($userenv{$envkey} ne '') {
  346:                 $curroption = $userenv{$envkey};
  347:             } else {
  348:                 my (@inststatuses);
  349:                 if ($context eq 'requestcourses') {
  350:                     $curroption =
  351:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  352:                                                                       $isadv,$ccdomain,$item,
  353:                                                                       \@inststatuses,\%domconfig);
  354:                 } else {
  355:                      $curroption = 
  356:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  357:                                                                        $isadv,$ccdomain,undef,
  358:                                                                        \@inststatuses,\%domconfig);
  359:                 }
  360:             }
  361:             if (!$curroption) {
  362:                 $curroption = 'norequest';
  363:             }
  364:             if ($curroption =~ /^autolimit=(\d*)$/) {
  365:                 $currlimit = $1;
  366:                 if ($currlimit eq '') {
  367:                     $currdisp = &mt('Yes, automatic creation');
  368:                 } else {
  369:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  370:                 }
  371:             } else {
  372:                 $currdisp = $reqdisplay{$curroption};
  373:             }
  374:             $custdisp = '<table>';
  375:             foreach my $option (@options) {
  376:                 my $val = $option;
  377:                 if ($option eq 'norequest') {
  378:                     $val = 0;
  379:                 }
  380:                 if ($option eq 'validate') {
  381:                     my $canvalidate = 0;
  382:                     if (ref($validations{$item}) eq 'HASH') {
  383:                         if ($validations{$item}{'_custom_'}) {
  384:                             $canvalidate = 1;
  385:                         }
  386:                     }
  387:                     next if (!$canvalidate);
  388:                 }
  389:                 my $checked = '';
  390:                 if ($option eq $curroption) {
  391:                     $checked = ' checked="checked"';
  392:                 } elsif ($option eq 'autolimit') {
  393:                     if ($curroption =~ /^autolimit/) {
  394:                         $checked = ' checked="checked"';
  395:                     }
  396:                 }
  397:                 my $name = 'crsreq_'.$item;
  398:                 if ($context eq 'requestauthor') {
  399:                     $name = $item;
  400:                 }
  401:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  402:                              '<input type="radio" name="'.$name.'" '.
  403:                              'value="'.$val.'"'.$checked.' />'.
  404:                              $reqtitles{$option}.'</label>&nbsp;';
  405:                 if ($option eq 'autolimit') {
  406:                     $custdisp .= '<input type="text" name="'.$name.
  407:                                  '_limit" size="1" '.
  408:                                  'value="'.$currlimit.'" /></span><br />'.
  409:                                  $reqtitles{'unlimited'};
  410:                 } else {
  411:                     $custdisp .= '</span>';
  412:                 }
  413:                 $custdisp .= '</td></tr>';
  414:             }
  415:             $custdisp .= '</table>';
  416:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  417:         } else {
  418:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  419:             my $name = $context.'_'.$item;
  420:             if ($context eq 'requestauthor') {
  421:                 $name = $context;
  422:             }
  423:             $custdisp = '<span class="LC_nobreak"><label>'.
  424:                         '<input type="radio" name="'.$name.'"'.
  425:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  426:                         '<input type="radio" name="'.$name.'" value="0" '.
  427:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  428:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  429:                           '</span>';
  430:         }
  431:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  432:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  433:                    &Apache::loncommon::end_data_table_row()."\n";
  434:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  435:             $output .=
  436:                    &Apache::loncommon::start_data_table_row()."\n".
  437:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  438:                    $lt{'chse'}.': <label>'.
  439:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  440:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  441:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  442:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  443:                    &Apache::loncommon::end_data_table_row()."\n";
  444:         }
  445:     }
  446:     return $output;
  447: }
  448: 
  449: sub coursereq_externaluser {
  450:     my ($ccuname,$ccdomain,$cdom) = @_;
  451:     my (@usertools,@options,%validations,%userenv,$output);
  452:     my %lt = &Apache::lonlocal::texthash (
  453:                    'official'   => 'Can request creation of official courses',
  454:                    'unofficial' => 'Can request creation of unofficial courses',
  455:                    'community'  => 'Can request creation of communities',
  456:                    'textbook'   => 'Can request creation of textbook courses',
  457:                    'placement'  => 'Can request creation of placement tests',
  458:     );
  459: 
  460:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  461:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  462:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  463:                       'reqcrsotherdom.placement');
  464:     @usertools = ('official','unofficial','community','textbook','placement');
  465:     @options = ('approval','validate','autolimit');
  466:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  467:     my $optregex = join('|',@options);
  468:     my %reqtitles = &courserequest_titles();
  469:     foreach my $item (@usertools) {
  470:         my ($curroption,$currlimit,$tooloff);
  471:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  472:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  473:             foreach my $req (@curr) {
  474:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  475:                     $curroption = $1;
  476:                     $currlimit = $2;
  477:                     last;
  478:                 }
  479:             }
  480:             if (!$curroption) {
  481:                 $curroption = 'norequest';
  482:                 $tooloff = ' checked="checked"';
  483:             }
  484:         } else {
  485:             $curroption = 'norequest';
  486:             $tooloff = ' checked="checked"';
  487:         }
  488:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  489:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  490:                   '<table><tr><td valign="top">'."\n".
  491:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  492:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  493:                   '</label></td>';
  494:         foreach my $option (@options) {
  495:             if ($option eq 'validate') {
  496:                 my $canvalidate = 0;
  497:                 if (ref($validations{$item}) eq 'HASH') {
  498:                     if ($validations{$item}{'_external_'}) {
  499:                         $canvalidate = 1;
  500:                     }
  501:                 }
  502:                 next if (!$canvalidate);
  503:             }
  504:             my $checked = '';
  505:             if ($option eq $curroption) {
  506:                 $checked = ' checked="checked"';
  507:             }
  508:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  509:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  510:                        '" value="'.$option.'"'.$checked.' />'.
  511:                        $reqtitles{$option}.'</label>';
  512:             if ($option eq 'autolimit') {
  513:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  514:                            $item.'_limit" size="1" '.
  515:                            'value="'.$currlimit.'" /></span>'.
  516:                            '<br />'.$reqtitles{'unlimited'};
  517:             } else {
  518:                 $output .= '</span>';
  519:             }
  520:             $output .= '</td>';
  521:         }
  522:         $output .= '</td></tr></table></td>'."\n".
  523:                    &Apache::loncommon::end_data_table_row()."\n";
  524:     }
  525:     return $output;
  526: }
  527: 
  528: sub domainrole_req {
  529:     my ($ccuname,$ccdomain) = @_;
  530:     return '<br /><h3>'.
  531:            &mt('User Can Request Assignment of Domain Roles?').
  532:            '</h3>'."\n".
  533:            &Apache::loncommon::start_data_table().
  534:            &build_tools_display($ccuname,$ccdomain,
  535:                                 'requestauthor').
  536:            &Apache::loncommon::end_data_table();
  537: }
  538: 
  539: sub courserequest_titles {
  540:     my %titles = &Apache::lonlocal::texthash (
  541:                                    official   => 'Official',
  542:                                    unofficial => 'Unofficial',
  543:                                    community  => 'Communities',
  544:                                    textbook   => 'Textbook',
  545:                                    placement  => 'Placement Tests',
  546:                                    norequest  => 'Not allowed',
  547:                                    approval   => 'Approval by Dom. Coord.',
  548:                                    validate   => 'With validation',
  549:                                    autolimit  => 'Numerical limit',
  550:                                    unlimited  => '(blank for unlimited)',
  551:                  );
  552:     return %titles;
  553: }
  554: 
  555: sub courserequest_display {
  556:     my %titles = &Apache::lonlocal::texthash (
  557:                                    approval   => 'Yes, need approval',
  558:                                    validate   => 'Yes, with validation',
  559:                                    norequest  => 'No',
  560:    );
  561:    return %titles;
  562: }
  563: 
  564: sub requestauthor_titles {
  565:     my %titles = &Apache::lonlocal::texthash (
  566:                                    norequest  => 'Not allowed',
  567:                                    approval   => 'Approval by Dom. Coord.',
  568:                                    automatic  => 'Automatic approval',
  569:                  );
  570:     return %titles;
  571: 
  572: }
  573: 
  574: sub requestauthor_display {
  575:     my %titles = &Apache::lonlocal::texthash (
  576:                                    approval   => 'Yes, need approval',
  577:                                    automatic  => 'Yes, automatic approval',
  578:                                    norequest  => 'No',
  579:    );
  580:    return %titles;
  581: }
  582: 
  583: sub requestchange_display {
  584:     my %titles = &Apache::lonlocal::texthash (
  585:                                    approval   => "availability set to 'on' (approval required)", 
  586:                                    automatic  => "availability set to 'on' (automatic approval)",
  587:                                    norequest  => "availability set to 'off'",
  588:    );
  589:    return %titles;
  590: }
  591: 
  592: sub curr_requestauthor {
  593:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  594:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  595:     if ($uname eq '' || $udom eq '') {
  596:         $uname = $env{'user.name'};
  597:         $udom = $env{'user.domain'};
  598:         $isadv = $env{'user.adv'};
  599:     }
  600:     my (%userenv,%settings,$val);
  601:     my @options = ('automatic','approval');
  602:     %userenv =
  603:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  604:     if ($userenv{'requestauthor'}) {
  605:         $val = $userenv{'requestauthor'};
  606:         @{$inststatuses} = ('_custom_');
  607:     } else {
  608:         my %alltasks;
  609:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  610:             %settings = %{$domconfig->{'requestauthor'}};
  611:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  612:                 $val = $settings{'_LC_adv'};
  613:                 @{$inststatuses} = ('_LC_adv_');
  614:             } else {
  615:                 if ($userenv{'inststatus'} ne '') {
  616:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  617:                 } else {
  618:                     @{$inststatuses} = ('default');
  619:                 }
  620:                 foreach my $status (@{$inststatuses}) {
  621:                     if (exists($settings{$status})) {
  622:                         my $value = $settings{$status};
  623:                         next unless ($value);
  624:                         unless (exists($alltasks{$value})) {
  625:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  626:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  627:                                     push(@{$alltasks{$value}},$status);
  628:                                 }
  629:                             } else {
  630:                                 @{$alltasks{$value}} = ($status);
  631:                             }
  632:                         }
  633:                     }
  634:                 }
  635:                 foreach my $option (@options) {
  636:                     if ($alltasks{$option}) {
  637:                         $val = $option;
  638:                         last;
  639:                     }
  640:                 }
  641:             }
  642:         }
  643:     }
  644:     return $val;
  645: }
  646: 
  647: # =================================================================== Phase one
  648: 
  649: sub print_username_entry_form {
  650:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum) = @_;
  651:     my $defdom=$env{'request.role.domain'};
  652:     my $formtoset = 'crtuser';
  653:     if (exists($env{'form.startrolename'})) {
  654:         $formtoset = 'docustom';
  655:         $env{'form.rolename'} = $env{'form.startrolename'};
  656:     } elsif ($env{'form.origform'} eq 'crtusername') {
  657:         $formtoset =  $env{'form.origform'};
  658:     }
  659: 
  660:     my ($jsback,$elements) = &crumb_utilities();
  661: 
  662:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  663:         '<script type="text/javascript">'."\n".
  664:         '// <![CDATA['."\n".
  665:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  666:         '// ]]>'."\n".
  667:         '</script>'."\n";
  668: 
  669:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  670:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  671:         && (&Apache::lonnet::allowed('mcr','/'))) {
  672:         $jscript .= &customrole_javascript();
  673:     }
  674:     my $helpitem = 'Course_Change_Privileges';
  675:     if ($env{'form.action'} eq 'custom') {
  676:         $helpitem = 'Course_Editing_Custom_Roles';
  677:     } elsif ($env{'form.action'} eq 'singlestudent') {
  678:         $helpitem = 'Course_Add_Student';
  679:     } elsif ($env{'form.action'} eq 'accesslogs') {
  680:         $helpitem = 'Domain_User_Access_Logs';
  681:     }
  682:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  683:     if ($env{'form.action'} eq 'custom') {
  684:         push(@{$brcrum},
  685:                  {href=>"javascript:backPage(document.crtuser)",       
  686:                   text=>"Pick custom role",
  687:                   help => $helpitem,}
  688:                  );
  689:     } else {
  690:         push (@{$brcrum},
  691:                   {href => "javascript:backPage(document.crtuser)",
  692:                    text => $breadcrumb_text{'search'},
  693:                    help => $helpitem,
  694:                    faq  => 282,
  695:                    bug  => 'Instructor Interface',}
  696:                   );
  697:     }
  698:     my %loaditems = (
  699:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  700:                     );
  701:     my $args = {bread_crumbs           => $brcrum,
  702:                 bread_crumbs_component => 'User Management',
  703:                 add_entries            => \%loaditems,};
  704:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  705: 
  706:     my %lt=&Apache::lonlocal::texthash(
  707:                     'srst' => 'Search for a user and enroll as a student',
  708:                     'srme' => 'Search for a user and enroll as a member',
  709:                     'srad' => 'Search for a user and modify/add user information or roles',
  710:                     'srvu' => 'Search for a user and view user information and roles',
  711:                     'srva' => 'Search for a user and view access log information',
  712: 		    'usr'  => "Username",
  713:                     'dom'  => "Domain",
  714:                     'ecrp' => "Define or Edit Custom Role",
  715:                     'nr'   => "role name",
  716:                     'cre'  => "Next",
  717: 				       );
  718: 
  719:     if ($env{'form.action'} eq 'custom') {
  720:         if (&Apache::lonnet::allowed('mcr','/')) {
  721:             my $newroletext = &mt('Define new custom role:');
  722:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  723:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  724:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  725:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  726:                       &Apache::loncommon::start_data_table().
  727:                       &Apache::loncommon::start_data_table_row().
  728:                       '<td>');
  729:             if (keys(%existingroles) > 0) {
  730:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  731:             } else {
  732:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  733:             }
  734:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  735:                       &Apache::loncommon::end_data_table_row());
  736:             if (keys(%existingroles) > 0) {
  737:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  738:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  739:                           &mt('View/Modify existing role:').'</b></label></td>'.
  740:                           '<td align="center"><br />'.
  741:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  742:                           '<option value="" selected="selected">'.
  743:                           &mt('Select'));
  744:                 foreach my $role (sort(keys(%existingroles))) {
  745:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  746:                 }
  747:                 $r->print('</select>'.
  748:                           '</td>'.
  749:                           &Apache::loncommon::end_data_table_row());
  750:             }
  751:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  752:                       '<input name="customeditor" type="submit" value="'.
  753:                       $lt{'cre'}.'" /></p>'.
  754:                       '</form>');
  755:         }
  756:     } else {
  757:         my $actiontext = $lt{'srad'};
  758:         my $fixeddom;
  759:         if ($env{'form.action'} eq 'singlestudent') {
  760:             if ($crstype eq 'Community') {
  761:                 $actiontext = $lt{'srme'};
  762:             } else {
  763:                 $actiontext = $lt{'srst'};
  764:             }
  765:         } elsif ($env{'form.action'} eq 'accesslogs') {
  766:             $actiontext = $lt{'srva'};
  767:             $fixeddom = 1;
  768:         } elsif (($env{'form.action'} eq 'singleuser') &&
  769:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  770:             $actiontext = $lt{'srvu'};
  771:         }
  772:         $r->print("<h3>$actiontext</h3>");
  773:         if ($env{'form.origform'} ne 'crtusername') {
  774:             if ($response) {
  775:                $r->print("\n<div>$response</div>".
  776:                          '<br clear="all" />');
  777:             }
  778:         }
  779:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  780:     }
  781: }
  782: 
  783: sub customrole_javascript {
  784:     my $js = <<"END";
  785: <script type="text/javascript">
  786: // <![CDATA[
  787: 
  788: function setCustomFields() {
  789:     if (document.docustom.customroleaction.length > 0) {
  790:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  791:             if (document.docustom.customroleaction[i].checked) {
  792:                 if (document.docustom.customroleaction[i].value == 'new') {
  793:                     document.docustom.rolename.selectedIndex = 0;
  794:                 } else {
  795:                     document.docustom.newrolename.value = '';
  796:                 }
  797:             }
  798:         }
  799:     }
  800:     return;
  801: }
  802: 
  803: function setCustomAction(caller) {
  804:     if (document.docustom.customroleaction.length > 0) {
  805:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  806:             if (document.docustom.customroleaction[i].value == caller) {
  807:                 document.docustom.customroleaction[i].checked = true;
  808:             }
  809:         }
  810:     }
  811:     setCustomFields();
  812:     return;
  813: }
  814: 
  815: // ]]>
  816: </script>
  817: END
  818:     return $js;
  819: }
  820: 
  821: sub entry_form {
  822:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  823:     my ($usertype,$inexact);
  824:     if (ref($srch) eq 'HASH') {
  825:         if (($srch->{'srchin'} eq 'dom') &&
  826:             ($srch->{'srchby'} eq 'uname') &&
  827:             ($srch->{'srchtype'} eq 'exact') &&
  828:             ($srch->{'srchdomain'} ne '') &&
  829:             ($srch->{'srchterm'} ne '')) {
  830:             my (%curr_rules,%got_rules);
  831:             my ($rules,$ruleorder) =
  832:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  833:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  834:         } else {
  835:             $inexact = 1;
  836:         }
  837:     }
  838:     my ($cancreate,$noinstd);
  839:     if ($env{'form.action'} eq 'accesslogs') {
  840:         $noinstd = 1;
  841:     } else {
  842:         $cancreate =
  843:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  844:     }
  845:     my ($userpicker,$cansearch) = 
  846:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  847:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
  848:     my $srchbutton = &mt('Search');
  849:     if ($env{'form.action'} eq 'singlestudent') {
  850:         $srchbutton = &mt('Search and Enroll');
  851:     } elsif ($env{'form.action'} eq 'accesslogs') {
  852:         $srchbutton = &mt('Search');
  853:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  854:         $srchbutton = &mt('Search or Add New User');
  855:     }
  856:     my $output;
  857:     if ($cansearch) {
  858:         $output = <<"ENDBLOCK";
  859: <form action="/adm/createuser" method="post" name="crtuser">
  860: <input type="hidden" name="action" value="$env{'form.action'}" />
  861: <input type="hidden" name="phase" value="get_user_info" />
  862: $userpicker
  863: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  864: </form>
  865: ENDBLOCK
  866:     } else {
  867:         $output = '<p>'.$userpicker.'</p>';
  868:     }
  869:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  870:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  871:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  872:         my $defdom=$env{'request.role.domain'};
  873:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
  874:         my %lt=&Apache::lonlocal::texthash(
  875:                   'enro' => 'Enroll one student',
  876:                   'enrm' => 'Enroll one member',
  877:                   'admo' => 'Add/modify a single user',
  878:                   'crea' => 'create new user if required',
  879:                   'uskn' => "username is known",
  880:                   'crnu' => 'Create a new user',
  881:                   'usr'  => 'Username',
  882:                   'dom'  => 'in domain',
  883:                   'enrl' => 'Enroll',
  884:                   'cram'  => 'Create/Modify user',
  885:         );
  886:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  887:         my ($title,$buttontext,$showresponse);
  888:         if ($env{'form.action'} eq 'singlestudent') {
  889:             if ($crstype eq 'Community') {
  890:                 $title = $lt{'enrm'};
  891:             } else {
  892:                 $title = $lt{'enro'};
  893:             }
  894:             $buttontext = $lt{'enrl'};
  895:         } else {
  896:             $title = $lt{'admo'};
  897:             $buttontext = $lt{'cram'};
  898:         }
  899:         if ($cancreate) {
  900:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  901:         } else {
  902:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  903:         }
  904:         if ($env{'form.origform'} eq 'crtusername') {
  905:             $showresponse = $responsemsg;
  906:         }
  907:         $output .= <<"ENDDOCUMENT";
  908: <br />
  909: <form action="/adm/createuser" method="post" name="crtusername">
  910: <input type="hidden" name="action" value="$env{'form.action'}" />
  911: <input type="hidden" name="phase" value="createnewuser" />
  912: <input type="hidden" name="srchtype" value="exact" />
  913: <input type="hidden" name="srchby" value="uname" />
  914: <input type="hidden" name="srchin" value="dom" />
  915: <input type="hidden" name="forcenewuser" value="1" />
  916: <input type="hidden" name="origform" value="crtusername" />
  917: <h3>$title</h3>
  918: $showresponse
  919: <table>
  920:  <tr>
  921:   <td>$lt{'usr'}:</td>
  922:   <td><input type="text" size="15" name="srchterm" /></td>
  923:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  924:   <td>&nbsp;$sellink&nbsp;</td>
  925:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  926:  </tr>
  927: </table>
  928: </form>
  929: ENDDOCUMENT
  930:     }
  931:     return $output;
  932: }
  933: 
  934: sub user_modification_js {
  935:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  936:     
  937:     return <<END;
  938: <script type="text/javascript" language="Javascript">
  939: // <![CDATA[
  940: 
  941:     $pjump_def
  942:     $dc_setcourse_code
  943: 
  944:     function dateset() {
  945:         eval("document.cu."+document.cu.pres_marker.value+
  946:             ".value=document.cu.pres_value.value");
  947:         modalWindow.close();
  948:     }
  949: 
  950:     $nondc_setsection_code
  951: // ]]>
  952: </script>
  953: END
  954: }
  955: 
  956: # =================================================================== Phase two
  957: sub print_user_selection_page {
  958:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  959:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  960:     my $sortby = $env{'form.sortby'};
  961: 
  962:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  963:         $sortby = 'lastname';
  964:     }
  965: 
  966:     my ($jsback,$elements) = &crumb_utilities();
  967: 
  968:     my $jscript = (<<ENDSCRIPT);
  969: <script type="text/javascript">
  970: // <![CDATA[
  971: function pickuser(uname,udom) {
  972:     document.usersrchform.seluname.value=uname;
  973:     document.usersrchform.seludom.value=udom;
  974:     document.usersrchform.phase.value="userpicked";
  975:     document.usersrchform.submit();
  976: }
  977: 
  978: $jsback
  979: // ]]>
  980: </script>
  981: ENDSCRIPT
  982: 
  983:     my %lt=&Apache::lonlocal::texthash(
  984:                                        'usrch'          => "User Search to add/modify roles",
  985:                                        'stusrch'        => "User Search to enroll student",
  986:                                        'memsrch'        => "User Search to enroll member",
  987:                                        'srcva'          => "Search for a user and view access log information",
  988:                                        'usrvu'          => "User Search to view user roles",
  989:                                        'usel'           => "Select a user to add/modify roles",
  990:                                        'suvr'           => "Select a user to view roles",
  991:                                        'stusel'         => "Select a user to enroll as a student",
  992:                                        'memsel'         => "Select a user to enroll as a member",
  993:                                        'vacsel'         => "Select a user to view access log",
  994:                                        'username'       => "username",
  995:                                        'domain'         => "domain",
  996:                                        'lastname'       => "last name",
  997:                                        'firstname'      => "first name",
  998:                                        'permanentemail' => "permanent e-mail",
  999:                                       );
 1000:     if ($context eq 'requestcrs') {
 1001:         $r->print('<div>');
 1002:     } else {
 1003:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1004:         my $helpitem;
 1005:         if ($env{'form.action'} eq 'singleuser') {
 1006:             $helpitem = 'Course_Change_Privileges';
 1007:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1008:             $helpitem = 'Course_Add_Student';
 1009:         }
 1010:         push (@{$brcrum},
 1011:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1012:                    text => $breadcrumb_text{'search'},
 1013:                    faq  => 282,
 1014:                    bug  => 'Instructor Interface',},
 1015:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1016:                    text => $breadcrumb_text{'userpicked'},
 1017:                    faq  => 282,
 1018:                    bug  => 'Instructor Interface',
 1019:                    help => $helpitem}
 1020:                   );
 1021:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1022:         if ($env{'form.action'} eq 'singleuser') {
 1023:             my $readonly;
 1024:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1025:                 $readonly = 1;
 1026:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1027:             } else {
 1028:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1029:             }
 1030:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1031:             if ($readonly) {
 1032:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1033:             } else {
 1034:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1035:             }
 1036:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1037:             $r->print($jscript."<b>");
 1038:             if ($crstype eq 'Community') {
 1039:                 $r->print($lt{'memsrch'});
 1040:             } else {
 1041:                 $r->print($lt{'stusrch'});
 1042:             }
 1043:             $r->print("</b><br />");
 1044:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1045:             $r->print('</form><h3>');
 1046:             if ($crstype eq 'Community') {
 1047:                 $r->print($lt{'memsel'});
 1048:             } else {
 1049:                 $r->print($lt{'stusel'});
 1050:             }
 1051:             $r->print('</h3>');
 1052:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1053:             $r->print("<b>$lt{'srcva'}</b><br />");
 1054:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1055:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1056:         }
 1057:     }
 1058:     $r->print('<form name="usersrchform" method="post" action="">'.
 1059:               &Apache::loncommon::start_data_table()."\n".
 1060:               &Apache::loncommon::start_data_table_header_row()."\n".
 1061:               ' <th> </th>'."\n");
 1062:     foreach my $field (@fields) {
 1063:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1064:                   "'".$field."'".';document.usersrchform.submit();">'.
 1065:                   $lt{$field}.'</a></th>'."\n");
 1066:     }
 1067:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1068: 
 1069:     my @sorted_users = sort {
 1070:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1071:             ||
 1072:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1073:             ||
 1074:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1075: 	    ||
 1076: 	lc($a) cmp lc($b)
 1077:         } (keys(%$srch_results));
 1078: 
 1079:     foreach my $user (@sorted_users) {
 1080:         my ($uname,$udom) = split(/:/,$user);
 1081:         my $onclick;
 1082:         if ($context eq 'requestcrs') {
 1083:             $onclick =
 1084:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1085:                                                "'$srch_results->{$user}->{firstname}',".
 1086:                                                "'$srch_results->{$user}->{lastname}',".
 1087:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1088:         } else {
 1089:             $onclick =
 1090:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1091:         }
 1092:         $r->print(&Apache::loncommon::start_data_table_row().
 1093:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1094:                   $onclick.' /></td>'.
 1095:                   '<td><tt>'.$uname.'</tt></td>'.
 1096:                   '<td><tt>'.$udom.'</tt></td>');
 1097:         foreach my $field ('lastname','firstname','permanentemail') {
 1098:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1099:         }
 1100:         $r->print(&Apache::loncommon::end_data_table_row());
 1101:     }
 1102:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1103:     if (ref($srcharray) eq 'ARRAY') {
 1104:         foreach my $item (@{$srcharray}) {
 1105:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1106:         }
 1107:     }
 1108:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1109:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1110:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1111:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1112:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1113:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1114:     if ($context eq 'requestcrs') {
 1115:         $r->print($opener_elements.'</form></div>');
 1116:     } else {
 1117:         $r->print($response.'</form>');
 1118:     }
 1119: }
 1120: 
 1121: sub print_user_query_page {
 1122:     my ($r,$caller,$brcrum) = @_;
 1123: # FIXME - this is for a network-wide name search (similar to catalog search)
 1124: # To use frames with similar behavior to catalog/portfolio search.
 1125: # To be implemented. 
 1126:     return;
 1127: }
 1128: 
 1129: sub print_user_modification_page {
 1130:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1131:         $brcrum,$showcredits) = @_;
 1132:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1133:         my $usermsg = &mt('No username and/or domain provided.');
 1134:         $env{'form.phase'} = '';
 1135: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum);
 1136:         return;
 1137:     }
 1138:     my ($form,$formname);
 1139:     if ($env{'form.action'} eq 'singlestudent') {
 1140:         $form = 'document.enrollstudent';
 1141:         $formname = 'enrollstudent';
 1142:     } else {
 1143:         $form = 'document.cu';
 1144:         $formname = 'cu';
 1145:     }
 1146:     my %abv_auth = &auth_abbrev();
 1147:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1148:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1149:     if ($uhome eq 'no_host') {
 1150:         my $usertype;
 1151:         my ($rules,$ruleorder) =
 1152:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1153:             $usertype =
 1154:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1155:                                                       \%curr_rules,\%got_rules);
 1156:         my $cancreate =
 1157:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1158:                                                    $usertype);
 1159:         if (!$cancreate) {
 1160:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1161:             my %usertypetext = (
 1162:                 official   => 'institutional',
 1163:                 unofficial => 'non-institutional',
 1164:             );
 1165:             my $response;
 1166:             if ($env{'form.origform'} eq 'crtusername') {
 1167:                 $response = '<span class="LC_warning">'.
 1168:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1169:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1170:                             '</span><br />';
 1171:             }
 1172:             $response .= '<p class="LC_warning">'
 1173:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1174:                         .' ';
 1175:             if ($context eq 'domain') {
 1176:                 $response .= &mt('Please contact a [_1] for assistance.',
 1177:                                  &Apache::lonnet::plaintext('dc'));
 1178:             } else {
 1179:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1180:                                 ,'<a href="'.$helplink.'">','</a>');
 1181:             }
 1182:             $response .= '</p><br />';
 1183:             $env{'form.phase'} = '';
 1184:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum);
 1185:             return;
 1186:         }
 1187:         $newuser = 1;
 1188:         my $checkhash;
 1189:         my $checks = { 'username' => 1 };
 1190:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1191:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1192:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1193:         if (ref($alerts{'username'}) eq 'HASH') {
 1194:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1195:                 my $domdesc =
 1196:                     &Apache::lonnet::domain($ccdomain,'description');
 1197:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1198:                     my $userchkmsg;
 1199:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1200:                         $userchkmsg = 
 1201:                             &Apache::loncommon::instrule_disallow_msg('username',
 1202:                                                                  $domdesc,1).
 1203:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1204:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1205:                             'username');
 1206:                     }
 1207:                     $env{'form.phase'} = '';
 1208:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum);
 1209:                     return;
 1210:                 }
 1211:             }
 1212:         }
 1213:     } else {
 1214:         $newuser = 0;
 1215:     }
 1216:     if ($response) {
 1217:         $response = '<br />'.$response;
 1218:     }
 1219: 
 1220:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1221:     my $dc_setcourse_code = '';
 1222:     my $nondc_setsection_code = '';                                        
 1223:     my %loaditem;
 1224: 
 1225:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1226: 
 1227:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1228:                                $groupslist,$newuser,$formname,\%loaditem);
 1229:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1230:     my $helpitem = 'Course_Change_Privileges';
 1231:     if ($env{'form.action'} eq 'singlestudent') {
 1232:         $helpitem = 'Course_Add_Student';
 1233:     }
 1234:     push (@{$brcrum},
 1235:         {href => "javascript:backPage($form)",
 1236:          text => $breadcrumb_text{'search'},
 1237:          faq  => 282,
 1238:          bug  => 'Instructor Interface',});
 1239:     if ($env{'form.phase'} eq 'userpicked') {
 1240:        push(@{$brcrum},
 1241:               {href => "javascript:backPage($form,'get_user_info','select')",
 1242:                text => $breadcrumb_text{'userpicked'},
 1243:                faq  => 282,
 1244:                bug  => 'Instructor Interface',});
 1245:     }
 1246:     push(@{$brcrum},
 1247:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1248:              text => $breadcrumb_text{'modify'},
 1249:              faq  => 282,
 1250:              bug  => 'Instructor Interface',
 1251:              help => $helpitem});
 1252:     my $args = {'add_entries'           => \%loaditem,
 1253:                 'bread_crumbs'          => $brcrum,
 1254:                 'bread_crumbs_component' => 'User Management'};
 1255:     if ($env{'form.popup'}) {
 1256:         $args->{'no_nav_bar'} = 1;
 1257:     }
 1258:     my $start_page =
 1259:         &Apache::loncommon::start_page('User Management',$js,$args);
 1260: 
 1261:     my $forminfo =<<"ENDFORMINFO";
 1262: <form action="/adm/createuser" method="post" name="$formname">
 1263: <input type="hidden" name="phase" value="update_user_data" />
 1264: <input type="hidden" name="ccuname" value="$ccuname" />
 1265: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1266: <input type="hidden" name="pres_value"  value="" />
 1267: <input type="hidden" name="pres_type"   value="" />
 1268: <input type="hidden" name="pres_marker" value="" />
 1269: ENDFORMINFO
 1270:     my (%inccourses,$roledom,$defaultcredits);
 1271:     if ($context eq 'course') {
 1272:         $inccourses{$env{'request.course.id'}}=1;
 1273:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1274:         if ($showcredits) {
 1275:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1276:         }
 1277:     } elsif ($context eq 'author') {
 1278:         $roledom = $env{'request.role.domain'};
 1279:     } elsif ($context eq 'domain') {
 1280:         foreach my $key (keys(%env)) {
 1281:             $roledom = $env{'request.role.domain'};
 1282:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1283:                 $inccourses{$1.'_'.$2}=1;
 1284:             }
 1285:         }
 1286:     } else {
 1287:         foreach my $key (keys(%env)) {
 1288: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1289: 	        $inccourses{$1.'_'.$2}=1;
 1290:             }
 1291:         }
 1292:     }
 1293:     my $title = '';
 1294:     if ($newuser) {
 1295:         my ($portfolioform,$domroleform);
 1296:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1297:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1298:             # Current user has quota or user tools modification privileges
 1299:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1300:         }
 1301:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1302:             ($ccdomain eq $env{'request.role.domain'})) {
 1303:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1304:         }
 1305:         &initialize_authen_forms($ccdomain,$formname);
 1306:         my %lt=&Apache::lonlocal::texthash(
 1307:                 'lg'             => 'Login Data',
 1308:                 'hs'             => "Home Server",
 1309:         );
 1310: 	$r->print(<<ENDTITLE);
 1311: $start_page
 1312: $response
 1313: $forminfo
 1314: <script type="text/javascript" language="Javascript">
 1315: // <![CDATA[
 1316: $loginscript
 1317: // ]]>
 1318: </script>
 1319: <input type='hidden' name='makeuser' value='1' />
 1320: ENDTITLE
 1321:         if ($env{'form.action'} eq 'singlestudent') {
 1322:             if ($crstype eq 'Community') {
 1323:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1324:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1325:             } else {
 1326:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1327:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1328:             }
 1329:         } else {
 1330:                 $title = &mt('Create New User [_1] in domain [_2]',
 1331:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1332:         }
 1333:         $r->print('<h2>'.$title.'</h2>'."\n");
 1334:         $r->print('<div class="LC_left_float">');
 1335:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1336:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1337:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1338:         my ($home_server_pick,$numlib) = 
 1339:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1340:                                                       'default','hide');
 1341:         if ($numlib > 1) {
 1342:             $r->print("
 1343: <br />
 1344: $lt{'hs'}: $home_server_pick
 1345: <br />");
 1346:         } else {
 1347:             $r->print($home_server_pick);
 1348:         }
 1349:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1350:             $r->print('<br /><h3>'.
 1351:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1352:                       &Apache::loncommon::start_data_table().
 1353:                       &build_tools_display($ccuname,$ccdomain,
 1354:                                            'requestcourses').
 1355:                       &Apache::loncommon::end_data_table());
 1356:         }
 1357:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1358:                   $lt{'lg'}.'</h3>');
 1359:         my ($fixedauth,$varauth,$authmsg); 
 1360:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1361:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1362:             my ($rules,$ruleorder) = 
 1363:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1364:             if (ref($rules) eq 'HASH') {
 1365:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1366:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1367:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1368:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1369:                     } else { 
 1370:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1371:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1372:                         if ($authtype =~ /^krb(4|5)$/) {
 1373:                             my $ver = $1;
 1374:                             if ($authparm ne '') {
 1375:                                 $fixedauth = <<"KERB"; 
 1376: <input type="hidden" name="login" value="krb" />
 1377: <input type="hidden" name="krbver" value="$ver" />
 1378: <input type="hidden" name="krbarg" value="$authparm" />
 1379: KERB
 1380:                             }
 1381:                         } else {
 1382:                             $fixedauth = 
 1383: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1384:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1385:                                 $fixedauth .=    
 1386: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1387:                             } else {
 1388:                                 if ($authtype eq 'int') {
 1389:                                     $varauth = '<br />'.
 1390: &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>';
 1391:                                 } elsif ($authtype eq 'loc') {
 1392:                                     $varauth = '<br />'.
 1393: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1394:                                 } else {
 1395:                                     $varauth =
 1396: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1397:                                 }
 1398:                             }
 1399:                         }
 1400:                     }
 1401:                 } else {
 1402:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1403:                 }
 1404:             }
 1405:             if ($authmsg) {
 1406:                 $r->print(<<ENDAUTH);
 1407: $fixedauth
 1408: $authmsg
 1409: $varauth
 1410: ENDAUTH
 1411:             }
 1412:         } else {
 1413:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1414:         }
 1415:         $r->print($portfolioform.$domroleform);
 1416:         if ($env{'form.action'} eq 'singlestudent') {
 1417:             $r->print(&date_sections_select($context,$newuser,$formname,
 1418:                                             $permission,$crstype,$ccuname,
 1419:                                             $ccdomain,$showcredits));
 1420:         }
 1421:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1422:     } else { # user already exists
 1423: 	$r->print($start_page.$forminfo);
 1424:         if ($env{'form.action'} eq 'singlestudent') {
 1425:             if ($crstype eq 'Community') {
 1426:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1427:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1428:             } else {
 1429:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1430:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1431:             }
 1432:         } else {
 1433:             if ($permission->{'cusr'}) {
 1434:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1435:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1436:             } else {
 1437:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1438:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1439:             }
 1440:         }
 1441:         $r->print('<h2>'.$title.'</h2>'."\n");
 1442:         $r->print('<div class="LC_left_float">');
 1443:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1444:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1445:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1446:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1447:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1448:                       &Apache::loncommon::start_data_table());
 1449:             if ($env{'request.role.domain'} eq $ccdomain) {
 1450:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1451:             } else {
 1452:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1453:                                                   $env{'request.role.domain'}));
 1454:             }
 1455:             $r->print(&Apache::loncommon::end_data_table());
 1456:         }
 1457:         $r->print('</div>');
 1458:         my @order = ('auth','quota','tools','requestauthor');
 1459:         my %user_text;
 1460:         my ($isadv,$isauthor) = 
 1461:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1462:         if ((!$isauthor) && 
 1463:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1464:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1465:              ($env{'request.role.domain'} eq $ccdomain)) {
 1466:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1467:         }
 1468:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
 1469:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1470:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1471:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1472:             # Current user has quota modification privileges
 1473:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1474:         }
 1475:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1476:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1477:                 my %lt=&Apache::lonlocal::texthash(
 1478:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1479:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1480:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1481:                 );
 1482:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1483: <h3>$lt{'dska'}</h3>
 1484: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1485: ENDNOPORTPRIV
 1486:             }
 1487:         }
 1488:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1489:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1490:                 my %lt=&Apache::lonlocal::texthash(
 1491:                     'utav'  => "User Tools Availability",
 1492:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1493:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1494:                 );
 1495:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1496: <h3>$lt{'utav'}</h3>
 1497: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1498: ENDNOTOOLSPRIV
 1499:             }
 1500:         }
 1501:         my $gotdiv = 0; 
 1502:         foreach my $item (@order) {
 1503:             if ($user_text{$item} ne '') {
 1504:                 unless ($gotdiv) {
 1505:                     $r->print('<div class="LC_left_float">');
 1506:                     $gotdiv = 1;
 1507:                 }
 1508:                 $r->print('<br />'.$user_text{$item});
 1509:             }
 1510:         }
 1511:         if ($env{'form.action'} eq 'singlestudent') {
 1512:             unless ($gotdiv) {
 1513:                 $r->print('<div class="LC_left_float">');
 1514:             }
 1515:             my $credits;
 1516:             if ($showcredits) {
 1517:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1518:                 if ($credits eq '') {
 1519:                     $credits = $defaultcredits;
 1520:                 }
 1521:             }
 1522:             $r->print(&date_sections_select($context,$newuser,$formname,
 1523:                                             $permission,$crstype,$ccuname,
 1524:                                             $ccdomain,$showcredits));
 1525:         }
 1526:         if ($gotdiv) {
 1527:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1528:         }
 1529:         my $statuses;
 1530:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1531:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1532:             $statuses = ['active'];
 1533:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1534:                  ($env{'request.course.sec'} &&
 1535:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1536:             $statuses = ['active'];
 1537:         }
 1538:         if ($env{'form.action'} ne 'singlestudent') {
 1539:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1540:                                     $roledom,$crstype,$showcredits,$statuses);
 1541:         }
 1542:     } ## End of new user/old user logic
 1543:     if ($env{'form.action'} eq 'singlestudent') {
 1544:         my $btntxt;
 1545:         if ($crstype eq 'Community') {
 1546:             $btntxt = &mt('Enroll Member');
 1547:         } else {
 1548:             $btntxt = &mt('Enroll Student');
 1549:         }
 1550:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1551:     } elsif ($permission->{'cusr'}) {
 1552:         $r->print('<div class="LC_left_float">'.
 1553:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1554:         my $addrolesdisplay = 0;
 1555:         if ($context eq 'domain' || $context eq 'author') {
 1556:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1557:         }
 1558:         if ($context eq 'domain') {
 1559:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1560:             if (!$addrolesdisplay) {
 1561:                 $addrolesdisplay = $add_domainroles;
 1562:             }
 1563:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1564:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1565:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1566:         } elsif ($context eq 'author') {
 1567:             if ($addrolesdisplay) {
 1568:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1569:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1570:                 if ($newuser) {
 1571:                     $r->print(' onclick="auth_check()" \>'."\n");
 1572:                 } else {
 1573:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1574:                 }
 1575:             } else {
 1576:                 $r->print('</fieldset></div>'.
 1577:                           '<div class="LC_clear_float_footer"></div>'.
 1578:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1579:                           &mt('Back to previous page').'</a>');
 1580:             }
 1581:         } else {
 1582:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1583:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1584:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1585:         }
 1586:     }
 1587:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1588:     $r->print('<input type="hidden" name="currstate" value="" />');
 1589:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1590:     return;
 1591: }
 1592: 
 1593: sub singleuser_breadcrumb {
 1594:     my ($crstype,$context,$domain) = @_;
 1595:     my %breadcrumb_text;
 1596:     if ($env{'form.action'} eq 'singlestudent') {
 1597:         if ($crstype eq 'Community') {
 1598:             $breadcrumb_text{'search'} = 'Enroll a member';
 1599:         } else {
 1600:             $breadcrumb_text{'search'} = 'Enroll a student';
 1601:         }
 1602:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1603:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1604:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1605:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1606:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1607:         $breadcrumb_text{'activity'} = 'Activity';
 1608:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1609:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1610:         $breadcrumb_text{'search'} = "View user's roles";
 1611:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1612:         $breadcrumb_text{'modify'} = 'User roles';
 1613:     } else {
 1614:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1615:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1616:         $breadcrumb_text{'modify'} = 'Set user role';
 1617:     }
 1618:     return %breadcrumb_text;
 1619: }
 1620: 
 1621: sub date_sections_select {
 1622:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1623:         $showcredits) = @_;
 1624:     my $credits;
 1625:     if ($showcredits) {
 1626:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1627:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1628:         if ($credits eq '') {
 1629:             $credits = $defaultcredits;
 1630:         }
 1631:     }
 1632:     my $cid = $env{'request.course.id'};
 1633:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1634:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1635:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1636:                                                   undef,$formname,$permission);
 1637:     my $rowtitle = 'Section';
 1638:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1639:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1640:                                               $permission,$context,'',$crstype,
 1641:                                               $showcredits,$credits);
 1642:     my $output = $date_table.$secbox;
 1643:     return $output;
 1644: }
 1645: 
 1646: sub validation_javascript {
 1647:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1648:         $loaditem) = @_;
 1649:     my $dc_setcourse_code = '';
 1650:     my $nondc_setsection_code = '';
 1651:     if ($context eq 'domain') {
 1652:         my $dcdom = $env{'request.role.domain'};
 1653:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1654:         $dc_setcourse_code = 
 1655:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1656:     } else {
 1657:         my $checkauth; 
 1658:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1659:             $checkauth = 1;
 1660:         }
 1661:         if ($context eq 'course') {
 1662:             $nondc_setsection_code =
 1663:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1664:                                                               undef,$checkauth,
 1665:                                                               $crstype);
 1666:         }
 1667:         if ($checkauth) {
 1668:             $nondc_setsection_code .= 
 1669:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1670:         }
 1671:     }
 1672:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1673:                                    $nondc_setsection_code,$groupslist);
 1674:     my ($jsback,$elements) = &crumb_utilities();
 1675:     $js .= "\n".
 1676:            '<script type="text/javascript">'."\n".
 1677:            '// <![CDATA['."\n".
 1678:            $jsback."\n".
 1679:            '// ]]>'."\n".
 1680:            '</script>'."\n";
 1681:     return $js;
 1682: }
 1683: 
 1684: sub display_existing_roles {
 1685:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1686:         $showcredits,$statuses) = @_;
 1687:     my $now=time;
 1688:     my $showall = 1;
 1689:     my ($showexpired,$showactive);
 1690:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1691:         $showall = 0;
 1692:         if (grep(/^expired$/,@{$statuses})) {
 1693:             $showexpired = 1;
 1694:         }
 1695:         if (grep(/^active$/,@{$statuses})) {
 1696:             $showactive = 1;
 1697:         }
 1698:         if ($showexpired && $showactive) {
 1699:             $showall = 1;
 1700:         }
 1701:     }
 1702:     my %lt=&Apache::lonlocal::texthash(
 1703:                     'rer'  => "Existing Roles",
 1704:                     'rev'  => "Revoke",
 1705:                     'del'  => "Delete",
 1706:                     'ren'  => "Re-Enable",
 1707:                     'rol'  => "Role",
 1708:                     'ext'  => "Extent",
 1709:                     'crd'  => "Credits",
 1710:                     'sta'  => "Start",
 1711:                     'end'  => "End",
 1712:                                        );
 1713:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1714:     if ($context eq 'course' || $context eq 'author') {
 1715:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1716:         my %roleshash = 
 1717:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1718:                               ['active','previous','future'],\@roles,$roledom,1);
 1719:         foreach my $key (keys(%roleshash)) {
 1720:             my ($start,$end) = split(':',$roleshash{$key});
 1721:             next if ($start eq '-1' || $end eq '-1');
 1722:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1723:             if ($context eq 'course') {
 1724:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1725:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1726:             } elsif ($context eq 'author') {
 1727:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1728:             }
 1729:             my ($newkey,$newvalue,$newrole);
 1730:             $newkey = '/'.$rdom.'/'.$rnum;
 1731:             if ($sec ne '') {
 1732:                 $newkey .= '/'.$sec;
 1733:             }
 1734:             $newvalue = $role;
 1735:             if ($role =~ /^cr/) {
 1736:                 $newrole = 'cr';
 1737:             } else {
 1738:                 $newrole = $role;
 1739:             }
 1740:             $newkey .= '_'.$newrole;
 1741:             if ($start ne '' && $end ne '') {
 1742:                 $newvalue .= '_'.$end.'_'.$start;
 1743:             } elsif ($end ne '') {
 1744:                 $newvalue .= '_'.$end;
 1745:             }
 1746:             $rolesdump{$newkey} = $newvalue;
 1747:         }
 1748:     } else {
 1749:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1750:     }
 1751:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1752:     my ($tmp) = keys(%rolesdump);
 1753:     return if ($tmp =~ /^(con_lost|error)/i);
 1754:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1755:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1756:                                 return $a1 cmp $b1;
 1757:                             } keys(%rolesdump)) {
 1758:         next if ($area =~ /^rolesdef/);
 1759:         my $envkey=$area;
 1760:         my $role = $rolesdump{$area};
 1761:         my $thisrole=$area;
 1762:         $area =~ s/\_\w\w$//;
 1763:         my ($role_code,$role_end_time,$role_start_time) =
 1764:             split(/_/,$role);
 1765:         my $active=1;
 1766:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1767:         if ($active) {
 1768:             next unless($showall || $showactive);
 1769:         } else {
 1770:             next unless($showall || $showexpired);
 1771:         }
 1772: # Is this a custom role? Get role owner and title.
 1773:         my ($croleudom,$croleuname,$croletitle)=
 1774:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1775:         my $allowed=0;
 1776:         my $delallowed=0;
 1777:         my $sortkey=$role_code;
 1778:         my $class='Unknown';
 1779:         my $credits='';
 1780:         my $csec;
 1781:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1782:             $class='Course';
 1783:             my ($coursedom,$coursedir) = ($1,$2);
 1784:             my $cid = $1.'_'.$2;
 1785:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1786:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1787:             my %coursedata=
 1788:                 &Apache::lonnet::coursedescription($cid);
 1789:             if ($coursedir =~ /^$match_community$/) {
 1790:                 $class='Community';
 1791:             }
 1792:             $sortkey.="\0$coursedom";
 1793:             my $carea;
 1794:             if (defined($coursedata{'description'})) {
 1795:                 $carea=$coursedata{'description'}.
 1796:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1797:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1798:                 $sortkey.="\0".$coursedata{'description'};
 1799:             } else {
 1800:                 if ($class eq 'Community') {
 1801:                     $carea=&mt('Unavailable community').': '.$area;
 1802:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1803:                 } else {
 1804:                     $carea=&mt('Unavailable course').': '.$area;
 1805:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1806:                 }
 1807:             }
 1808:             $sortkey.="\0$coursedir";
 1809:             $inccourses->{$cid}=1;
 1810:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1811:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1812:                 $credits =
 1813:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1814:                                       $coursedom,$coursedir);
 1815:                 if ($credits eq '') {
 1816:                     $credits = $defaultcredits;
 1817:                 }
 1818:             }
 1819:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1820:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1821:                 $allowed=1;
 1822:             }
 1823:             unless ($allowed) {
 1824:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1825:                 if ($isowner) {
 1826:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1827:                         $allowed = 1;
 1828:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1829:                         $allowed = 1;
 1830:                     }
 1831:                 }
 1832:             } 
 1833:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1834:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1835:                 $delallowed=1;
 1836:             }
 1837: # - custom role. Needs more info, too
 1838:             if ($croletitle) {
 1839:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1840:                     $allowed=1;
 1841:                     $thisrole.='.'.$role_code;
 1842:                 }
 1843:             }
 1844:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1845:                 $csec = $2;
 1846:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1847:                 $sortkey.="\0$csec";
 1848:                 if (!$allowed) {
 1849:                     if ($env{'request.course.sec'} eq $csec) {
 1850:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1851:                             $allowed = 1;
 1852:                         }
 1853:                     }
 1854:                 }
 1855:             }
 1856:             $area=$carea;
 1857:         } else {
 1858:             $sortkey.="\0".$area;
 1859:             # Determine if current user is able to revoke privileges
 1860:             if ($area=~m{^/($match_domain)/}) {
 1861:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1862:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1863:                    $allowed=1;
 1864:                 }
 1865:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1866:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1867:                     ($role_code ne 'dc')) {
 1868:                     $delallowed=1;
 1869:                 }
 1870:             } else {
 1871:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1872:                     $allowed=1;
 1873:                 }
 1874:             }
 1875:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1876:                 $class='Authoring Space';
 1877:             } elsif ($role_code eq 'su') {
 1878:                 $class='System';
 1879:             } else {
 1880:                 $class='Domain';
 1881:             }
 1882:         }
 1883:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1884:             $area=~m{/($match_domain)/($match_username)};
 1885:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1886:                 $allowed=1;
 1887:             } else {
 1888:                 $allowed=0;
 1889:             }
 1890:         }
 1891:         my $row = '';
 1892:         if ($showall) {
 1893:             $row.= '<td>';
 1894:             if (($active) && ($allowed)) {
 1895:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1896:             } else {
 1897:                 if ($active) {
 1898:                     $row.='&nbsp;';
 1899:                 } else {
 1900:                     $row.=&mt('expired or revoked');
 1901:                 }
 1902:             }
 1903:             $row.='</td><td>';
 1904:             if ($allowed && !$active) {
 1905:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1906:             } else {
 1907:                 $row.='&nbsp;';
 1908:             }
 1909:             $row.='</td><td>';
 1910:             if ($delallowed) {
 1911:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1912:             } else {
 1913:                 $row.='&nbsp;';
 1914:             }
 1915:             $row.= '</td>';
 1916:         }
 1917:         my $plaintext='';
 1918:         if (!$croletitle) {
 1919:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1920:             if (($showcredits) && ($credits ne '')) {
 1921:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1922:                               '<span class="LC_fontsize_small">'.
 1923:                               &mt('Credits: [_1]',$credits).
 1924:                               '</span></span>';
 1925:             }
 1926:         } else {
 1927:             $plaintext=
 1928:                 &mt('Custom role [_1][_2]defined by [_3]',
 1929:                         '"'.$croletitle.'"',
 1930:                         '<br />',
 1931:                         $croleuname.':'.$croleudom);
 1932:         }
 1933:         $row.= '<td>'.$plaintext.'</td>'.
 1934:                '<td>'.$area.'</td>'.
 1935:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1936:                                             : '&nbsp;' ).'</td>'.
 1937:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1938:                                             : '&nbsp;' ).'</td>';
 1939:         $sortrole{$sortkey}=$envkey;
 1940:         $roletext{$envkey}=$row;
 1941:         $roleclass{$envkey}=$class;
 1942:         if ($allowed) {
 1943:             $rolepriv{$envkey}='edit';
 1944:         } else {
 1945:             if ($context eq 'domain') {
 1946:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1947:                     ($envkey=~m{^/$ccdomain/})) {
 1948:                     $rolepriv{$envkey}='view';
 1949:                 }
 1950:             } elsif ($context eq 'course') {
 1951:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1952:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1953:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 1954:                     $rolepriv{$envkey}='view';
 1955:                 }
 1956:             }
 1957:         }
 1958:     } # end of foreach        (table building loop)
 1959: 
 1960:     my $rolesdisplay = 0;
 1961:     my %output = ();
 1962:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 1963:         $output{$type} = '';
 1964:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1965:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 1966:                  $output{$type}.=
 1967:                       &Apache::loncommon::start_data_table_row().
 1968:                       $roletext{$sortrole{$which}}.
 1969:                       &Apache::loncommon::end_data_table_row();
 1970:             }
 1971:         }
 1972:         unless($output{$type} eq '') {
 1973:             $output{$type} = '<tr class="LC_info_row">'.
 1974:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1975:                       $output{$type};
 1976:             $rolesdisplay = 1;
 1977:         }
 1978:     }
 1979:     if ($rolesdisplay == 1) {
 1980:         my $contextrole='';
 1981:         if ($env{'request.course.id'}) {
 1982:             if (&Apache::loncommon::course_type() eq 'Community') {
 1983:                 $contextrole = &mt('Existing Roles in this Community');
 1984:             } else {
 1985:                 $contextrole = &mt('Existing Roles in this Course');
 1986:             }
 1987:         } elsif ($env{'request.role'} =~ /^au\./) {
 1988:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 1989:         } else {
 1990:             if ($showall) {
 1991:                 $contextrole = &mt('Existing Roles in this Domain');
 1992:             } elsif ($showactive) {
 1993:                 $contextrole = &mt('Unexpired Roles in this Domain');
 1994:             } elsif ($showexpired) {
 1995:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 1996:             }
 1997:         }
 1998:         $r->print('<div class="LC_left_float">'.
 1999: '<fieldset><legend>'.$contextrole.'</legend>'.
 2000: &Apache::loncommon::start_data_table("LC_createuser").
 2001: &Apache::loncommon::start_data_table_header_row());
 2002:         if ($showall) {
 2003:             $r->print(
 2004: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2005:             );
 2006:         } elsif ($showexpired) {
 2007:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2008:         }
 2009:         $r->print(
 2010: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2011: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2012: &Apache::loncommon::end_data_table_header_row());
 2013:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2014:             if ($output{$type}) {
 2015:                 $r->print($output{$type}."\n");
 2016:             }
 2017:         }
 2018:         $r->print(&Apache::loncommon::end_data_table().
 2019:                   '</fieldset></div>');
 2020:     }
 2021:     return;
 2022: }
 2023: 
 2024: sub new_coauthor_roles {
 2025:     my ($r,$ccuname,$ccdomain) = @_;
 2026:     my $addrolesdisplay = 0;
 2027:     #
 2028:     # Co-Author
 2029:     #
 2030:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2031:                                           $env{'request.role.domain'}) &&
 2032:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2033:         # No sense in assigning co-author role to yourself
 2034:         $addrolesdisplay = 1;
 2035:         my $cuname=$env{'user.name'};
 2036:         my $cudom=$env{'request.role.domain'};
 2037:         my %lt=&Apache::lonlocal::texthash(
 2038:                     'cs'   => "Authoring Space",
 2039:                     'act'  => "Activate",
 2040:                     'rol'  => "Role",
 2041:                     'ext'  => "Extent",
 2042:                     'sta'  => "Start",
 2043:                     'end'  => "End",
 2044:                     'cau'  => "Co-Author",
 2045:                     'caa'  => "Assistant Co-Author",
 2046:                     'ssd'  => "Set Start Date",
 2047:                     'sed'  => "Set End Date"
 2048:                                        );
 2049:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2050:                   &Apache::loncommon::start_data_table()."\n".
 2051:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2052:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2053:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2054:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2055:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2056:                   &Apache::loncommon::start_data_table_row().'
 2057:            <td>
 2058:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2059:            </td>
 2060:            <td>'.$lt{'cau'}.'</td>
 2061:            <td>'.$cudom.'_'.$cuname.'</td>
 2062:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2063:              <a href=
 2064: "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>
 2065: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2066: <a href=
 2067: "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".
 2068:               &Apache::loncommon::end_data_table_row()."\n".
 2069:               &Apache::loncommon::start_data_table_row()."\n".
 2070: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2071: <td>'.$lt{'caa'}.'</td>
 2072: <td>'.$cudom.'_'.$cuname.'</td>
 2073: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2074: <a href=
 2075: "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>
 2076: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2077: <a href=
 2078: "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".
 2079:              &Apache::loncommon::end_data_table_row()."\n".
 2080:              &Apache::loncommon::end_data_table());
 2081:     } elsif ($env{'request.role'} =~ /^au\./) {
 2082:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2083:                                                 $env{'request.role.domain'}))) {
 2084:             $r->print('<span class="LC_error">'.
 2085:                       &mt('You do not have privileges to assign co-author roles.').
 2086:                       '</span>');
 2087:         } elsif (($env{'user.name'} eq $ccuname) &&
 2088:              ($env{'user.domain'} eq $ccdomain)) {
 2089:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2090:         }
 2091:     }
 2092:     return $addrolesdisplay;;
 2093: }
 2094: 
 2095: sub new_domain_roles {
 2096:     my ($r,$ccdomain) = @_;
 2097:     my $addrolesdisplay = 0;
 2098:     #
 2099:     # Domain level
 2100:     #
 2101:     my $num_domain_level = 0;
 2102:     my $domaintext =
 2103:     '<h4>'.&mt('Domain Level').'</h4>'.
 2104:     &Apache::loncommon::start_data_table().
 2105:     &Apache::loncommon::start_data_table_header_row().
 2106:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2107:     &mt('Extent').'</th>'.
 2108:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2109:     &Apache::loncommon::end_data_table_header_row();
 2110:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2111:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2112:         foreach my $role (@allroles) {
 2113:             next if ($role eq 'ad');
 2114:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2115:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2116:                my $plrole=&Apache::lonnet::plaintext($role);
 2117:                my %lt=&Apache::lonlocal::texthash(
 2118:                     'ssd'  => "Set Start Date",
 2119:                     'sed'  => "Set End Date"
 2120:                                        );
 2121:                $num_domain_level ++;
 2122:                $domaintext .=
 2123: &Apache::loncommon::start_data_table_row().
 2124: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2125: <td>'.$plrole.'</td>
 2126: <td>'.$thisdomain.'</td>
 2127: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2128: <a href=
 2129: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2130: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2131: <a href=
 2132: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2133: &Apache::loncommon::end_data_table_row();
 2134:             }
 2135:         }
 2136:     }
 2137:     $domaintext.= &Apache::loncommon::end_data_table();
 2138:     if ($num_domain_level > 0) {
 2139:         $r->print($domaintext);
 2140:         $addrolesdisplay = 1;
 2141:     }
 2142:     return $addrolesdisplay;
 2143: }
 2144: 
 2145: sub user_authentication {
 2146:     my ($ccuname,$ccdomain,$formname) = @_;
 2147:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2148:     my $outcome;
 2149:     my %lt=&Apache::lonlocal::texthash(
 2150:                    'err'   => "ERROR",
 2151:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2152:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2153:                    'sldb'  => "Please specify login data below",
 2154:                    'ld'    => "Login Data"
 2155:     );
 2156:     # Check for a bad authentication type
 2157:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2158:         # bad authentication scheme
 2159:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2160:             &initialize_authen_forms($ccdomain,$formname);
 2161: 
 2162:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2163:             $outcome = <<ENDBADAUTH;
 2164: <script type="text/javascript" language="Javascript">
 2165: // <![CDATA[
 2166: $loginscript
 2167: // ]]>
 2168: </script>
 2169: <span class="LC_error">$lt{'err'}:
 2170: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2171: <h3>$lt{'ld'}</h3>
 2172: $choices
 2173: ENDBADAUTH
 2174:         } else {
 2175:             # This user is not allowed to modify the user's
 2176:             # authentication scheme, so just notify them of the problem
 2177:             $outcome = <<ENDBADAUTH;
 2178: <span class="LC_error"> $lt{'err'}: 
 2179: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2180: </span>
 2181: ENDBADAUTH
 2182:         }
 2183:     } else { # Authentication type is valid
 2184:         
 2185:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2186:         my ($authformcurrent,$can_modify,@authform_others) =
 2187:             &modify_login_block($ccdomain,$currentauth);
 2188:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2189:             # Current user has login modification privileges
 2190:             $outcome =
 2191:                        '<script type="text/javascript" language="Javascript">'."\n".
 2192:                        '// <![CDATA['."\n".
 2193:                        $loginscript."\n".
 2194:                        '// ]]>'."\n".
 2195:                        '</script>'."\n".
 2196:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2197:                        &Apache::loncommon::start_data_table().
 2198:                        &Apache::loncommon::start_data_table_row().
 2199:                        '<td>'.$authformnop;
 2200:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2201:                 $outcome .= '</td>'."\n".
 2202:                             &Apache::loncommon::end_data_table_row().
 2203:                             &Apache::loncommon::start_data_table_row().
 2204:                             '<td>'.$authformcurrent.'</td>'.
 2205:                             &Apache::loncommon::end_data_table_row()."\n";
 2206:             } else {
 2207:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2208:                             &Apache::loncommon::end_data_table_row()."\n";
 2209:             }
 2210:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2211:                 foreach my $item (@authform_others) { 
 2212:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2213:                                 '<td>'.$item.'</td>'.
 2214:                                 &Apache::loncommon::end_data_table_row()."\n";
 2215:                 }
 2216:             }
 2217:             $outcome .= &Apache::loncommon::end_data_table();
 2218:         } else {
 2219:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2220:                 # Current user has rights to view domain preferences for user's domain
 2221:                 my $result;
 2222:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2223:                     my ($krbver,$krbrealm) = ($1,$2);
 2224:                     if ($krbrealm eq '') {
 2225:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2226:                     } else {
 2227:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2228:                                       $krbrealm,$krbver);
 2229:                     }
 2230:                 } elsif ($currentauth =~ /^internal:/) {
 2231:                     $result = &mt('Currently internally authenticated.');
 2232:                 } elsif ($currentauth =~ /^localauth:/) {
 2233:                     $result = &mt('Currently using local (institutional) authentication.');
 2234:                 } elsif ($currentauth =~ /^unix:/) {
 2235:                     $result = &mt('Currently Filesystem Authenticated.');
 2236:                 }
 2237:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2238:                            &Apache::loncommon::start_data_table().
 2239:                            &Apache::loncommon::start_data_table_row().
 2240:                            '<td>'.$result.'</td>'.
 2241:                            &Apache::loncommon::end_data_table_row()."\n".
 2242:                            &Apache::loncommon::end_data_table();
 2243:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2244:                 my %lt=&Apache::lonlocal::texthash(
 2245:                            'ccld'  => "Change Current Login Data",
 2246:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2247:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2248:                 );
 2249:                 $outcome .= <<ENDNOPRIV;
 2250: <h3>$lt{'ccld'}</h3>
 2251: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2252: <input type="hidden" name="login" value="nochange" />
 2253: ENDNOPRIV
 2254:             }
 2255:         }
 2256:     }  ## End of "check for bad authentication type" logic
 2257:     return $outcome;
 2258: }
 2259: 
 2260: sub modify_login_block {
 2261:     my ($dom,$currentauth) = @_;
 2262:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2263:     my ($authnum,%can_assign) =
 2264:         &Apache::loncommon::get_assignable_auth($dom);
 2265:     my ($authformcurrent,@authform_others,$show_override_msg);
 2266:     if ($currentauth=~/^krb(4|5):/) {
 2267:         $authformcurrent=$authformkrb;
 2268:         if ($can_assign{'int'}) {
 2269:             push(@authform_others,$authformint);
 2270:         }
 2271:         if ($can_assign{'loc'}) {
 2272:             push(@authform_others,$authformloc);
 2273:         }
 2274:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2275:             $show_override_msg = 1;
 2276:         }
 2277:     } elsif ($currentauth=~/^internal:/) {
 2278:         $authformcurrent=$authformint;
 2279:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2280:             push(@authform_others,$authformkrb);
 2281:         }
 2282:         if ($can_assign{'loc'}) {
 2283:             push(@authform_others,$authformloc);
 2284:         }
 2285:         if ($can_assign{'int'}) {
 2286:             $show_override_msg = 1;
 2287:         }
 2288:     } elsif ($currentauth=~/^unix:/) {
 2289:         $authformcurrent=$authformfsys;
 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:             push(@authform_others,$authformloc);
 2298:         }
 2299:         if ($can_assign{'fsys'}) {
 2300:             $show_override_msg = 1;
 2301:         }
 2302:     } elsif ($currentauth=~/^localauth:/) {
 2303:         $authformcurrent=$authformloc;
 2304:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2305:             push(@authform_others,$authformkrb);
 2306:         }
 2307:         if ($can_assign{'int'}) {
 2308:             push(@authform_others,$authformint);
 2309:         }
 2310:         if ($can_assign{'loc'}) {
 2311:             $show_override_msg = 1;
 2312:         }
 2313:     }
 2314:     if ($show_override_msg) {
 2315:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2316:                            '</td></tr>'."\n".
 2317:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2318:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2319:                            '<td align="right"><span class="LC_cusr_emph">'.
 2320:                             &mt('will override current values').
 2321:                             '</span></td></tr></table>';
 2322:     }
 2323:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2324: }
 2325: 
 2326: sub personal_data_display {
 2327:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2328:         $now,$captchaform,$emailusername,$usertype) = @_;
 2329:     my ($output,%userenv,%canmodify,%canmodify_status);
 2330:     my @userinfo = ('firstname','middlename','lastname','generation',
 2331:                     'permanentemail','id');
 2332:     my $rowcount = 0;
 2333:     my $editable = 0;
 2334:     my %textboxsize = (
 2335:                        firstname      => '15',
 2336:                        middlename     => '15',
 2337:                        lastname       => '15',
 2338:                        generation     => '5',
 2339:                        permanentemail => '25',
 2340:                        id             => '15',
 2341:                       );
 2342: 
 2343:     my %lt=&Apache::lonlocal::texthash(
 2344:                 'pd'             => "Personal Data",
 2345:                 'firstname'      => "First Name",
 2346:                 'middlename'     => "Middle Name",
 2347:                 'lastname'       => "Last Name",
 2348:                 'generation'     => "Generation",
 2349:                 'permanentemail' => "Permanent e-mail address",
 2350:                 'id'             => "Student/Employee ID",
 2351:                 'lg'             => "Login Data",
 2352:                 'inststatus'     => "Affiliation",
 2353:                 'email'          => 'E-mail address',
 2354:                 'valid'          => 'Validation',
 2355:     );
 2356: 
 2357:     %canmodify_status =
 2358:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2359:                                                    ['inststatus'],$rolesarray);
 2360:     if (!$newuser) {
 2361:         # Get the users information
 2362:         %userenv = &Apache::lonnet::get('environment',
 2363:                    ['firstname','middlename','lastname','generation',
 2364:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2365:         %canmodify =
 2366:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2367:                                                        \@userinfo,$rolesarray);
 2368:     } elsif ($context eq 'selfcreate') {
 2369:         if ($newuser eq 'email') {
 2370:             if (ref($emailusername) eq 'HASH') {
 2371:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2372:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2373:                     @userinfo = ();          
 2374:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2375:                         foreach my $field (@{$infofields}) { 
 2376:                             if ($emailusername->{$usertype}->{$field}) {
 2377:                                 push(@userinfo,$field);
 2378:                                 $canmodify{$field} = 1;
 2379:                                 unless ($textboxsize{$field}) {
 2380:                                     $textboxsize{$field} = 25;
 2381:                                 }
 2382:                                 unless ($lt{$field}) {
 2383:                                     $lt{$field} = $infotitles->{$field};
 2384:                                 }
 2385:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2386:                                     $lt{$field} .= '<b>*</b>';
 2387:                                 }
 2388:                             }
 2389:                         }
 2390:                     }
 2391:                 }
 2392:             }
 2393:         } else {
 2394:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2395:                                                $inst_results,$rolesarray);
 2396:         }
 2397:     }
 2398: 
 2399:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2400:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2401:               &Apache::lonhtmlcommon::start_pick_box();
 2402:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2403:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2404:                                                      'LC_oddrow_value')."\n".
 2405:                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
 2406:         $rowcount ++;
 2407:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2408:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2409:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2410:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2411:                                                     'LC_pick_box_title',
 2412:                                                     'LC_oddrow_value')."\n".
 2413:                    $upassone."\n".
 2414:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2415:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2416:                                                      'LC_pick_box_title',
 2417:                                                      'LC_oddrow_value')."\n".
 2418:                    $upasstwo.
 2419:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2420:     }
 2421:     foreach my $item (@userinfo) {
 2422:         my $rowtitle = $lt{$item};
 2423:         my $hiderow = 0;
 2424:         if ($item eq 'generation') {
 2425:             $rowtitle = $genhelp.$rowtitle;
 2426:         }
 2427:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2428:         if ($newuser) {
 2429:             if (ref($inst_results) eq 'HASH') {
 2430:                 if ($inst_results->{$item} ne '') {
 2431:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2432:                 } else {
 2433:                     if ($context eq 'selfcreate') {
 2434:                         if ($canmodify{$item}) {
 2435:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2436:                             $editable ++;
 2437:                         } else {
 2438:                             $hiderow = 1;
 2439:                         }
 2440:                     } else {
 2441:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2442:                     }
 2443:                 }
 2444:             } else {
 2445:                 if ($context eq 'selfcreate') {
 2446:                     if ($canmodify{$item}) {
 2447:                         if ($newuser eq 'email') {
 2448:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2449:                         } else {
 2450:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2451:                         }
 2452:                         $editable ++;
 2453:                     } else {
 2454:                         $hiderow = 1;
 2455:                     }
 2456:                 } else {
 2457:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2458:                 }
 2459:             }
 2460:         } else {
 2461:             if ($canmodify{$item}) {
 2462:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2463:                 if (($item eq 'id') && (!$newuser)) {
 2464:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2465:                 }
 2466:             } else {
 2467:                 $row .= $userenv{$item};
 2468:             }
 2469:         }
 2470:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2471:         if (!$hiderow) {
 2472:             $output .= $row;
 2473:             $rowcount ++;
 2474:         }
 2475:     }
 2476:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2477:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2478:         if (ref($types) eq 'ARRAY') {
 2479:             if (@{$types} > 0) {
 2480:                 my ($hiderow,$shown);
 2481:                 if ($canmodify_status{'inststatus'}) {
 2482:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2483:                 } else {
 2484:                     if ($userenv{'inststatus'} eq '') {
 2485:                         $hiderow = 1;
 2486:                     } else {
 2487:                         my @showitems;
 2488:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2489:                             if (exists($usertypes->{$item})) {
 2490:                                 push(@showitems,$usertypes->{$item});
 2491:                             } else {
 2492:                                 push(@showitems,$item);
 2493:                             }
 2494:                         }
 2495:                         if (@showitems) {
 2496:                             $shown = join(', ',@showitems);
 2497:                         } else {
 2498:                             $hiderow = 1;
 2499:                         }
 2500:                     }
 2501:                 }
 2502:                 if (!$hiderow) {
 2503:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2504:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2505:                     if ($context eq 'selfcreate') {
 2506:                         $rowcount ++;
 2507:                     }
 2508:                     $output .= $row;
 2509:                 }
 2510:             }
 2511:         }
 2512:     }
 2513:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2514:         if ($captchaform) {
 2515:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2516:                                                          'LC_pick_box_title')."\n".
 2517:                        $captchaform."\n".'<br /><br />'.
 2518:                        &Apache::lonhtmlcommon::row_closure(1); 
 2519:             $rowcount ++;
 2520:         }
 2521:         my $submit_text = &mt('Create account');
 2522:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2523:                    '<br /><input type="submit" name="createaccount" value="'.
 2524:                    $submit_text.'" />'.
 2525:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2526:                    &Apache::lonhtmlcommon::row_closure(1);
 2527:     }
 2528:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2529:     if (wantarray) {
 2530:         if ($context eq 'selfcreate') {
 2531:             return($output,$rowcount,$editable);
 2532:         } else {
 2533:             return $output;
 2534:         }
 2535:     } else {
 2536:         return $output;
 2537:     }
 2538: }
 2539: 
 2540: sub pick_inst_statuses {
 2541:     my ($curr,$usertypes,$types) = @_;
 2542:     my ($output,$rem,@currtypes);
 2543:     if ($curr ne '') {
 2544:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2545:     }
 2546:     my $numinrow = 2;
 2547:     if (ref($types) eq 'ARRAY') {
 2548:         $output = '<table>';
 2549:         my $lastcolspan; 
 2550:         for (my $i=0; $i<@{$types}; $i++) {
 2551:             if (defined($usertypes->{$types->[$i]})) {
 2552:                 my $rem = $i%($numinrow);
 2553:                 if ($rem == 0) {
 2554:                     if ($i<@{$types}-1) {
 2555:                         if ($i > 0) { 
 2556:                             $output .= '</tr>';
 2557:                         }
 2558:                         $output .= '<tr>';
 2559:                     }
 2560:                 } elsif ($i==@{$types}-1) {
 2561:                     my $colsleft = $numinrow - $rem;
 2562:                     if ($colsleft > 1) {
 2563:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2564:                     }
 2565:                 }
 2566:                 my $check = ' ';
 2567:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2568:                     $check = ' checked="checked" ';
 2569:                 }
 2570:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2571:                            '<span class="LC_nobreak"><label>'.
 2572:                            '<input type="checkbox" name="inststatus" '.
 2573:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2574:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2575:             }
 2576:         }
 2577:         $output .= '</tr></table>';
 2578:     }
 2579:     return $output;
 2580: }
 2581: 
 2582: sub selfcreate_canmodify {
 2583:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2584:     if (ref($inst_results) eq 'HASH') {
 2585:         my @inststatuses = &get_inststatuses($inst_results);
 2586:         if (@inststatuses == 0) {
 2587:             @inststatuses = ('default');
 2588:         }
 2589:         $rolesarray = \@inststatuses;
 2590:     }
 2591:     my %canmodify =
 2592:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2593:                                                    $rolesarray);
 2594:     return %canmodify;
 2595: }
 2596: 
 2597: sub get_inststatuses {
 2598:     my ($insthashref) = @_;
 2599:     my @inststatuses = ();
 2600:     if (ref($insthashref) eq 'HASH') {
 2601:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2602:             @inststatuses = @{$insthashref->{'inststatus'}};
 2603:         }
 2604:     }
 2605:     return @inststatuses;
 2606: }
 2607: 
 2608: # ================================================================= Phase Three
 2609: sub update_user_data {
 2610:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2611:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2612:                                           $env{'form.ccdomain'});
 2613:     # Error messages
 2614:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2615:     my $end       = '</span><br /><br />';
 2616:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2617:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2618:                     &mt('Return to previous page').'</a>'.
 2619:                     &Apache::loncommon::end_page();
 2620:     my $now = time;
 2621:     my $title;
 2622:     if (exists($env{'form.makeuser'})) {
 2623: 	$title='Set Privileges for New User';
 2624:     } else {
 2625:         $title='Modify User Privileges';
 2626:     }
 2627:     my $newuser = 0;
 2628:     my ($jsback,$elements) = &crumb_utilities();
 2629:     my $jscript = '<script type="text/javascript">'."\n".
 2630:                   '// <![CDATA['."\n".
 2631:                   $jsback."\n".
 2632:                   '// ]]>'."\n".
 2633:                   '</script>'."\n";
 2634:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2635:     push (@{$brcrum},
 2636:              {href => "javascript:backPage(document.userupdate)",
 2637:               text => $breadcrumb_text{'search'},
 2638:               faq  => 282,
 2639:               bug  => 'Instructor Interface',}
 2640:              );
 2641:     if ($env{'form.prevphase'} eq 'userpicked') {
 2642:         push(@{$brcrum},
 2643:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2644:                 text => $breadcrumb_text{'userpicked'},
 2645:                 faq  => 282,
 2646:                 bug  => 'Instructor Interface',});
 2647:     }
 2648:     my $helpitem = 'Course_Change_Privileges';
 2649:     if ($env{'form.action'} eq 'singlestudent') {
 2650:         $helpitem = 'Course_Add_Student';
 2651:     }
 2652:     push(@{$brcrum}, 
 2653:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2654:              text => $breadcrumb_text{'modify'},
 2655:              faq  => 282,
 2656:              bug  => 'Instructor Interface',},
 2657:             {href => "/adm/createuser",
 2658:              text => "Result",
 2659:              faq  => 282,
 2660:              bug  => 'Instructor Interface',
 2661:              help => $helpitem});
 2662:     my $args = {bread_crumbs          => $brcrum,
 2663:                 bread_crumbs_component => 'User Management'};
 2664:     if ($env{'form.popup'}) {
 2665:         $args->{'no_nav_bar'} = 1;
 2666:     }
 2667:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2668:     $r->print(&update_result_form($uhome));
 2669:     # Check Inputs
 2670:     if (! $env{'form.ccuname'} ) {
 2671: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2672: 	return;
 2673:     }
 2674:     if (  $env{'form.ccuname'} ne 
 2675: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2676: 	$r->print($error.&mt('Invalid login name.').'  '.
 2677: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2678: 		  $end.$rtnlink);
 2679: 	return;
 2680:     }
 2681:     if (! $env{'form.ccdomain'}       ) {
 2682: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2683: 	return;
 2684:     }
 2685:     if (  $env{'form.ccdomain'} ne
 2686: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2687: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2688: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2689: 		  $end.$rtnlink);
 2690: 	return;
 2691:     }
 2692:     if ($uhome eq 'no_host') {
 2693:         $newuser = 1;
 2694:     }
 2695:     if (! exists($env{'form.makeuser'})) {
 2696:         # Modifying an existing user, so check the validity of the name
 2697:         if ($uhome eq 'no_host') {
 2698:             $r->print(
 2699:                 $error
 2700:                .'<p class="LC_error">'
 2701:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2702:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2703:                .'</p>');
 2704:             return;
 2705:         }
 2706:     }
 2707:     # Determine authentication method and password for the user being modified
 2708:     my $amode='';
 2709:     my $genpwd='';
 2710:     if ($env{'form.login'} eq 'krb') {
 2711: 	$amode='krb';
 2712: 	$amode.=$env{'form.krbver'};
 2713: 	$genpwd=$env{'form.krbarg'};
 2714:     } elsif ($env{'form.login'} eq 'int') {
 2715: 	$amode='internal';
 2716: 	$genpwd=$env{'form.intarg'};
 2717:     } elsif ($env{'form.login'} eq 'fsys') {
 2718: 	$amode='unix';
 2719: 	$genpwd=$env{'form.fsysarg'};
 2720:     } elsif ($env{'form.login'} eq 'loc') {
 2721: 	$amode='localauth';
 2722: 	$genpwd=$env{'form.locarg'};
 2723: 	$genpwd=" " if (!$genpwd);
 2724:     } elsif (($env{'form.login'} eq 'nochange') ||
 2725:              ($env{'form.login'} eq ''        )) { 
 2726:         # There is no need to tell the user we did not change what they
 2727:         # did not ask us to change.
 2728:         # If they are creating a new user but have not specified login
 2729:         # information this will be caught below.
 2730:     } else {
 2731:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2732:             return;
 2733:     }
 2734: 
 2735:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2736:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2737:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2738:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2739: 
 2740:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2741:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2742:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2743:     my @requestcourses = ('official','unofficial','community','textbook','placement');
 2744:     my @requestauthor = ('requestauthor');
 2745:     my ($othertitle,$usertypes,$types) = 
 2746:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2747:     my %canmodify_status =
 2748:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2749:                                                    ['inststatus']);
 2750:     if ($env{'form.makeuser'}) {
 2751: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2752:         # Check for the authentication mode and password
 2753:         if (! $amode || ! $genpwd) {
 2754: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2755: 	    return;
 2756: 	}
 2757:         # Determine desired host
 2758:         my $desiredhost = $env{'form.hserver'};
 2759:         if (lc($desiredhost) eq 'default') {
 2760:             $desiredhost = undef;
 2761:         } else {
 2762:             my %home_servers = 
 2763: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2764:             if (! exists($home_servers{$desiredhost})) {
 2765:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2766:                 return;
 2767:             }
 2768:         }
 2769:         # Check ID format
 2770:         my %checkhash;
 2771:         my %checks = ('id' => 1);
 2772:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2773:             'newuser' => $newuser, 
 2774:             'id' => $env{'form.cid'},
 2775:         );
 2776:         if ($env{'form.cid'} ne '') {
 2777:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2778:                                           \%rulematch,\%inst_results,\%curr_rules);
 2779:             if (ref($alerts{'id'}) eq 'HASH') {
 2780:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2781:                     my $domdesc =
 2782:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2783:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2784:                         my $userchkmsg;
 2785:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2786:                             $userchkmsg  = 
 2787:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2788:                                                                     $domdesc,1).
 2789:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2790:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2791:                         }
 2792:                         $r->print($error.&mt('Invalid ID format').$end.
 2793:                                   $userchkmsg.$rtnlink);
 2794:                         return;
 2795:                     }
 2796:                 }
 2797:             }
 2798:         }
 2799:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2800: 	# Call modifyuser
 2801: 	my $result = &Apache::lonnet::modifyuser
 2802: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2803:              $amode,$genpwd,$env{'form.cfirstname'},
 2804:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2805:              $env{'form.cgeneration'},undef,$desiredhost,
 2806:              $env{'form.cpermanentemail'});
 2807: 	$r->print(&mt('Generating user').': '.$result);
 2808:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2809:                                                $env{'form.ccdomain'});
 2810:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2811:         if ($uhome ne 'no_host') {
 2812:             if ($context eq 'domain') {
 2813:                 foreach my $name ('portfolio','author') {
 2814:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2815:                         if ($env{'form.'.$name.'quota'} eq '') {
 2816:                             $newcustom{$name.'quota'} = 0;
 2817:                         } else {
 2818:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2819:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2820:                         }
 2821:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2822:                             $changed{$name.'quota'} = 1;
 2823:                         }
 2824:                     }
 2825:                 }
 2826:                 foreach my $item (@usertools) {
 2827:                     if ($env{'form.custom'.$item} == 1) {
 2828:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2829:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2830:                                                      \%changeHash,'tools');
 2831:                     }
 2832:                 }
 2833:                 foreach my $item (@requestcourses) {
 2834:                     if ($env{'form.custom'.$item} == 1) {
 2835:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2836:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2837:                             $newcustom{$item} .= '=';
 2838:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2839:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2840:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2841:                             }
 2842:                         }
 2843:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2844:                                                       \%changeHash,'requestcourses');
 2845:                     }
 2846:                 }
 2847:                 if ($env{'form.customrequestauthor'} == 1) {
 2848:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2849:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2850:                                                     $newcustom{'requestauthor'},
 2851:                                                     \%changeHash,'requestauthor');
 2852:                 }
 2853:             }
 2854:             if ($canmodify_status{'inststatus'}) {
 2855:                 if (exists($env{'form.inststatus'})) {
 2856:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2857:                     if (@inststatuses > 0) {
 2858:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2859:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2860:                     }
 2861:                 }
 2862:             }
 2863:             if (keys(%changed)) {
 2864:                 foreach my $item (@userinfo) {
 2865:                     $changeHash{$item}  = $env{'form.c'.$item};
 2866:                 }
 2867:                 my $chgresult =
 2868:                      &Apache::lonnet::put('environment',\%changeHash,
 2869:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 2870:             } 
 2871:         }
 2872:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 2873:                   &Apache::lonnet::hostname($uhome));
 2874:     } elsif (($env{'form.login'} ne 'nochange') &&
 2875:              ($env{'form.login'} ne ''        )) {
 2876: 	# Modify user privileges
 2877:         if (! $amode || ! $genpwd) {
 2878: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 2879: 	    return;
 2880: 	}
 2881: 	# Only allow authentication modification if the person has authority
 2882: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 2883: 	    $r->print('Modifying authentication: '.
 2884:                       &Apache::lonnet::modifyuserauth(
 2885: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 2886:                        $amode,$genpwd));
 2887:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 2888: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 2889: 	} else {
 2890: 	    # Okay, this is a non-fatal error.
 2891: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 2892: 	}
 2893:     }
 2894:     $r->rflush(); # Finish display of header before time consuming actions start
 2895:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 2896:     ##
 2897:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 2898:     if ($context eq 'course') {
 2899:         ($cnum,$cdom) =
 2900:             &Apache::lonuserutils::get_course_identity();
 2901:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2902:         if ($showcredits) {
 2903:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 2904:         }
 2905:     }
 2906:     if (! $env{'form.makeuser'} ) {
 2907:         # Check for need to change
 2908:         my %userenv = &Apache::lonnet::get
 2909:             ('environment',['firstname','middlename','lastname','generation',
 2910:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 2911:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 2912:              'requestcourses.official','requestcourses.unofficial',
 2913:              'requestcourses.community','requestcourses.textbook',
 2914:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 2915:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 2916:              'reqcrsotherdom.placement','requestauthor'],
 2917:               $env{'form.ccdomain'},$env{'form.ccuname'});
 2918:         my ($tmp) = keys(%userenv);
 2919:         if ($tmp =~ /^(con_lost|error)/i) { 
 2920:             %userenv = ();
 2921:         }
 2922:         my $no_forceid_alert;
 2923:         # Check to see if user information can be changed
 2924:         my %domconfig =
 2925:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 2926:                                      $env{'form.ccdomain'});
 2927:         my @statuses = ('active','future');
 2928:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 2929:         my ($auname,$audom);
 2930:         if ($context eq 'author') {
 2931:             $auname = $env{'user.name'};
 2932:             $audom = $env{'user.domain'};     
 2933:         }
 2934:         foreach my $item (keys(%roles)) {
 2935:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 2936:             if ($context eq 'course') {
 2937:                 if ($cnum ne '' && $cdom ne '') {
 2938:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 2939:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 2940:                             push(@userroles,$role);
 2941:                         }
 2942:                     }
 2943:                 }
 2944:             } elsif ($context eq 'author') {
 2945:                 if ($rolenum eq $auname && $roledom eq $audom) {
 2946:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 2947:                         push(@userroles,$role);
 2948:                     }
 2949:                 }
 2950:             }
 2951:         }
 2952:         if ($env{'form.action'} eq 'singlestudent') {
 2953:             if (!grep(/^st$/,@userroles)) {
 2954:                 push(@userroles,'st');
 2955:             }
 2956:         } else {
 2957:             # Check for course or co-author roles being activated or re-enabled
 2958:             if ($context eq 'author' || $context eq 'course') {
 2959:                 foreach my $key (keys(%env)) {
 2960:                     if ($context eq 'author') {
 2961:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 2962:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2963:                                 push(@userroles,$1);
 2964:                             }
 2965:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 2966:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2967:                                 push(@userroles,$1);
 2968:                             }
 2969:                         }
 2970:                     } elsif ($context eq 'course') {
 2971:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 2972:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2973:                                 push(@userroles,$1);
 2974:                             }
 2975:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 2976:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 2977:                                 push(@userroles,$1);
 2978:                             }
 2979:                         }
 2980:                     }
 2981:                 }
 2982:             }
 2983:         }
 2984:         #Check to see if we can change personal data for the user 
 2985:         my (@mod_disallowed,@longroles);
 2986:         foreach my $role (@userroles) {
 2987:             if ($role eq 'cr') {
 2988:                 push(@longroles,'Custom');
 2989:             } else {
 2990:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 2991:             }
 2992:         }
 2993:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 2994:         foreach my $item (@userinfo) {
 2995:             # Strip leading and trailing whitespace
 2996:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 2997:             if (!$canmodify{$item}) {
 2998:                 if (defined($env{'form.c'.$item})) {
 2999:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3000:                         push(@mod_disallowed,$item);
 3001:                     }
 3002:                 }
 3003:                 $env{'form.c'.$item} = $userenv{$item};
 3004:             }
 3005:         }
 3006:         # Check to see if we can change the Student/Employee ID
 3007:         my $forceid = $env{'form.forceid'};
 3008:         my $recurseid = $env{'form.recurseid'};
 3009:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3010:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3011:                                             $env{'form.ccuname'});
 3012:         if (($uidhash{$env{'form.ccuname'}}) && 
 3013:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3014:             (!$forceid)) {
 3015:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3016:                 $env{'form.cid'} = $userenv{'id'};
 3017:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3018:                                    .'<br />'
 3019:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3020:                                    .'<br />'."\n";
 3021:             }
 3022:         }
 3023:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3024:             my $checkhash;
 3025:             my $checks = { 'id' => 1 };
 3026:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3027:                    { 'newuser' => $newuser,
 3028:                      'id'  => $env{'form.cid'}, 
 3029:                    };
 3030:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3031:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3032:             if (ref($alerts{'id'}) eq 'HASH') {
 3033:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3034:                    $env{'form.cid'} = $userenv{'id'};
 3035:                 }
 3036:             }
 3037:         }
 3038:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3039:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3040:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3041:             %oldsettingstatus,%newsettingstatus);
 3042:         @disporder = ('inststatus');
 3043:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3044:             push(@disporder,'requestcourses','requestauthor');
 3045:         } else {
 3046:             push(@disporder,'reqcrsotherdom');
 3047:         }
 3048:         push(@disporder,('quota','tools'));
 3049:         $oldinststatus = $userenv{'inststatus'};
 3050:         foreach my $name ('portfolio','author') {
 3051:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3052:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3053:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3054:         }
 3055:         my %canshow;
 3056:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3057:             $canshow{'quota'} = 1;
 3058:         }
 3059:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3060:             $canshow{'tools'} = 1;
 3061:         }
 3062:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3063:             $canshow{'requestcourses'} = 1;
 3064:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3065:             $canshow{'reqcrsotherdom'} = 1;
 3066:         }
 3067:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3068:             $canshow{'inststatus'} = 1;
 3069:         }
 3070:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3071:             $canshow{'requestauthor'} = 1;
 3072:         }
 3073:         my (%changeHash,%changed);
 3074:         if ($oldinststatus eq '') {
 3075:             $oldsettings{'inststatus'} = $othertitle; 
 3076:         } else {
 3077:             if (ref($usertypes) eq 'HASH') {
 3078:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3079:             } else {
 3080:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3081:             }
 3082:         }
 3083:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3084:         if ($canmodify_status{'inststatus'}) {
 3085:             $canshow{'inststatus'} = 1;
 3086:             if (exists($env{'form.inststatus'})) {
 3087:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3088:                 if (@inststatuses > 0) {
 3089:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3090:                     $changeHash{'inststatus'} = $newinststatus;
 3091:                     if ($newinststatus ne $oldinststatus) {
 3092:                         $changed{'inststatus'} = $newinststatus;
 3093:                         foreach my $name ('portfolio','author') {
 3094:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3095:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3096:                         }
 3097:                     }
 3098:                     if (ref($usertypes) eq 'HASH') {
 3099:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3100:                     } else {
 3101:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3102:                     }
 3103:                 }
 3104:             } else {
 3105:                 $newinststatus = '';
 3106:                 $changeHash{'inststatus'} = $newinststatus;
 3107:                 $newsettings{'inststatus'} = $othertitle;
 3108:                 if ($newinststatus ne $oldinststatus) {
 3109:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3110:                     foreach my $name ('portfolio','author') {
 3111:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3112:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3113:                     }
 3114:                 }
 3115:             }
 3116:         } elsif ($context ne 'selfcreate') {
 3117:             $canshow{'inststatus'} = 1;
 3118:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3119:         }
 3120:         foreach my $name ('portfolio','author') {
 3121:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3122:         }
 3123:         if ($context eq 'domain') {
 3124:             foreach my $name ('portfolio','author') {
 3125:                 if ($userenv{$name.'quota'} ne '') {
 3126:                     $oldquota{$name} = $userenv{$name.'quota'};
 3127:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3128:                         if ($env{'form.'.$name.'quota'} eq '') {
 3129:                             $newquota{$name} = 0;
 3130:                         } else {
 3131:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3132:                             $newquota{$name} =~ s/[^\d\.]//g;
 3133:                         }
 3134:                         if ($newquota{$name} != $oldquota{$name}) {
 3135:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3136:                                 $changed{$name.'quota'} = 1;
 3137:                             }
 3138:                         }
 3139:                     } else {
 3140:                         if (&quota_admin('',\%changeHash,$name)) {
 3141:                             $changed{$name.'quota'} = 1;
 3142:                             $newquota{$name} = $newdefquota{$name};
 3143:                             $newisdefault{$name} = 1;
 3144:                         }
 3145:                     }
 3146:                 } else {
 3147:                     $oldisdefault{$name} = 1;
 3148:                     $oldquota{$name} = $olddefquota{$name};
 3149:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3150:                         if ($env{'form.'.$name.'quota'} eq '') {
 3151:                             $newquota{$name} = 0;
 3152:                         } else {
 3153:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3154:                             $newquota{$name} =~ s/[^\d\.]//g;
 3155:                         }
 3156:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3157:                             $changed{$name.'quota'} = 1;
 3158:                         }
 3159:                     } else {
 3160:                         $newquota{$name} = $newdefquota{$name};
 3161:                         $newisdefault{$name} = 1;
 3162:                     }
 3163:                 }
 3164:                 if ($oldisdefault{$name}) {
 3165:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3166:                 }  else {
 3167:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3168:                 }
 3169:                 if ($newisdefault{$name}) {
 3170:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3171:                 } else {
 3172:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3173:                 }
 3174:             }
 3175:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3176:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3177:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3178:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3179:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3180:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3181:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3182:             } else {
 3183:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3184:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3185:             }
 3186:         }
 3187:         foreach my $item (@userinfo) {
 3188:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3189:                 $namechanged{$item} = 1;
 3190:             }
 3191:         }
 3192:         foreach my $name ('portfolio','author') {
 3193:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3194:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3195:         }
 3196:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3197:             my ($chgresult,$namechgresult);
 3198:             if (keys(%changed) > 0) {
 3199:                 $chgresult = 
 3200:                     &Apache::lonnet::put('environment',\%changeHash,
 3201:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3202:                 if ($chgresult eq 'ok') {
 3203:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3204:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3205:                         my %newenvhash;
 3206:                         foreach my $key (keys(%changed)) {
 3207:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3208:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3209:                                 ($key eq 'placement')) {
 3210:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3211:                                     $changeHash{'requestcourses.'.$key};
 3212:                                 if ($changeHash{'requestcourses.'.$key}) {
 3213:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3214:                                 } else {
 3215:                                     $newenvhash{'environment.canrequest.'.$key} =
 3216:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3217:                                             $key,'reload','requestcourses');
 3218:                                 }
 3219:                             } elsif ($key eq 'requestauthor') {
 3220:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3221:                                 if ($changeHash{$key}) {
 3222:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3223:                                 } else {
 3224:                                     $newenvhash{'environment.canrequest.author'} =
 3225:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3226:                                             $key,'reload','requestauthor');
 3227:                                 }
 3228:                             } elsif ($key ne 'quota') {
 3229:                                 $newenvhash{'environment.tools.'.$key} = 
 3230:                                     $changeHash{'tools.'.$key};
 3231:                                 if ($changeHash{'tools.'.$key} ne '') {
 3232:                                     $newenvhash{'environment.availabletools.'.$key} =
 3233:                                         $changeHash{'tools.'.$key};
 3234:                                 } else {
 3235:                                     $newenvhash{'environment.availabletools.'.$key} =
 3236:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3237:           $key,'reload','tools');
 3238:                                 }
 3239:                             }
 3240:                         }
 3241:                         if (keys(%newenvhash)) {
 3242:                             &Apache::lonnet::appenv(\%newenvhash);
 3243:                         }
 3244:                     }
 3245:                 }
 3246:             }
 3247:             if (keys(%namechanged) > 0) {
 3248:                 foreach my $field (@userinfo) {
 3249:                     $changeHash{$field}  = $env{'form.c'.$field};
 3250:                 }
 3251: # Make the change
 3252:                 $namechgresult =
 3253:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3254:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3255:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3256:                         $changeHash{'lastname'},$changeHash{'generation'},
 3257:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3258:                 %userupdate = (
 3259:                                lastname   => $env{'form.clastname'},
 3260:                                middlename => $env{'form.cmiddlename'},
 3261:                                firstname  => $env{'form.cfirstname'},
 3262:                                generation => $env{'form.cgeneration'},
 3263:                                id         => $env{'form.cid'},
 3264:                              );
 3265:             }
 3266:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3267:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3268:             # Tell the user we changed the name
 3269:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3270:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3271:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3272:                                   \%newsettingstext);
 3273:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3274:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3275:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3276:                     if (($recurseid) &&
 3277:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3278:                         my $idresult = 
 3279:                             &Apache::lonuserutils::propagate_id_change(
 3280:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3281:                                 \%userupdate);
 3282:                         $r->print('<br />'.$idresult.'<br />');
 3283:                     }
 3284:                 }
 3285:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3286:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3287:                     my %newenvhash;
 3288:                     foreach my $key (keys(%changeHash)) {
 3289:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3290:                     }
 3291:                     &Apache::lonnet::appenv(\%newenvhash);
 3292:                 }
 3293:             } else { # error occurred
 3294:                 $r->print(
 3295:                     '<p class="LC_error">'
 3296:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3297:                             '"'.$env{'form.ccuname'}.'"',
 3298:                             '"'.$env{'form.ccdomain'}.'"')
 3299:                    .'</p>');
 3300:             }
 3301:         } else { # End of if ($env ... ) logic
 3302:             # They did not want to change the users name, quota, tool availability,
 3303:             # or ability to request creation of courses, 
 3304:             # but we can still tell them what the name and quota and availabilities are  
 3305:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3306:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3307:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3308:         }
 3309:         if (@mod_disallowed) {
 3310:             my ($rolestr,$contextname);
 3311:             if (@longroles > 0) {
 3312:                 $rolestr = join(', ',@longroles);
 3313:             } else {
 3314:                 $rolestr = &mt('No roles');
 3315:             }
 3316:             if ($context eq 'course') {
 3317:                 $contextname = 'course';
 3318:             } elsif ($context eq 'author') {
 3319:                 $contextname = 'co-author';
 3320:             }
 3321:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3322:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3323:             foreach my $field (@mod_disallowed) {
 3324:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3325:             }
 3326:             $r->print('</ul>');
 3327:             if (@mod_disallowed == 1) {
 3328:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3329:             } else {
 3330:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3331:             }
 3332:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3333:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3334:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3335:                          ,'<a href="'.$helplink.'">','</a>')
 3336:                       .'<br />');
 3337:         }
 3338:         $r->print('<span class="LC_warning">'
 3339:                   .$no_forceid_alert
 3340:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3341:                   .'</span>');
 3342:     }
 3343:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3344:     if ($env{'form.action'} eq 'singlestudent') {
 3345:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3346:                                $crstype,$showcredits,$defaultcredits);
 3347:         my $linktext = ($crstype eq 'Community' ?
 3348:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3349:         $r->print(
 3350:             &Apache::lonhtmlcommon::actionbox([
 3351:                 '<a href="javascript:backPage(document.userupdate)">'
 3352:                .($crstype eq 'Community' ? 
 3353:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3354:                .'</a>']));
 3355:     } else {
 3356:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3357:         if (keys(%namechanged) > 0) {
 3358:             if ($context eq 'course') {
 3359:                 if (@userroles > 0) {
 3360:                     if ((@rolechanges == 0) || 
 3361:                         (!(grep(/^st$/,@rolechanges)))) {
 3362:                         if (grep(/^st$/,@userroles)) {
 3363:                             my $classlistupdated =
 3364:                                 &Apache::lonuserutils::update_classlist($cdom,
 3365:                                               $cnum,$env{'form.ccdomain'},
 3366:                                        $env{'form.ccuname'},\%userupdate);
 3367:                         }
 3368:                     }
 3369:                 }
 3370:             }
 3371:         }
 3372:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3373:                                                      $env{'form.ccdomain'});
 3374:         if ($env{'form.popup'}) {
 3375:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3376:         } else {
 3377:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3378:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3379:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3380:         }
 3381:     }
 3382: }
 3383: 
 3384: sub display_userinfo {
 3385:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3386:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3387:         $newsetting,$newsettingtext) = @_;
 3388:     return unless (ref($order) eq 'ARRAY' &&
 3389:                    ref($canshow) eq 'HASH' && 
 3390:                    ref($requestcourses) eq 'ARRAY' && 
 3391:                    ref($requestauthor) eq 'ARRAY' &&
 3392:                    ref($usertools) eq 'ARRAY' && 
 3393:                    ref($userenv) eq 'HASH' &&
 3394:                    ref($changedhash) eq 'HASH' &&
 3395:                    ref($oldsetting) eq 'HASH' &&
 3396:                    ref($oldsettingtext) eq 'HASH' &&
 3397:                    ref($newsetting) eq 'HASH' &&
 3398:                    ref($newsettingtext) eq 'HASH');
 3399:     my %lt=&Apache::lonlocal::texthash(
 3400:          'ui'             => 'User Information',
 3401:          'uic'            => 'User Information Changed',
 3402:          'firstname'      => 'First Name',
 3403:          'middlename'     => 'Middle Name',
 3404:          'lastname'       => 'Last Name',
 3405:          'generation'     => 'Generation',
 3406:          'id'             => 'Student/Employee ID',
 3407:          'permanentemail' => 'Permanent e-mail address',
 3408:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3409:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3410:          'blog'           => 'Blog Availability',
 3411:          'webdav'         => 'WebDAV Availability',
 3412:          'aboutme'        => 'Personal Information Page Availability',
 3413:          'portfolio'      => 'Portfolio Availability',
 3414:          'official'       => 'Can Request Official Courses',
 3415:          'unofficial'     => 'Can Request Unofficial Courses',
 3416:          'community'      => 'Can Request Communities',
 3417:          'textbook'       => 'Can Request Textbook Courses',
 3418:          'placement'      => 'Can Request Placement Tests',
 3419:          'requestauthor'  => 'Can Request Author Role',
 3420:          'inststatus'     => "Affiliation",
 3421:          'prvs'           => 'Previous Value:',
 3422:          'chto'           => 'Changed To:'
 3423:     );
 3424:     if ($changed) {
 3425:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3426:                 &Apache::loncommon::start_data_table().
 3427:                 &Apache::loncommon::start_data_table_header_row());
 3428:         $r->print("<th>&nbsp;</th>\n");
 3429:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3430:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3431:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3432:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3433: 
 3434:         foreach my $item (@userinfo) {
 3435:             my $value = $env{'form.c'.$item};
 3436:             #show changes only:
 3437:             unless ($value eq $userenv->{$item}){
 3438:                 $r->print(&Apache::loncommon::start_data_table_row());
 3439:                 $r->print("<td>$lt{$item}</td>\n");
 3440:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3441:                 $r->print("<td>$value </td>\n");
 3442:                 $r->print(&Apache::loncommon::end_data_table_row());
 3443:             }
 3444:         }
 3445:         foreach my $entry (@{$order}) {
 3446:             if ($canshow->{$entry}) {
 3447:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3448:                     my @items;
 3449:                     if ($entry eq 'requestauthor') {
 3450:                         @items = ($entry);
 3451:                     } else {
 3452:                         @items = @{$requestcourses};
 3453:                     }
 3454:                     foreach my $item (@items) {
 3455:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3456:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3457:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3458:                             $r->print("<td>$lt{$item}</td>\n");
 3459:                             $r->print("<td>".$oldsetting->{$item});
 3460:                             if ($oldsettingtext->{$item}) {
 3461:                                 if ($oldsetting->{$item}) {
 3462:                                     $r->print(' -- ');
 3463:                                 }
 3464:                                 $r->print($oldsettingtext->{$item});
 3465:                             }
 3466:                             $r->print("</td>\n");
 3467:                             $r->print("<td>".$newsetting->{$item});
 3468:                             if ($newsettingtext->{$item}) {
 3469:                                 if ($newsetting->{$item}) {
 3470:                                     $r->print(' -- ');
 3471:                                 }
 3472:                                 $r->print($newsettingtext->{$item});
 3473:                             }
 3474:                             $r->print("</td>\n");
 3475:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3476:                         }
 3477:                     }
 3478:                 } elsif ($entry eq 'tools') {
 3479:                     foreach my $item (@{$usertools}) {
 3480:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3481:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3482:                             $r->print("<td>$lt{$item}</td>\n");
 3483:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3484:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3485:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3486:                         }
 3487:                     }
 3488:                 } elsif ($entry eq 'quota') {
 3489:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3490:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3491:                         foreach my $name ('portfolio','author') {
 3492:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3493:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3494:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3495:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3496:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3497:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3498:                             }
 3499:                         }
 3500:                     }
 3501:                 } else {
 3502:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3503:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3504:                         $r->print("<td>$lt{$entry}</td>\n");
 3505:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3506:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3507:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3508:                     }
 3509:                 }
 3510:             }
 3511:         }
 3512:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3513:     } else {
 3514:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3515:                   '<p>'.&mt('No changes made to user information').'</p>');
 3516:     }
 3517:     return;
 3518: }
 3519: 
 3520: sub tool_changes {
 3521:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3522:         $changed,$newaccess,$newaccesstext) = @_;
 3523:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3524:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3525:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3526:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3527:         return;
 3528:     }
 3529:     my %reqdisplay = &requestchange_display();
 3530:     if ($context eq 'reqcrsotherdom') {
 3531:         my @options = ('approval','validate','autolimit');
 3532:         my $optregex = join('|',@options);
 3533:         my $cdom = $env{'request.role.domain'};
 3534:         foreach my $tool (@{$usertools}) {
 3535:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3536:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3537:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3538:             my ($newop,$limit);
 3539:             if ($env{'form.'.$context.'_'.$tool}) {
 3540:                 $newop = $env{'form.'.$context.'_'.$tool};
 3541:                 if ($newop eq 'autolimit') {
 3542:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3543:                     $limit =~ s/\D+//g;
 3544:                     $newop .= '='.$limit;
 3545:                 }
 3546:             }
 3547:             if ($userenv->{$context.'.'.$tool} eq '') {
 3548:                 if ($newop) {
 3549:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3550:                                                   $changeHash,$context);
 3551:                     if ($changed->{$tool}) {
 3552:                         if ($newop =~ /^autolimit/) {
 3553:                             if ($limit) {
 3554:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3555:                             } else {
 3556:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3557:                             }
 3558:                         } else {
 3559:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3560:                         }
 3561:                     } else {
 3562:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3563:                     }
 3564:                 }
 3565:             } else {
 3566:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3567:                 my @new;
 3568:                 my $changedoms;
 3569:                 foreach my $req (@curr) {
 3570:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3571:                         my $oldop = $1;
 3572:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3573:                             my $limit = $1;
 3574:                             if ($limit) {
 3575:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3576:                             } else {
 3577:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3578:                             }
 3579:                         } else {
 3580:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3581:                         }
 3582:                         if ($oldop ne $newop) {
 3583:                             $changedoms = 1;
 3584:                             foreach my $item (@curr) {
 3585:                                 my ($reqdom,$option) = split(':',$item);
 3586:                                 unless ($reqdom eq $cdom) {
 3587:                                     push(@new,$item);
 3588:                                 }
 3589:                             }
 3590:                             if ($newop) {
 3591:                                 push(@new,$cdom.':'.$newop);
 3592:                             }
 3593:                             @new = sort(@new);
 3594:                         }
 3595:                         last;
 3596:                     }
 3597:                 }
 3598:                 if ((!$changedoms) && ($newop)) {
 3599:                     $changedoms = 1;
 3600:                     @new = sort(@curr,$cdom.':'.$newop);
 3601:                 }
 3602:                 if ($changedoms) {
 3603:                     my $newdomstr;
 3604:                     if (@new) {
 3605:                         $newdomstr = join(',',@new);
 3606:                     }
 3607:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3608:                                                   $context);
 3609:                     if ($changed->{$tool}) {
 3610:                         if ($env{'form.'.$context.'_'.$tool}) {
 3611:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3612:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3613:                                 $limit =~ s/\D+//g;
 3614:                                 if ($limit) {
 3615:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3616:                                 } else {
 3617:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3618:                                 }
 3619:                             } else {
 3620:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3621:                             }
 3622:                         } else {
 3623:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3624:                         }
 3625:                     }
 3626:                 }
 3627:             }
 3628:         }
 3629:         return;
 3630:     }
 3631:     foreach my $tool (@{$usertools}) {
 3632:         my ($newval,$limit,$envkey);
 3633:         $envkey = $context.'.'.$tool;
 3634:         if ($context eq 'requestcourses') {
 3635:             $newval = $env{'form.crsreq_'.$tool};
 3636:             if ($newval eq 'autolimit') {
 3637:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3638:                 $limit =~ s/\D+//g;
 3639:                 $newval .= '='.$limit;
 3640:             }
 3641:         } elsif ($context eq 'requestauthor') {
 3642:             $newval = $env{'form.'.$context};
 3643:             $envkey = $context;
 3644:         } else {
 3645:             $newval = $env{'form.'.$context.'_'.$tool};
 3646:         }
 3647:         if ($userenv->{$envkey} ne '') {
 3648:             $oldaccess->{$tool} = &mt('custom');
 3649:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3650:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3651:                     my $currlimit = $1;
 3652:                     if ($currlimit eq '') {
 3653:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3654:                     } else {
 3655:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3656:                     }
 3657:                 } elsif ($userenv->{$envkey}) {
 3658:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3659:                 } else {
 3660:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3661:                 }
 3662:             } else {
 3663:                 if ($userenv->{$envkey}) {
 3664:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3665:                 } else {
 3666:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3667:                 }
 3668:             }
 3669:             $changeHash->{$envkey} = $userenv->{$envkey};
 3670:             if ($env{'form.custom'.$tool} == 1) {
 3671:                 if ($newval ne $userenv->{$envkey}) {
 3672:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3673:                                                     $context);
 3674:                     if ($changed->{$tool}) {
 3675:                         $newaccess->{$tool} = &mt('custom');
 3676:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3677:                             if ($newval =~ /^autolimit/) {
 3678:                                 if ($limit) {
 3679:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3680:                                 } else {
 3681:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3682:                                 }
 3683:                             } elsif ($newval) {
 3684:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3685:                             } else {
 3686:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3687:                             }
 3688:                         } else {
 3689:                             if ($newval) {
 3690:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3691:                             } else {
 3692:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3693:                             }
 3694:                         }
 3695:                     } else {
 3696:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3697:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3698:                             if ($newval =~ /^autolimit/) {
 3699:                                 if ($limit) {
 3700:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3701:                                 } else {
 3702:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3703:                                 }
 3704:                             } elsif ($newval) {
 3705:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3706:                             } else {
 3707:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3708:                             }
 3709:                         } else {
 3710:                             if ($userenv->{$context.'.'.$tool}) {
 3711:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3712:                             } else {
 3713:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3714:                             }
 3715:                         }
 3716:                     }
 3717:                 } else {
 3718:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3719:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3720:                 }
 3721:             } else {
 3722:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3723:                 if ($changed->{$tool}) {
 3724:                     $newaccess->{$tool} = &mt('default');
 3725:                 } else {
 3726:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3727:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3728:                         if ($newval =~ /^autolimit/) {
 3729:                             if ($limit) {
 3730:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3731:                             } else {
 3732:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3733:                             }
 3734:                         } elsif ($newval) {
 3735:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3736:                         } else {
 3737:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3738:                         }
 3739:                     } else {
 3740:                         if ($userenv->{$context.'.'.$tool}) {
 3741:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3742:                         } else {
 3743:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3744:                         }
 3745:                     }
 3746:                 }
 3747:             }
 3748:         } else {
 3749:             $oldaccess->{$tool} = &mt('default');
 3750:             if ($env{'form.custom'.$tool} == 1) {
 3751:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3752:                                                 $context);
 3753:                 if ($changed->{$tool}) {
 3754:                     $newaccess->{$tool} = &mt('custom');
 3755:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3756:                         if ($newval =~ /^autolimit/) {
 3757:                             if ($limit) {
 3758:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3759:                             } else {
 3760:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3761:                             }
 3762:                         } elsif ($newval) {
 3763:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3764:                         } else {
 3765:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3766:                         }
 3767:                     } else {
 3768:                         if ($newval) {
 3769:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3770:                         } else {
 3771:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3772:                         }
 3773:                     }
 3774:                 } else {
 3775:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3776:                 }
 3777:             } else {
 3778:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3779:             }
 3780:         }
 3781:     }
 3782:     return;
 3783: }
 3784: 
 3785: sub update_roles {
 3786:     my ($r,$context,$showcredits) = @_;
 3787:     my $now=time;
 3788:     my @rolechanges;
 3789:     my %disallowed;
 3790:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3791:     foreach my $key (keys(%env)) {
 3792: 	next if (! $env{$key});
 3793:         next if ($key eq 'form.action');
 3794: 	# Revoke roles
 3795: 	if ($key=~/^form\.rev/) {
 3796: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3797: # Revoke standard role
 3798: 		my ($scope,$role) = ($1,$2);
 3799: 		my $result =
 3800: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3801: 						$env{'form.ccuname'},
 3802: 						$scope,$role,'','',$context);
 3803:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3804:                             &mt('Revoking [_1] in [_2]',
 3805:                                 &Apache::lonnet::plaintext($role),
 3806:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3807:                                 $result ne "ok").'<br />');
 3808:                 if ($result ne "ok") {
 3809:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3810:                 }
 3811: 		if ($role eq 'st') {
 3812: 		    my $result = 
 3813:                         &Apache::lonuserutils::classlist_drop($scope,
 3814:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3815: 			    $now);
 3816:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3817: 		}
 3818:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3819:                     push(@rolechanges,$role);
 3820:                 }
 3821: 	    }
 3822: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3823: # Revoke custom role
 3824:                 my $result = &Apache::lonnet::revokecustomrole(
 3825:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3826:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3827:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3828:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3829:                             $result ne 'ok').'<br />');
 3830:                 if ($result ne "ok") {
 3831:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3832:                 }
 3833:                 if (!grep(/^cr$/,@rolechanges)) {
 3834:                     push(@rolechanges,'cr');
 3835:                 }
 3836: 	    }
 3837: 	} elsif ($key=~/^form\.del/) {
 3838: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3839: # Delete standard role
 3840: 		my ($scope,$role) = ($1,$2);
 3841: 		my $result =
 3842: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3843: 						$env{'form.ccuname'},
 3844: 						$scope,$role,$now,0,1,'',
 3845:                                                 $context);
 3846:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3847:                             &mt('Deleting [_1] in [_2]',
 3848:                                 &Apache::lonnet::plaintext($role),
 3849:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3850:                             $result ne 'ok').'<br />');
 3851:                 if ($result ne "ok") {
 3852:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3853:                 }
 3854: 
 3855: 		if ($role eq 'st') {
 3856: 		    my $result = 
 3857:                         &Apache::lonuserutils::classlist_drop($scope,
 3858:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3859: 			    $now);
 3860: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3861: 		}
 3862:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3863:                     push(@rolechanges,$role);
 3864:                 }
 3865:             }
 3866: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3867:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3868: # Delete custom role
 3869:                 my $result =
 3870:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 3871:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 3872:                         0,1,$context);
 3873:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 3874:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3875:                       $result ne "ok").'<br />');
 3876:                 if ($result ne "ok") {
 3877:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3878:                 }
 3879: 
 3880:                 if (!grep(/^cr$/,@rolechanges)) {
 3881:                     push(@rolechanges,'cr');
 3882:                 }
 3883:             }
 3884: 	} elsif ($key=~/^form\.ren/) {
 3885:             my $udom = $env{'form.ccdomain'};
 3886:             my $uname = $env{'form.ccuname'};
 3887: # Re-enable standard role
 3888: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 3889:                 my $url = $1;
 3890:                 my $role = $2;
 3891:                 my $logmsg;
 3892:                 my $output;
 3893:                 if ($role eq 'st') {
 3894:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 3895:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 3896:                         my $credits;
 3897:                         if ($showcredits) {
 3898:                             my $defaultcredits = 
 3899:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3900:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 3901:                         }
 3902:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 3903:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 3904:                             if ($result eq 'refused' && $logmsg) {
 3905:                                 $output = $logmsg;
 3906:                             } else { 
 3907:                                 $output = &mt('Error: [_1]',$result)."\n";
 3908:                             }
 3909:                         } else {
 3910:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 3911:                                         &Apache::lonnet::plaintext($role),
 3912:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 3913:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 3914:                         }
 3915:                     }
 3916:                 } else {
 3917: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 3918:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 3919:                                $context);
 3920:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 3921:                                         &Apache::lonnet::plaintext($role),
 3922:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 3923:                     if ($result ne "ok") {
 3924:                         $output .= &mt('Error: [_1]',$result).'<br />';
 3925:                     }
 3926:                 }
 3927:                 $r->print($output);
 3928:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3929:                     push(@rolechanges,$role);
 3930:                 }
 3931: 	    }
 3932: # Re-enable custom role
 3933: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3934:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3935:                 my $result = &Apache::lonnet::assigncustomrole(
 3936:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 3937:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 3938:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3939:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 3940:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3941:                     $result ne "ok").'<br />');
 3942:                 if ($result ne "ok") {
 3943:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3944:                 }
 3945:                 if (!grep(/^cr$/,@rolechanges)) {
 3946:                     push(@rolechanges,'cr');
 3947:                 }
 3948:             }
 3949: 	} elsif ($key=~/^form\.act/) {
 3950:             my $udom = $env{'form.ccdomain'};
 3951:             my $uname = $env{'form.ccuname'};
 3952: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 3953:                 # Activate a custom role
 3954: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 3955: 		my $url='/'.$one.'/'.$two;
 3956: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 3957: 
 3958:                 my $start = ( $env{'form.start_'.$full} ?
 3959:                               $env{'form.start_'.$full} :
 3960:                               $now );
 3961:                 my $end   = ( $env{'form.end_'.$full} ?
 3962:                               $env{'form.end_'.$full} :
 3963:                               0 );
 3964:                                                                                      
 3965:                 # split multiple sections
 3966:                 my %sections = ();
 3967:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 3968:                 if ($num_sections == 0) {
 3969:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 3970:                 } else {
 3971: 		    my %curr_groups =
 3972: 			&Apache::longroup::coursegroups($one,$two);
 3973:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 3974:                         if (($sec eq 'none') || ($sec eq 'all') || 
 3975:                             exists($curr_groups{$sec})) {
 3976:                             $disallowed{$sec} = $url;
 3977:                             next;
 3978:                         }
 3979:                         my $securl = $url.'/'.$sec;
 3980: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 3981:                     }
 3982:                 }
 3983:                 if (!grep(/^cr$/,@rolechanges)) {
 3984:                     push(@rolechanges,'cr');
 3985:                 }
 3986: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 3987: 		# Activate roles for sections with 3 id numbers
 3988: 		# set start, end times, and the url for the class
 3989: 		my ($one,$two,$three)=($1,$2,$3);
 3990: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 3991: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 3992: 			      $now );
 3993: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 3994: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 3995: 			      0 );
 3996: 		my $url='/'.$one.'/'.$two;
 3997:                 my $type = 'three';
 3998:                 # split multiple sections
 3999:                 my %sections = ();
 4000:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4001:                 my $credits;
 4002:                 if ($three eq 'st') {
 4003:                     if ($showcredits) { 
 4004:                         my $defaultcredits = 
 4005:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4006:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4007:                         $credits =~ s/[^\d\.]//g;
 4008:                         if ($credits eq $defaultcredits) {
 4009:                             undef($credits);
 4010:                         }
 4011:                     }
 4012:                 }
 4013:                 if ($num_sections == 0) {
 4014:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4015:                 } else {
 4016:                     my %curr_groups = 
 4017: 			&Apache::longroup::coursegroups($one,$two);
 4018:                     my $emptysec = 0;
 4019:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4020:                         $sec =~ s/\W//g;
 4021:                         if ($sec ne '') {
 4022:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4023:                                 exists($curr_groups{$sec})) {
 4024:                                 $disallowed{$sec} = $url;
 4025:                                 next;
 4026:                             }
 4027:                             my $securl = $url.'/'.$sec;
 4028:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4029:                         } else {
 4030:                             $emptysec = 1;
 4031:                         }
 4032:                     }
 4033:                     if ($emptysec) {
 4034:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4035:                     }
 4036:                 }
 4037:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4038:                     push(@rolechanges,$three);
 4039:                 }
 4040: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4041: 		# Activate roles for sections with two id numbers
 4042: 		# set start, end times, and the url for the class
 4043: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4044: 			      $env{'form.start_'.$1.'_'.$2} : 
 4045: 			      $now );
 4046: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4047: 			      $env{'form.end_'.$1.'_'.$2} :
 4048: 			      0 );
 4049:                 my $one = $1;
 4050:                 my $two = $2;
 4051: 		my $url='/'.$one.'/';
 4052:                 # split multiple sections
 4053:                 my %sections = ();
 4054:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4055:                 if ($num_sections == 0) {
 4056:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4057:                 } else {
 4058:                     my $emptysec = 0;
 4059:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4060:                         if ($sec ne '') {
 4061:                             my $securl = $url.'/'.$sec;
 4062:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4063:                         } else {
 4064:                             $emptysec = 1;
 4065:                         }
 4066:                     }
 4067:                     if ($emptysec) {
 4068:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4069:                     }
 4070:                 }
 4071:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4072:                     push(@rolechanges,$two);
 4073:                 }
 4074: 	    } else {
 4075: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4076:             }
 4077:             foreach my $key (sort(keys(%disallowed))) {
 4078:                 $r->print('<p class="LC_warning">');
 4079:                 if (($key eq 'none') || ($key eq 'all')) {  
 4080:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4081:                 } else {
 4082:                     $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>'));
 4083:                 }
 4084:                 $r->print('</p><p>'
 4085:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4086:                              ,'<a href="javascript:history.go(-1)'
 4087:                              ,'</a>')
 4088:                          .'</p><br />'
 4089:                 );
 4090:             }
 4091: 	}
 4092:     } # End of foreach (keys(%env))
 4093: # Flush the course logs so reverse user roles immediately updated
 4094:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4095:     if (@rolechanges == 0) {
 4096:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4097:     }
 4098:     return @rolechanges;
 4099: }
 4100: 
 4101: sub get_user_credits {
 4102:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4103:     if ($cdom eq '' || $cnum eq '') {
 4104:         return unless ($env{'request.course.id'});
 4105:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4106:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4107:     }
 4108:     my $credits;
 4109:     my %currhash =
 4110:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4111:     if (keys(%currhash) > 0) {
 4112:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4113:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4114:         $credits = $items[$crdidx];
 4115:         $credits =~ s/[^\d\.]//g;
 4116:     }
 4117:     if ($credits eq $defaultcredits) {
 4118:         undef($credits);
 4119:     }
 4120:     return $credits;
 4121: }
 4122: 
 4123: sub enroll_single_student {
 4124:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4125:         $showcredits,$defaultcredits) = @_;
 4126:     $r->print('<h3>');
 4127:     if ($crstype eq 'Community') {
 4128:         $r->print(&mt('Enrolling Member'));
 4129:     } else {
 4130:         $r->print(&mt('Enrolling Student'));
 4131:     }
 4132:     $r->print('</h3>');
 4133: 
 4134:     # Remove non alphanumeric values from section
 4135:     $env{'form.sections'}=~s/\W//g;
 4136: 
 4137:     my $credits;
 4138:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4139:         $credits = $env{'form.credits'};
 4140:         $credits =~ s/[^\d\.]//g;
 4141:         if ($credits ne '') {
 4142:             if ($credits eq $defaultcredits) {
 4143:                 undef($credits);
 4144:             }
 4145:         }
 4146:     }
 4147: 
 4148:     # Clean out any old student roles the user has in this class.
 4149:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4150:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4151:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4152:     my $enroll_result =
 4153:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4154:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4155:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4156:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4157:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4158:             $credits);
 4159:     if ($enroll_result =~ /^ok/) {
 4160:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4161:         if ($env{'form.sections'} ne '') {
 4162:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4163:         }
 4164:         my ($showstart,$showend);
 4165:         if ($startdate <= $now) {
 4166:             $showstart = &mt('Access starts immediately');
 4167:         } else {
 4168:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4169:         }
 4170:         if ($enddate == 0) {
 4171:             $showend = &mt('ends: no ending date');
 4172:         } else {
 4173:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4174:         }
 4175:         $r->print('.<br />'.$showstart.'; '.$showend);
 4176:         if ($startdate <= $now && !$newuser) {
 4177:             $r->print('<p class="LC_info">');
 4178:             if ($crstype eq 'Community') {
 4179:                 $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.'));
 4180:             } else {
 4181:                 $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.'));
 4182:            }
 4183:            $r->print('</p>');
 4184:         }
 4185:     } else {
 4186:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4187:     }
 4188:     return;
 4189: }
 4190: 
 4191: sub get_defaultquota_text {
 4192:     my ($settingstatus) = @_;
 4193:     my $defquotatext; 
 4194:     if ($settingstatus eq '') {
 4195:         $defquotatext = &mt('default');
 4196:     } else {
 4197:         my ($usertypes,$order) =
 4198:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4199:         if ($usertypes->{$settingstatus} eq '') {
 4200:             $defquotatext = &mt('default');
 4201:         } else {
 4202:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4203:         }
 4204:     }
 4205:     return $defquotatext;
 4206: }
 4207: 
 4208: sub update_result_form {
 4209:     my ($uhome) = @_;
 4210:     my $outcome = 
 4211:     '<form name="userupdate" method="post" action="">'."\n";
 4212:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4213:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4214:     }
 4215:     if ($env{'form.origname'} ne '') {
 4216:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4217:     }
 4218:     foreach my $item ('sortby','seluname','seludom') {
 4219:         if (exists($env{'form.'.$item})) {
 4220:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4221:         }
 4222:     }
 4223:     if ($uhome eq 'no_host') {
 4224:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4225:     }
 4226:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4227:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4228:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4229:                 '</form>';
 4230:     return $outcome;
 4231: }
 4232: 
 4233: sub quota_admin {
 4234:     my ($setquota,$changeHash,$name) = @_;
 4235:     my $quotachanged;
 4236:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4237:         # Current user has quota modification privileges
 4238:         if (ref($changeHash) eq 'HASH') {
 4239:             $quotachanged = 1;
 4240:             $changeHash->{$name.'quota'} = $setquota;
 4241:         }
 4242:     }
 4243:     return $quotachanged;
 4244: }
 4245: 
 4246: sub tool_admin {
 4247:     my ($tool,$settool,$changeHash,$context) = @_;
 4248:     my $canchange = 0; 
 4249:     if ($context eq 'requestcourses') {
 4250:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4251:             $canchange = 1;
 4252:         }
 4253:     } elsif ($context eq 'reqcrsotherdom') {
 4254:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4255:             $canchange = 1;
 4256:         }
 4257:     } elsif ($context eq 'requestauthor') {
 4258:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4259:             $canchange = 1;
 4260:         }
 4261:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4262:         # Current user has quota modification privileges
 4263:         $canchange = 1;
 4264:     }
 4265:     my $toolchanged;
 4266:     if ($canchange) {
 4267:         if (ref($changeHash) eq 'HASH') {
 4268:             $toolchanged = 1;
 4269:             if ($tool eq 'requestauthor') {
 4270:                 $changeHash->{$context} = $settool;
 4271:             } else {
 4272:                 $changeHash->{$context.'.'.$tool} = $settool;
 4273:             }
 4274:         }
 4275:     }
 4276:     return $toolchanged;
 4277: }
 4278: 
 4279: sub build_roles {
 4280:     my ($sectionstr,$sections,$role) = @_;
 4281:     my $num_sections = 0;
 4282:     if ($sectionstr=~ /,/) {
 4283:         my @secnums = split/,/,$sectionstr;
 4284:         if ($role eq 'st') {
 4285:             $secnums[0] =~ s/\W//g;
 4286:             $$sections{$secnums[0]} = 1;
 4287:             $num_sections = 1;
 4288:         } else {
 4289:             foreach my $sec (@secnums) {
 4290:                 $sec =~ ~s/\W//g;
 4291:                 if (!($sec eq "")) {
 4292:                     if (exists($$sections{$sec})) {
 4293:                         $$sections{$sec} ++;
 4294:                     } else {
 4295:                         $$sections{$sec} = 1;
 4296:                         $num_sections ++;
 4297:                     }
 4298:                 }
 4299:             }
 4300:         }
 4301:     } else {
 4302:         $sectionstr=~s/\W//g;
 4303:         unless ($sectionstr eq '') {
 4304:             $$sections{$sectionstr} = 1;
 4305:             $num_sections ++;
 4306:         }
 4307:     }
 4308: 
 4309:     return $num_sections;
 4310: }
 4311: 
 4312: # ========================================================== Custom Role Editor
 4313: 
 4314: sub custom_role_editor {
 4315:     my ($r,$brcrum,$prefix) = @_;
 4316:     my $action = $env{'form.customroleaction'};
 4317:     my $rolename; 
 4318:     if ($action eq 'new') {
 4319:         $rolename=$env{'form.newrolename'};
 4320:     } else {
 4321:         $rolename=$env{'form.rolename'};
 4322:     }
 4323: 
 4324:     my ($crstype,$context);
 4325:     if ($env{'request.course.id'}) {
 4326:         $crstype = &Apache::loncommon::course_type();
 4327:         $context = 'course';
 4328:     } else {
 4329:         $context = 'domain';
 4330:         $crstype = 'course';
 4331:     }
 4332: 
 4333:     $rolename=~s/[^A-Za-z0-9]//gs;
 4334:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4335: 	&print_username_entry_form($r,undef,undef,undef,undef,$crstype,$brcrum);
 4336:         return;
 4337:     }
 4338: 
 4339:     my $formname = 'form1';
 4340:     my %privs=();
 4341:     my $body_top = '<h2>';
 4342: # ------------------------------------------------------- Does this role exist?
 4343:     my ($rdummy,$roledef)=
 4344: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4345:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4346:         $body_top .= &mt('Existing Role').' "';
 4347: # ------------------------------------------------- Get current role privileges
 4348:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4349:         if ($privs{'system'} =~ /bre\&S/) {
 4350:             if ($context eq 'domain') {
 4351:                 $crstype = 'Course';
 4352:             } elsif ($crstype eq 'Community') {
 4353:                 $privs{'system'} =~ s/bre\&S//;
 4354:             }
 4355:         } elsif ($context eq 'domain') {
 4356:             $crstype = 'Course';
 4357:         }
 4358:     } else {
 4359:         $body_top .= &mt('New Role').' "';
 4360:         $roledef='';
 4361:     }
 4362:     $body_top .= $rolename.'"</h2>';
 4363: 
 4364: # ------------------------------------------------------- What can be assigned?
 4365:     my %full=();
 4366:     my %levels=(
 4367:                  course => {},
 4368:                  domain => {},
 4369:                  system => {},
 4370:                );
 4371:     my %levelscurrent=(
 4372:                         course => {},
 4373:                         domain => {},
 4374:                         system => {},
 4375:                       );
 4376:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4377:     my ($jsback,$elements) = &crumb_utilities();
 4378:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4379:     my $head_script =
 4380:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4381:                                                   \%full,\@templateroles,$jsback);
 4382:     push (@{$brcrum},
 4383:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4384:                text => "Pick custom role",
 4385:                faq  => 282,bug=>'Instructor Interface',},
 4386:               {href => "javascript:backPage(document.$formname,'','')",
 4387:                text => "Edit custom role",
 4388:                faq  => 282,
 4389:                bug  => 'Instructor Interface',
 4390:                help => 'Course_Editing_Custom_Roles'}
 4391:               );
 4392:     my $args = { bread_crumbs          => $brcrum,
 4393:                  bread_crumbs_component => 'User Management'};
 4394:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4395:                                              $head_script,$args).
 4396:               $body_top);
 4397:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4398:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4399:                                                         \@templateroles,$prefix));
 4400: 
 4401:     $r->print(<<ENDCCF);
 4402: <input type="hidden" name="phase" value="set_custom_roles" />
 4403: <input type="hidden" name="rolename" value="$rolename" />
 4404: ENDCCF
 4405:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4406:                                                        \%levelscurrent,$prefix));
 4407:     $r->print(&Apache::loncommon::end_data_table().
 4408:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4409:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4410:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4411:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4412:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4413: }
 4414: 
 4415: # ---------------------------------------------------------- Call to definerole
 4416: sub set_custom_role {
 4417:     my ($r,$context,$brcrum,$prefix) = @_;
 4418:     my $rolename=$env{'form.rolename'};
 4419:     $rolename=~s/[^A-Za-z0-9]//gs;
 4420:     if (!$rolename) {
 4421: 	&custom_role_editor($r,$brcrum,$prefix);
 4422:         return;
 4423:     }
 4424:     my ($jsback,$elements) = &crumb_utilities();
 4425:     my $jscript = '<script type="text/javascript">'
 4426:                  .'// <![CDATA['."\n"
 4427:                  .$jsback."\n"
 4428:                  .'// ]]>'."\n"
 4429:                  .'</script>'."\n";
 4430:     push(@{$brcrum},
 4431:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4432:          text => "Pick custom role",
 4433:          faq  => 282,
 4434:          bug  => 'Instructor Interface',},
 4435:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4436:          text => "Edit custom role",
 4437:          faq  => 282,
 4438:          bug  => 'Instructor Interface',},
 4439:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4440:          text => "Result",
 4441:          faq  => 282,
 4442:          bug  => 'Instructor Interface',
 4443:          help => 'Course_Editing_Custom_Roles'},
 4444:         );
 4445:     my $args = { bread_crumbs           => $brcrum,
 4446:                  bread_crumbs_component => 'User Management'};
 4447:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4448: 
 4449:     my $newrole;
 4450:     my ($rdummy,$roledef)=
 4451: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4452: 
 4453: # ------------------------------------------------------- Does this role exist?
 4454:     $r->print('<h3>');
 4455:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4456: 	$r->print(&mt('Existing Role').' "');
 4457:     } else {
 4458: 	$r->print(&mt('New Role').' "');
 4459: 	$roledef='';
 4460:         $newrole = 1;
 4461:     }
 4462:     $r->print($rolename.'"</h3>');
 4463: # ------------------------------------------------- Assign role and show result
 4464: 
 4465:     my $errmsg;
 4466:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4467:     # Assign role and return result
 4468:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4469:                                              $newprivs{'c'});
 4470:     if ($result ne 'ok') {
 4471:         $errmsg = ': '.$result;
 4472:     }
 4473:     my $message =
 4474:         &Apache::lonhtmlcommon::confirm_success(
 4475:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4476:     if ($env{'request.course.id'}) {
 4477:         my $url='/'.$env{'request.course.id'};
 4478:         $url=~s/\_/\//g;
 4479:         $result =
 4480:             &Apache::lonnet::assigncustomrole(
 4481:                 $env{'user.domain'},$env{'user.name'},
 4482:                 $url,
 4483:                 $env{'user.domain'},$env{'user.name'},
 4484:                 $rolename,undef,undef,undef,$context);
 4485:         if ($result ne 'ok') {
 4486:             $errmsg = ': '.$result;
 4487:         }
 4488:         $message .=
 4489:             '<br />'
 4490:            .&Apache::lonhtmlcommon::confirm_success(
 4491:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4492:     }
 4493:     $r->print(
 4494:         &Apache::loncommon::confirmwrapper($message)
 4495:        .'<br />'
 4496:        .&Apache::lonhtmlcommon::actionbox([
 4497:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4498:            .&mt('Create or edit another custom role')
 4499:            .'</a>'])
 4500:        .'<form name="customresult" method="post" action="">'
 4501:        .&Apache::lonhtmlcommon::echo_form_input([])
 4502:        .'</form>'
 4503:     );
 4504: }
 4505: 
 4506: # ================================================================ Main Handler
 4507: sub handler {
 4508:     my $r = shift;
 4509:     if ($r->header_only) {
 4510:        &Apache::loncommon::content_type($r,'text/html');
 4511:        $r->send_http_header;
 4512:        return OK;
 4513:     }
 4514:     my ($context,$crstype);
 4515:     if ($env{'request.course.id'}) {
 4516:         $context = 'course';
 4517:         $crstype = &Apache::loncommon::course_type();
 4518:     } elsif ($env{'request.role'} =~ /^au\./) {
 4519:         $context = 'author';
 4520:     } else {
 4521:         $context = 'domain';
 4522:     }
 4523: 
 4524:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4525:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4526:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4527:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4528:     my $args;
 4529:     my $brcrum = [];
 4530:     my $bread_crumbs_component = 'User Management';
 4531:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4532:         $brcrum = [{href=>"/adm/createuser",
 4533:                     text=>"User Management",
 4534:                     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'}
 4535:                   ];
 4536:     }
 4537:     #SD Following files not added to help, because the corresponding .tex-files seem to
 4538:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
 4539:     my ($permission,$allowed) = 
 4540:         &Apache::lonuserutils::get_permission($context,$crstype);
 4541:     if (!$allowed) {
 4542:         if ($context eq 'course') {
 4543:             $r->internal_redirect('/adm/viewclasslist');
 4544:             return OK;
 4545:         }
 4546:         $env{'user.error.msg'}=
 4547:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4548:                                  "or view user status.";
 4549:         return HTTP_NOT_ACCEPTABLE;
 4550:     }
 4551: 
 4552:     &Apache::loncommon::content_type($r,'text/html');
 4553:     $r->send_http_header;
 4554: 
 4555:     my $showcredits;
 4556:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4557:          ($context eq 'domain')) {
 4558:         my %domdefaults = 
 4559:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4560:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4561:             $showcredits = 1;
 4562:         }
 4563:     }
 4564: 
 4565:     # Main switch on form.action and form.state, as appropriate
 4566:     if (! exists($env{'form.action'})) {
 4567:         $args = {bread_crumbs => $brcrum,
 4568:                  bread_crumbs_component => $bread_crumbs_component}; 
 4569:         $r->print(&header(undef,$args));
 4570:         $r->print(&print_main_menu($permission,$context,$crstype));
 4571:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4572:         push(@{$brcrum},
 4573:               { href => '/adm/createuser?action=upload&state=',
 4574:                 text => 'Upload Users List',
 4575:                 help => 'Course_Create_Class_List',
 4576:               });
 4577:         $bread_crumbs_component = 'Upload Users List';
 4578:         $args = {bread_crumbs           => $brcrum,
 4579:                  bread_crumbs_component => $bread_crumbs_component};
 4580:         $r->print(&header(undef,$args));
 4581:         $r->print('<form name="studentform" method="post" '.
 4582:                   'enctype="multipart/form-data" '.
 4583:                   ' action="/adm/createuser">'."\n");
 4584:         if (! exists($env{'form.state'})) {
 4585:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4586:         } elsif ($env{'form.state'} eq 'got_file') {
 4587:             &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4588:                                                              $crstype,$showcredits);
 4589:         } elsif ($env{'form.state'} eq 'enrolling') {
 4590:             if ($env{'form.datatoken'}) {
 4591:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission,
 4592:                                                        $showcredits);
 4593:             }
 4594:         } else {
 4595:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4596:         }
 4597:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4598:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4599:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4600:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4601:         my $phase = $env{'form.phase'};
 4602:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4603: 	&Apache::loncreateuser::restore_prev_selections();
 4604: 	my $srch;
 4605: 	foreach my $item (@search) {
 4606: 	    $srch->{$item} = $env{'form.'.$item};
 4607: 	}
 4608:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4609:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4610:             if ($env{'form.phase'} eq 'createnewuser') {
 4611:                 my $response;
 4612:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4613:                     my $response =
 4614:                         '<span class="LC_warning">'
 4615:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4616:                            .' letters numbers - . @')
 4617:                        .'</span>';
 4618:                     $env{'form.phase'} = '';
 4619:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4620:                                                $crstype,$brcrum,$showcredits);
 4621:                 } else {
 4622:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4623:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4624:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4625:                                                   $srch,$response,$context,
 4626:                                                   $permission,$crstype,$brcrum,
 4627:                                                   $showcredits);
 4628:                 }
 4629:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4630:                 my ($currstate,$response,$forcenewuser,$results) = 
 4631:                     &user_search_result($context,$srch);
 4632:                 if ($env{'form.currstate'} eq 'modify') {
 4633:                     $currstate = $env{'form.currstate'};
 4634:                 }
 4635:                 if ($currstate eq 'select') {
 4636:                     &print_user_selection_page($r,$response,$srch,$results,
 4637:                                                \@search,$context,undef,$crstype,
 4638:                                                $brcrum);
 4639:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4640:                     my ($ccuname,$ccdomain,$uhome);
 4641:                     if (($srch->{'srchby'} eq 'uname') && 
 4642:                         ($srch->{'srchtype'} eq 'exact')) {
 4643:                         $ccuname = $srch->{'srchterm'};
 4644:                         $ccdomain= $srch->{'srchdomain'};
 4645:                     } else {
 4646:                         my @matchedunames = keys(%{$results});
 4647:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4648:                     }
 4649:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4650:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4651:                     if ($env{'form.action'} eq 'accesslogs') {
 4652:                         my $uhome;
 4653:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4654:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4655:                         }
 4656:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4657:                             $env{'form.phase'} = '';
 4658:                             undef($forcenewuser);
 4659:                             #if ($response) {
 4660:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4661:                             #        $response .= '<br /><br />';
 4662:                             #    }
 4663:                             #}
 4664:                             &print_username_entry_form($r,$context,$response,$srch,
 4665:                                                        $forcenewuser,$crstype,$brcrum);
 4666:                         } else {
 4667:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4668:                         }
 4669:                     } else {
 4670:                         if ($env{'form.forcenewuser'}) {
 4671:                             $response = '';
 4672:                         }
 4673:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4674:                                                       $srch,$response,$context,
 4675:                                                       $permission,$crstype,$brcrum);
 4676:                     }
 4677:                 } elsif ($currstate eq 'query') {
 4678:                     &print_user_query_page($r,'createuser',$brcrum);
 4679:                 } else {
 4680:                     $env{'form.phase'} = '';
 4681:                     &print_username_entry_form($r,$context,$response,$srch,
 4682:                                                $forcenewuser,$crstype,$brcrum);
 4683:                 }
 4684:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4685:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4686:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4687:                 if ($env{'form.action'} eq 'accesslogs') {
 4688:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4689:                 } else {
 4690:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4691:                                                   $context,$permission,$crstype,
 4692:                                                   $brcrum);
 4693:                 }
 4694:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4695:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4696:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4697:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4698:             }
 4699:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4700:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4701:         } else {
 4702:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4703:                                        $brcrum);
 4704:         }
 4705:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4706:         my $prefix;
 4707:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4708:             &set_custom_role($r,$context,$brcrum,$prefix);
 4709:         } else {
 4710:             &custom_role_editor($r,$brcrum,$prefix);
 4711:         }
 4712:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4713:              ($permission->{'cusr'}) && 
 4714:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4715:         push(@{$brcrum},
 4716:                  {href => '/adm/createuser?action=processauthorreq',
 4717:                   text => 'Authoring Space requests',
 4718:                   help => 'Domain_Role_Approvals'});
 4719:         $bread_crumbs_component = 'Authoring requests';
 4720:         if ($env{'form.state'} eq 'done') {
 4721:             push(@{$brcrum},
 4722:                      {href => '/adm/createuser?action=authorreqqueue',
 4723:                       text => 'Result',
 4724:                       help => 'Domain_Role_Approvals'});
 4725:             $bread_crumbs_component = 'Authoring request result';
 4726:         }
 4727:         $args = { bread_crumbs           => $brcrum,
 4728:                   bread_crumbs_component => $bread_crumbs_component};
 4729:         my $js = &usernamerequest_javascript();
 4730:         $r->print(&header(&add_script($js),$args));
 4731:         if (!exists($env{'form.state'})) {
 4732:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4733:                                                                             $env{'request.role.domain'}));
 4734:         } elsif ($env{'form.state'} eq 'done') {
 4735:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4736:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4737:                                                                          $env{'request.role.domain'}));
 4738:         }
 4739:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4740:              ($permission->{'cusr'}) &&
 4741:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4742:         push(@{$brcrum},
 4743:                  {href => '/adm/createuser?action=processusernamereq',
 4744:                   text => 'LON-CAPA account requests',
 4745:                   help => 'Domain_Username_Approvals'});
 4746:         $bread_crumbs_component = 'Account requests';
 4747:         if ($env{'form.state'} eq 'done') {
 4748:             push(@{$brcrum},
 4749:                      {href => '/adm/createuser?action=usernamereqqueue',
 4750:                       text => 'Result',
 4751:                       help => 'Domain_Username_Approvals'});
 4752:             $bread_crumbs_component = 'LON-CAPA account request result';
 4753:         }
 4754:         $args = { bread_crumbs           => $brcrum,
 4755:                   bread_crumbs_component => $bread_crumbs_component};
 4756:         my $js = &usernamerequest_javascript();
 4757:         $r->print(&header(&add_script($js),$args));
 4758:         if (!exists($env{'form.state'})) {
 4759:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4760:                                                                             $env{'request.role.domain'}));
 4761:         } elsif ($env{'form.state'} eq 'done') {
 4762:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4763:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4764:                                                                          $env{'request.role.domain'}));
 4765:         }
 4766:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4767:              ($permission->{'cusr'})) {
 4768:         my $dom = $env{'form.domain'};
 4769:         my $uname = $env{'form.username'};
 4770:         my $warning;
 4771:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 4772:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 4773:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 4774:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 4775:                     if ($uhome eq 'no_host') {
 4776:                         my $queue = $env{'form.queue'};
 4777:                         my $reqkey = &escape($uname).'_'.$queue; 
 4778:                         my $namespace = 'usernamequeue';
 4779:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 4780:                         my %queued =
 4781:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 4782:                         unless ($queued{$reqkey}) {
 4783:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 4784:                         }
 4785:                     } else {
 4786:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 4787:                     }
 4788:                 } else {
 4789:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 4790:                 }
 4791:             } else {
 4792:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 4793:             }
 4794:         } else {
 4795:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 4796:         }
 4797:         my $args = { only_body => 1 };
 4798:         $r->print(&header(undef,$args).
 4799:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 4800:         if ($warning ne '') {
 4801:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 4802:         } else {
 4803:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4804:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 4805:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 4806:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 4807:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 4808:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 4809:                         my %info =
 4810:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 4811:                         if (ref($info{$uname}) eq 'HASH') {
 4812:                             my $usertype = $info{$uname}{'inststatus'};
 4813:                             unless ($usertype) {
 4814:                                 $usertype = 'default';
 4815:                             }
 4816:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 4817:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 4818:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 4819:                                     my ($num,$count,$showstatus);
 4820:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 4821:                                     unless ($usertype eq 'default') {
 4822:                                         my ($othertitle,$usertypes,$types) = 
 4823:                                             &Apache::loncommon::sorted_inst_types($dom);
 4824:                                         if (ref($usertypes) eq 'HASH') {
 4825:                                             if ($usertypes->{$usertype}) {
 4826:                                                 $showstatus = $usertypes->{$usertype};
 4827:                                                 $count ++;
 4828:                                             }
 4829:                                         }
 4830:                                     }
 4831:                                     foreach my $field (@{$infofields}) {
 4832:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 4833:                                         next unless ($infotitles->{$field});
 4834:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 4835:                                                   $info{$uname}{$field});
 4836:                                         $num ++;
 4837:                                         if ($count == $num) {
 4838:                                             $r->print(&Apache::lonhtmlcommon::row_closure(1));
 4839:                                         } else {
 4840:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 4841:                                         }
 4842:                                     }
 4843:                                     if ($showstatus) {
 4844:                                         $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type (self-reported)')).
 4845:                                                   $showstatus.
 4846:                                                   &Apache::lonhtmlcommon::row_closure(1));
 4847:                                     }
 4848:                                     $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 4849:                                 }
 4850:                             }
 4851:                         }
 4852:                     }
 4853:                 }
 4854:             }
 4855:             $r->print(&close_popup_form());
 4856:         }
 4857:     } elsif (($env{'form.action'} eq 'listusers') && 
 4858:              ($permission->{'view'} || $permission->{'cusr'})) {
 4859:         if ($env{'form.phase'} eq 'bulkchange') {
 4860:             push(@{$brcrum},
 4861:                     {href => '/adm/createuser?action=listusers',
 4862:                      text => "List Users"},
 4863:                     {href => "/adm/createuser",
 4864:                      text => "Result",
 4865:                      help => 'Course_View_Class_List'});
 4866:             $bread_crumbs_component = 'Update Users';
 4867:             $args = {bread_crumbs           => $brcrum,
 4868:                      bread_crumbs_component => $bread_crumbs_component};
 4869:             $r->print(&header(undef,$args));
 4870:             my $setting = $env{'form.roletype'};
 4871:             my $choice = $env{'form.bulkaction'};
 4872:             if ($permission->{'cusr'}) {
 4873:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 4874:             } else {
 4875:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 4876:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 4877:             }
 4878:         } else {
 4879:             push(@{$brcrum},
 4880:                     {href => '/adm/createuser?action=listusers',
 4881:                      text => "List Users",
 4882:                      help => 'Course_View_Class_List'});
 4883:             $bread_crumbs_component = 'List Users';
 4884:             $args = {bread_crumbs           => $brcrum,
 4885:                      bread_crumbs_component => $bread_crumbs_component};
 4886:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 4887:             my $formname = 'studentform';
 4888:             my $hidecall = "hide_searching();";
 4889:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 4890:                 ($env{'form.roletype'} eq 'community'))) {
 4891:                 if ($env{'form.roletype'} eq 'course') {
 4892:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 4893:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 4894:                                                                 $formname);
 4895:                 } elsif ($env{'form.roletype'} eq 'community') {
 4896:                     $cb_jscript = 
 4897:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 4898:                     my %elements = (
 4899:                                       coursepick => 'radio',
 4900:                                       coursetotal => 'text',
 4901:                                       courselist => 'text',
 4902:                                    );
 4903:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 4904:                 }
 4905:                 $jscript .= &verify_user_display($context)."\n".
 4906:                             &Apache::loncommon::check_uncheck_jscript();
 4907:                 my $js = &add_script($jscript).$cb_jscript;
 4908:                 my $loadcode = 
 4909:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 4910:                 if ($loadcode ne '') {
 4911:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 4912:                 } else {
 4913:                     $args->{add_entries} = {onload => $hidecall};
 4914:                 }
 4915:                 $r->print(&header($js,$args));
 4916:             } else {
 4917:                 $args->{add_entries} = {onload => $hidecall};
 4918:                 $jscript = &verify_user_display($context).
 4919:                            &Apache::loncommon::check_uncheck_jscript(); 
 4920:                 $r->print(&header(&add_script($jscript),$args));
 4921:             }
 4922:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 4923:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 4924:                          $showcredits);
 4925:         }
 4926:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 4927:         my $brtext;
 4928:         if ($crstype eq 'Community') {
 4929:             $brtext = 'Drop Members';
 4930:         } else {
 4931:             $brtext = 'Drop Students';
 4932:         }
 4933:         push(@{$brcrum},
 4934:                 {href => '/adm/createuser?action=drop',
 4935:                  text => $brtext,
 4936:                  help => 'Course_Drop_Student'});
 4937:         if ($env{'form.state'} eq 'done') {
 4938:             push(@{$brcrum},
 4939:                      {href=>'/adm/createuser?action=drop',
 4940:                       text=>"Result"});
 4941:         }
 4942:         $bread_crumbs_component = $brtext;
 4943:         $args = {bread_crumbs           => $brcrum,
 4944:                  bread_crumbs_component => $bread_crumbs_component}; 
 4945:         $r->print(&header(undef,$args));
 4946:         if (!exists($env{'form.state'})) {
 4947:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 4948:         } elsif ($env{'form.state'} eq 'done') {
 4949:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 4950:                                                     $env{'form.action'});
 4951:         }
 4952:     } elsif ($env{'form.action'} eq 'dateselect') {
 4953:         if ($permission->{'cusr'}) {
 4954:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4955:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 4956:                                                                    $crstype,$showcredits));
 4957:         } else {
 4958:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 4959:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 4960:         }
 4961:     } elsif ($env{'form.action'} eq 'selfenroll') {
 4962:         if ($permission->{selfenrolladmin}) {
 4963:             my $cid = $env{'request.course.id'};
 4964:             my $cdom = $env{'course.'.$cid.'.domain'};
 4965:             my $cnum = $env{'course.'.$cid.'.num'};
 4966:             my %currsettings = (
 4967:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 4968:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 4969:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 4970:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 4971:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 4972:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 4973:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 4974:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 4975:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 4976:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 4977:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 4978:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 4979:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 4980:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 4981:             );
 4982:             push(@{$brcrum},
 4983:                     {href => '/adm/createuser?action=selfenroll',
 4984:                      text => "Configure Self-enrollment",
 4985:                      help => 'Course_Self_Enrollment'});
 4986:             if (!exists($env{'form.state'})) {
 4987:                 $args = { bread_crumbs           => $brcrum,
 4988:                           bread_crumbs_component => 'Configure Self-enrollment'};
 4989:                 $r->print(&header(undef,$args));
 4990:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 4991:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 4992:             } elsif ($env{'form.state'} eq 'done') {
 4993:                 push (@{$brcrum},
 4994:                           {href=>'/adm/createuser?action=selfenroll',
 4995:                            text=>"Result"});
 4996:                 $args = { bread_crumbs           => $brcrum,
 4997:                           bread_crumbs_component => 'Self-enrollment result'};
 4998:                 $r->print(&header(undef,$args));
 4999:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5000:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5001:             }
 5002:         } else {
 5003:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5004:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5005:         }
 5006:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5007:         if ($permission->{selfenrolladmin}) {
 5008:             push(@{$brcrum},
 5009:                      {href => '/adm/createuser?action=selfenrollqueue',
 5010:                       text => 'Enrollment requests',
 5011:                       help => 'Course_Self_Enrollment'});
 5012:             $bread_crumbs_component = 'Enrollment requests';
 5013:             if ($env{'form.state'} eq 'done') {
 5014:                 push(@{$brcrum},
 5015:                          {href => '/adm/createuser?action=selfenrollqueue',
 5016:                           text => 'Result',
 5017:                           help => 'Course_Self_Enrollment'});
 5018:                 $bread_crumbs_component = 'Enrollment result';
 5019:             }
 5020:             $args = { bread_crumbs           => $brcrum,
 5021:                       bread_crumbs_component => $bread_crumbs_component};
 5022:             $r->print(&header(undef,$args));
 5023:             my $cid = $env{'request.course.id'};
 5024:             my $cdom = $env{'course.'.$cid.'.domain'};
 5025:             my $cnum = $env{'course.'.$cid.'.num'};
 5026:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5027:             if (!exists($env{'form.state'})) {
 5028:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5029:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5030:                                                                                 $cdom,$cnum));
 5031:             } elsif ($env{'form.state'} eq 'done') {
 5032:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5033:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5034:                               $cdom,$cnum,$coursedesc));
 5035:             }
 5036:         } else {
 5037:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5038:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5039:         }
 5040:     } elsif ($env{'form.action'} eq 'changelogs') {
 5041:         if ($permission->{cusr} || $permission->{view}) {
 5042:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5043:         } else {
 5044:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5045:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5046:         }
 5047:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5048:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5049:             if ($env{'form.state'} eq 'process') {
 5050:                 if ($permission->{'owner'}) {
 5051:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5052:                 } else {
 5053:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5054:                 }
 5055:             } else {
 5056:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5057:             }
 5058:         } else {
 5059:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5060:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5061:         }
 5062:     } else {
 5063:         $bread_crumbs_component = 'User Management';
 5064:         $args = { bread_crumbs           => $brcrum,
 5065:                   bread_crumbs_component => $bread_crumbs_component};
 5066:         $r->print(&header(undef,$args));
 5067:         $r->print(&print_main_menu($permission,$context,$crstype));
 5068:     }
 5069:     $r->print(&Apache::loncommon::end_page());
 5070:     return OK;
 5071: }
 5072: 
 5073: sub header {
 5074:     my ($jscript,$args) = @_;
 5075:     my $start_page;
 5076:     if (ref($args) eq 'HASH') {
 5077:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5078:     } else {
 5079:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5080:     }
 5081:     return $start_page;
 5082: }
 5083: 
 5084: sub add_script {
 5085:     my ($js) = @_;
 5086:     return '<script type="text/javascript">'."\n"
 5087:           .'// <![CDATA['."\n"
 5088:           .$js."\n"
 5089:           .'// ]]>'."\n"
 5090:           .'</script>'."\n";
 5091: }
 5092: 
 5093: sub usernamerequest_javascript {
 5094:     my $js = <<ENDJS;
 5095: 
 5096: function openusernamereqdisplay(dom,uname,queue) {
 5097:     var url = '/adm/createuser?action=displayuserreq';
 5098:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5099:     var title = 'Account_Request_Browser';
 5100:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5101:     options += ',width=700,height=600';
 5102:     var stdeditbrowser = open(url,title,options,'1');
 5103:     stdeditbrowser.focus();
 5104:     return;
 5105: }
 5106:  
 5107: ENDJS
 5108: }
 5109: 
 5110: sub close_popup_form {
 5111:     my $close= &mt('Close Window');
 5112:     return << "END";
 5113: <p><form name="displayreq" action="" method="post">
 5114: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5115: </form></p>
 5116: END
 5117: }
 5118: 
 5119: sub verify_user_display {
 5120:     my ($context) = @_;
 5121:     my %lt = &Apache::lonlocal::texthash (
 5122:         course    => 'course(s): description, section(s), status',
 5123:         community => 'community(s): description, section(s), status',
 5124:         author    => 'author',
 5125:     );
 5126:     my $photos;
 5127:     if (($context eq 'course') && $env{'request.course.id'}) {
 5128:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5129:     }
 5130:     my $output = <<"END";
 5131: 
 5132: function hide_searching() {
 5133:     if (document.getElementById('searching')) {
 5134:         document.getElementById('searching').style.display = 'none';
 5135:     }
 5136:     return;
 5137: }
 5138: 
 5139: function display_update() {
 5140:     document.studentform.action.value = 'listusers';
 5141:     document.studentform.phase.value = 'display';
 5142:     document.studentform.submit();
 5143: }
 5144: 
 5145: function updateCols(caller) {
 5146:     var context = '$context';
 5147:     var photos = '$photos';
 5148:     if (caller == 'Status') {
 5149:         if ((context == 'domain') && 
 5150:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5151:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5152:             document.getElementById('showcolstatus').checked = false;
 5153:             document.getElementById('showcolstatus').disabled = 'disabled';
 5154:             document.getElementById('showcolstart').checked = false;
 5155:             document.getElementById('showcolend').checked = false;
 5156:         } else {
 5157:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5158:                 document.getElementById('showcolstatus').checked = true;
 5159:                 document.getElementById('showcolstatus').disabled = '';
 5160:                 document.getElementById('showcolstart').checked = true;
 5161:                 document.getElementById('showcolend').checked = true;
 5162:             } else {
 5163:                 document.getElementById('showcolstatus').checked = false;
 5164:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5165:                 document.getElementById('showcolstart').checked = false;
 5166:                 document.getElementById('showcolend').checked = false;
 5167:             }
 5168:         }
 5169:     }
 5170:     if (caller == 'output') {
 5171:         if (photos == 1) {
 5172:             if (document.getElementById('showcolphoto')) {
 5173:                 var photoitem = document.getElementById('showcolphoto');
 5174:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5175:                     photoitem.checked = true;
 5176:                     photoitem.disabled = '';
 5177:                 } else {
 5178:                     photoitem.checked = false;
 5179:                     photoitem.disabled = 'disabled';
 5180:                 }
 5181:             }
 5182:         }
 5183:     }
 5184:     if (caller == 'showrole') {
 5185:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5186:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5187:             document.getElementById('showcolrole').checked = true;
 5188:             document.getElementById('showcolrole').disabled = '';
 5189:         } else {
 5190:             document.getElementById('showcolrole').checked = false;
 5191:             document.getElementById('showcolrole').disabled = 'disabled';
 5192:         }
 5193:         if (context == 'domain') {
 5194:             var quotausageshow = 0;
 5195:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5196:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5197:                 document.getElementById('showcolstatus').checked = false;
 5198:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5199:                 document.getElementById('showcolstart').checked = false;
 5200:                 document.getElementById('showcolend').checked = false;
 5201:             } else {
 5202:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5203:                     document.getElementById('showcolstatus').checked = true;
 5204:                     document.getElementById('showcolstatus').disabled = '';
 5205:                     document.getElementById('showcolstart').checked = true;
 5206:                     document.getElementById('showcolend').checked = true;
 5207:                 }
 5208:             }
 5209:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5210:                 document.getElementById('showcolextent').disabled = 'disabled';
 5211:                 document.getElementById('showcolextent').checked = 'false';
 5212:                 document.getElementById('showextent').style.display='none';
 5213:                 document.getElementById('showcoltextextent').innerHTML = '';
 5214:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5215:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5216:                     if (document.getElementById('showcolauthorusage')) {
 5217:                         document.getElementById('showcolauthorusage').disabled = '';
 5218:                     }
 5219:                     if (document.getElementById('showcolauthorquota')) {
 5220:                         document.getElementById('showcolauthorquota').disabled = '';
 5221:                     }
 5222:                     quotausageshow = 1;
 5223:                 }
 5224:             } else {
 5225:                 document.getElementById('showextent').style.display='block';
 5226:                 document.getElementById('showextent').style.textAlign='left';
 5227:                 document.getElementById('showextent').style.textFace='normal';
 5228:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5229:                     document.getElementById('showcolextent').disabled = '';
 5230:                     document.getElementById('showcolextent').checked = 'true';
 5231:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5232:                 } else {
 5233:                     document.getElementById('showcolextent').disabled = '';
 5234:                     document.getElementById('showcolextent').checked = 'true';
 5235:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5236:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5237:                     } else {
 5238:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5239:                     }
 5240:                 }
 5241:             }
 5242:             if (quotausageshow == 0)  {
 5243:                 if (document.getElementById('showcolauthorusage')) {
 5244:                     document.getElementById('showcolauthorusage').checked = false;
 5245:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5246:                 }
 5247:                 if (document.getElementById('showcolauthorquota')) {
 5248:                     document.getElementById('showcolauthorquota').checked = false;
 5249:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5250:                 }
 5251:             }
 5252:         }
 5253:     }
 5254:     return;
 5255: }
 5256: 
 5257: END
 5258:     return $output;
 5259: 
 5260: }
 5261: 
 5262: ###############################################################
 5263: ###############################################################
 5264: #  Menu Phase One
 5265: sub print_main_menu {
 5266:     my ($permission,$context,$crstype) = @_;
 5267:     my $linkcontext = $context;
 5268:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5269:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5270:         $linkcontext = lc($crstype);
 5271:         $stuterm = 'Members';
 5272:     }
 5273:     my %links = (
 5274:                 domain => {
 5275:                             upload     => 'Upload a File of Users',
 5276:                             singleuser => 'Add/Modify a User',
 5277:                             listusers  => 'Manage Users',
 5278:                             },
 5279:                 author => {
 5280:                             upload     => 'Upload a File of Co-authors',
 5281:                             singleuser => 'Add/Modify a Co-author',
 5282:                             listusers  => 'Manage Co-authors',
 5283:                             },
 5284:                 course => {
 5285:                             upload     => 'Upload a File of Course Users',
 5286:                             singleuser => 'Add/Modify a Course User',
 5287:                             listusers  => 'List and Modify Multiple Course Users',
 5288:                             },
 5289:                 community => {
 5290:                             upload     => 'Upload a File of Community Users',
 5291:                             singleuser => 'Add/Modify a Community User',
 5292:                             listusers  => 'List and Modify Multiple Community Users',
 5293:                            },
 5294:                 );
 5295:      my %linktitles = (
 5296:                 domain => {
 5297:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5298:                             listusers  => 'Show and manage users in this domain.',
 5299:                             },
 5300:                 author => {
 5301:                             singleuser => 'Add a user with a co- or assistant author role.',
 5302:                             listusers  => 'Show and manage co- or assistant authors.',
 5303:                             },
 5304:                 course => {
 5305:                             singleuser => 'Add a user with a certain role to this course.',
 5306:                             listusers  => 'Show and manage users in this course.',
 5307:                             },
 5308:                 community => {
 5309:                             singleuser => 'Add a user with a certain role to this community.',
 5310:                             listusers  => 'Show and manage users in this community.',
 5311:                            },
 5312:                 );
 5313:   if ($linkcontext eq 'domain') {
 5314:       unless ($permission->{'cusr'}) {
 5315:           $links{'domain'}{'singleuser'} = 'View a User';
 5316:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5317:       }
 5318:   } elsif ($linkcontext eq 'course') {
 5319:       unless ($permission->{'cusr'}) {
 5320:           $links{'course'}{'singleuser'} = 'View a Course User';
 5321:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5322:           $links{'course'}{'listusers'} = 'List Course Users';
 5323:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5324:       }
 5325:   } elsif ($linkcontext eq 'community') {
 5326:       unless ($permission->{'cusr'}) {
 5327:           $links{'community'}{'singleuser'} = 'View a Community User';
 5328:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5329:           $links{'community'}{'listusers'} = 'List Community Users';
 5330:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5331:       }
 5332:   }
 5333:   my @menu = ( {categorytitle => 'Single Users', 
 5334:          items =>
 5335:          [
 5336:             {
 5337:              linktext => $links{$linkcontext}{'singleuser'},
 5338:              icon => 'edit-redo.png',
 5339:              #help => 'Course_Change_Privileges',
 5340:              url => '/adm/createuser?action=singleuser',
 5341:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5342:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5343:             },
 5344:          ]},
 5345: 
 5346:          {categorytitle => 'Multiple Users',
 5347:          items => 
 5348:          [
 5349:             {
 5350:              linktext => $links{$linkcontext}{'upload'},
 5351:              icon => 'uplusr.png',
 5352:              #help => 'Course_Create_Class_List',
 5353:              url => '/adm/createuser?action=upload',
 5354:              permission => $permission->{'cusr'},
 5355:              linktitle => 'Upload a CSV or a text file containing users.',
 5356:             },
 5357:             {
 5358:              linktext => $links{$linkcontext}{'listusers'},
 5359:              icon => 'mngcu.png',
 5360:              #help => 'Course_View_Class_List',
 5361:              url => '/adm/createuser?action=listusers',
 5362:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5363:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5364:             },
 5365: 
 5366:          ]},
 5367: 
 5368:          {categorytitle => 'Administration',
 5369:          items => [ ]},
 5370:        );
 5371: 
 5372:     if ($context eq 'domain'){
 5373:         push(@{  $menu[0]->{items} }, # Single Users
 5374:             {
 5375:              linktext => 'User Access Log',
 5376:              icon => 'document-properties.png',
 5377:              #help => 'Domain_User_Access_Logs',
 5378:              url => '/adm/createuser?action=accesslogs',
 5379:              permission => $permission->{'activity'},
 5380:              linktitle => 'View user access log.',
 5381:             }
 5382:         );
 5383:         
 5384:         push(@{ $menu[2]->{items} }, #Category: Administration
 5385:             {
 5386:              linktext => 'Custom Roles',
 5387:              icon => 'emblem-photos.png',
 5388:              #help => 'Course_Editing_Custom_Roles',
 5389:              url => '/adm/createuser?action=custom',
 5390:              permission => $permission->{'custom'},
 5391:              linktitle => 'Configure a custom role.',
 5392:             },
 5393:             {
 5394:              linktext => 'Authoring Space Requests',
 5395:              icon => 'selfenrl-queue.png',
 5396:              #help => 'Domain_Role_Approvals',
 5397:              url => '/adm/createuser?action=processauthorreq',
 5398:              permission => $permission->{'cusr'},
 5399:              linktitle => 'Approve or reject author role requests',
 5400:             },
 5401:             {
 5402:              linktext => 'LON-CAPA Account Requests',
 5403:              icon => 'list-add.png',
 5404:              #help => 'Domain_Username_Approvals',
 5405:              url => '/adm/createuser?action=processusernamereq',
 5406:              permission => $permission->{'cusr'},
 5407:              linktitle => 'Approve or reject LON-CAPA account requests',
 5408:             },
 5409:             {
 5410:              linktext => 'Change Log',
 5411:              icon => 'document-properties.png',
 5412:              #help => 'Course_User_Logs',
 5413:              url => '/adm/createuser?action=changelogs',
 5414:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5415:              linktitle => 'View change log.',
 5416:             },
 5417:         );
 5418:         
 5419:     }elsif ($context eq 'course'){
 5420:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5421: 
 5422:         my %linktext = (
 5423:                          'Course'    => {
 5424:                                           single => 'Add/Modify a Student', 
 5425:                                           drop   => 'Drop Students',
 5426:                                           groups => 'Course Groups',
 5427:                                         },
 5428:                          'Community' => {
 5429:                                           single => 'Add/Modify a Member', 
 5430:                                           drop   => 'Drop Members',
 5431:                                           groups => 'Community Groups',
 5432:                                         },
 5433:                        );
 5434:         $linktext{'Placement'} = $linktext{'Course'};
 5435: 
 5436:         my %linktitle = (
 5437:             'Course' => {
 5438:                   single => 'Add a user with the role of student to this course',
 5439:                   drop   => 'Remove a student from this course.',
 5440:                   groups => 'Manage course groups',
 5441:                         },
 5442:             'Community' => {
 5443:                   single => 'Add a user with the role of member to this community',
 5444:                   drop   => 'Remove a member from this community.',
 5445:                   groups => 'Manage community groups',
 5446:                            },
 5447:         );
 5448: 
 5449:         $linktitle{'Placement'} = $linktitle{'Course'};
 5450: 
 5451:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5452:             {   
 5453:              linktext => $linktext{$crstype}{'single'},
 5454:              #help => 'Course_Add_Student',
 5455:              icon => 'list-add.png',
 5456:              url => '/adm/createuser?action=singlestudent',
 5457:              permission => $permission->{'cusr'},
 5458:              linktitle => $linktitle{$crstype}{'single'},
 5459:             },
 5460:         );
 5461:         
 5462:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5463:             {
 5464:              linktext => $linktext{$crstype}{'drop'},
 5465:              icon => 'edit-undo.png',
 5466:              #help => 'Course_Drop_Student',
 5467:              url => '/adm/createuser?action=drop',
 5468:              permission => $permission->{'cusr'},
 5469:              linktitle => $linktitle{$crstype}{'drop'},
 5470:             },
 5471:         );
 5472:         push(@{ $menu[2]->{items} }, #Category: Administration
 5473:             {
 5474:              linktext => 'Helpdesk Access',
 5475:              icon => 'helpdesk-access.png',
 5476:              #help => 'Course_Helpdesk_Access',
 5477:              url => '/adm/createuser?action=helpdesk',
 5478:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5479:              linktitle => 'Helpdesk access options',
 5480:             },
 5481:             {
 5482:              linktext => 'Custom Roles',
 5483:              icon => 'emblem-photos.png',
 5484:              #help => 'Course_Editing_Custom_Roles',
 5485:              url => '/adm/createuser?action=custom',
 5486:              permission => $permission->{'custom'},
 5487:              linktitle => 'Configure a custom role.',
 5488:             },
 5489:             {
 5490:              linktext => $linktext{$crstype}{'groups'},
 5491:              icon => 'grps.png',
 5492:              #help => 'Course_Manage_Group',
 5493:              url => '/adm/coursegroups?refpage=cusr',
 5494:              permission => $permission->{'grp_manage'},
 5495:              linktitle => $linktitle{$crstype}{'groups'},
 5496:             },
 5497:             {
 5498:              linktext => 'Change Log',
 5499:              icon => 'document-properties.png',
 5500:              #help => 'Course_User_Logs',
 5501:              url => '/adm/createuser?action=changelogs',
 5502:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5503:              linktitle => 'View change log.',
 5504:             },
 5505:         );
 5506:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5507:             push(@{ $menu[2]->{items} },
 5508:                     {
 5509:                      linktext => 'Enrollment Requests',
 5510:                      icon => 'selfenrl-queue.png',
 5511:                      #help => 'Course_Approve_Selfenroll',
 5512:                      url => '/adm/createuser?action=selfenrollqueue',
 5513:                      permission => $permission->{'selfenrolladmin'},
 5514:                      linktitle =>'Approve or reject enrollment requests.',
 5515:                     },
 5516:             );
 5517:         }
 5518:         
 5519:         if (!exists($permission->{'cusr_section'})){
 5520:             if ($crstype ne 'Community') {
 5521:                 push(@{ $menu[2]->{items} },
 5522:                     {
 5523:                      linktext => 'Automated Enrollment',
 5524:                      icon => 'roles.png',
 5525:                      #help => 'Course_Automated_Enrollment',
 5526:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5527:                                          && (($permission->{'cusr'}) ||
 5528:                                              ($permission->{'view'}))),
 5529:                      url  => '/adm/populate',
 5530:                      linktitle => 'Automated enrollment manager.',
 5531:                     }
 5532:                 );
 5533:             }
 5534:             push(@{ $menu[2]->{items} }, 
 5535:                 {
 5536:                  linktext => 'User Self-Enrollment',
 5537:                  icon => 'self_enroll.png',
 5538:                  #help => 'Course_Self_Enrollment',
 5539:                  url => '/adm/createuser?action=selfenroll',
 5540:                  permission => $permission->{'selfenrolladmin'},
 5541:                  linktitle => 'Configure user self-enrollment.',
 5542:                 },
 5543:             );
 5544:         }
 5545:     } elsif ($context eq 'author') {
 5546:         push(@{ $menu[2]->{items} }, #Category: Administration
 5547:             {
 5548:              linktext => 'Change Log',
 5549:              icon => 'document-properties.png',
 5550:              #help => 'Course_User_Logs',
 5551:              url => '/adm/createuser?action=changelogs',
 5552:              permission => $permission->{'cusr'},
 5553:              linktitle => 'View change log.',
 5554:             },
 5555:         );
 5556:     }
 5557:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5558: #               { text => 'View Log-in History',
 5559: #                 help => 'Course_User_Logins',
 5560: #                 action => 'logins',
 5561: #                 permission => $permission->{'cusr'},
 5562: #               });
 5563: }
 5564: 
 5565: sub restore_prev_selections {
 5566:     my %saveable_parameters = ('srchby'   => 'scalar',
 5567: 			       'srchin'   => 'scalar',
 5568: 			       'srchtype' => 'scalar',
 5569: 			       );
 5570:     &Apache::loncommon::store_settings('user','user_picker',
 5571: 				       \%saveable_parameters);
 5572:     &Apache::loncommon::restore_settings('user','user_picker',
 5573: 					 \%saveable_parameters);
 5574: }
 5575: 
 5576: sub print_selfenroll_menu {
 5577:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5578:     my $crstype = &Apache::loncommon::course_type();
 5579:     my $formname = 'selfenroll';
 5580:     my $nolink = 1;
 5581:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5582:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5583:     my $setsec_js = 
 5584:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5585:     my %alerts = &Apache::lonlocal::texthash(
 5586:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5587:         butn => 'but no user types have been checked.',
 5588:         wilf => "Please uncheck 'activate' or check at least one type.",
 5589:     );
 5590:     my $disabled;
 5591:     if ($readonly) {
 5592:        $disabled = ' disabled="disabled"';
 5593:     }
 5594:     &js_escape(\%alerts);
 5595:     my $selfenroll_js = <<"ENDSCRIPT";
 5596: function update_types(caller,num) {
 5597:     var delidx = getIndexByName('selfenroll_delete');
 5598:     var actidx = getIndexByName('selfenroll_activate');
 5599:     if (caller == 'selfenroll_all') {
 5600:         var selall;
 5601:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5602:             if (document.$formname.selfenroll_all[i].checked) {
 5603:                 selall = document.$formname.selfenroll_all[i].value;
 5604:             }
 5605:         }
 5606:         if (selall == 1) {
 5607:             if (delidx != -1) {
 5608:                 if (document.$formname.selfenroll_delete.length) {
 5609:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5610:                         document.$formname.selfenroll_delete[j].checked = true;
 5611:                     }
 5612:                 } else {
 5613:                     document.$formname.elements[delidx].checked = true;
 5614:                 }
 5615:             }
 5616:             if (actidx != -1) {
 5617:                 if (document.$formname.selfenroll_activate.length) {
 5618:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5619:                         document.$formname.selfenroll_activate[j].checked = false;
 5620:                     }
 5621:                 } else {
 5622:                     document.$formname.elements[actidx].checked = false;
 5623:                 }
 5624:             }
 5625:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5626:         }
 5627:     }
 5628:     if (caller == 'selfenroll_activate') {
 5629:         if (document.$formname.selfenroll_activate.length) {
 5630:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5631:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5632:                     if (document.$formname.selfenroll_activate[j].checked) {
 5633:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5634:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5635:                                 document.$formname.selfenroll_all[i].checked = false;
 5636:                             }
 5637:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5638:                                 document.$formname.selfenroll_all[i].checked = true;
 5639:                             }
 5640:                         }
 5641:                     }
 5642:                 }
 5643:             }
 5644:         } else {
 5645:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5646:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5647:                     document.$formname.selfenroll_all[i].checked = false;
 5648:                 }
 5649:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5650:                     document.$formname.selfenroll_all[i].checked = true;
 5651:                 }
 5652:             }
 5653:         }
 5654:     }
 5655:     if (caller == 'selfenroll_delete') {
 5656:         if (document.$formname.selfenroll_delete.length) {
 5657:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5658:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5659:                     if (document.$formname.selfenroll_delete[j].checked) {
 5660:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5661:                         if (delindex != -1) { 
 5662:                             if (document.$formname.elements[delindex].length) {
 5663:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5664:                                     document.$formname.elements[delindex][k].checked = false;
 5665:                                 }
 5666:                             } else {
 5667:                                 document.$formname.elements[delindex].checked = false;
 5668:                             }
 5669:                         }
 5670:                     }
 5671:                 }
 5672:             }
 5673:         } else {
 5674:             if (document.$formname.selfenroll_delete.checked) {
 5675:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5676:                 if (delindex != -1) {
 5677:                     if (document.$formname.elements[delindex].length) {
 5678:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5679:                             document.$formname.elements[delindex][k].checked = false;
 5680:                         }
 5681:                     } else {
 5682:                         document.$formname.elements[delindex].checked = false;
 5683:                     }
 5684:                 }
 5685:             }
 5686:         }
 5687:     }
 5688:     return;
 5689: }
 5690: 
 5691: function validate_types(form) {
 5692:     var needaction = new Array();
 5693:     var countfail = 0;
 5694:     var actidx = getIndexByName('selfenroll_activate');
 5695:     if (actidx != -1) {
 5696:         if (document.$formname.selfenroll_activate.length) {
 5697:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5698:                 var num = document.$formname.selfenroll_activate[j].value;
 5699:                 if (document.$formname.selfenroll_activate[j].checked) {
 5700:                     countfail = check_types(num,countfail,needaction)
 5701:                 }
 5702:             }
 5703:         } else {
 5704:             if (document.$formname.selfenroll_activate.checked) {
 5705:                 var num = document.$formname.selfenroll_activate.value;
 5706:                 countfail = check_types(num,countfail,needaction)
 5707:             }
 5708:         }
 5709:     }
 5710:     if (countfail > 0) {
 5711:         var msg = "$alerts{'acto'}\\n";
 5712:         var loopend = needaction.length -1;
 5713:         if (loopend > 0) {
 5714:             for (var m=0; m<loopend; m++) {
 5715:                 msg += needaction[m]+", ";
 5716:             }
 5717:         }
 5718:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5719:         alert(msg);
 5720:         return; 
 5721:     }
 5722:     setSections(form);
 5723: }
 5724: 
 5725: function check_types(num,countfail,needaction) {
 5726:     var typeidx = getIndexByName('selfenroll_types_'+num);
 5727:     var count = 0;
 5728:     if (typeidx != -1) {
 5729:         if (document.$formname.elements[typeidx].length) {
 5730:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
 5731:                 if (document.$formname.elements[typeidx][k].checked) {
 5732:                     count ++;
 5733:                 }
 5734:             }
 5735:         } else {
 5736:             if (document.$formname.elements[typeidx].checked) {
 5737:                 count ++;
 5738:             }
 5739:         }
 5740:         if (count == 0) {
 5741:             var domidx = getIndexByName('selfenroll_dom_'+num);
 5742:             if (domidx != -1) {
 5743:                 var domname = document.$formname.elements[domidx].value;
 5744:                 needaction[countfail] = domname;
 5745:                 countfail ++;
 5746:             }
 5747:         }
 5748:     }
 5749:     return countfail;
 5750: }
 5751: 
 5752: function toggleNotify() {
 5753:     var selfenrollApproval = 0;
 5754:     if (document.$formname.selfenroll_approval.length) {
 5755:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 5756:             if (document.$formname.selfenroll_approval[i].checked) {
 5757:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 5758:                 break;        
 5759:             }
 5760:         }
 5761:     }
 5762:     if (document.getElementById('notified')) {
 5763:         if (selfenrollApproval == 0) {
 5764:             document.getElementById('notified').style.display='none';
 5765:         } else {
 5766:             document.getElementById('notified').style.display='block';
 5767:         }
 5768:     }
 5769:     return;
 5770: }
 5771: 
 5772: function getIndexByName(item) {
 5773:     for (var i=0;i<document.$formname.elements.length;i++) {
 5774:         if (document.$formname.elements[i].name == item) {
 5775:             return i;
 5776:         }
 5777:     }
 5778:     return -1;
 5779: }
 5780: ENDSCRIPT
 5781: 
 5782:     my $output = '<script type="text/javascript">'."\n".
 5783:                  '// <![CDATA['."\n".
 5784:                  $setsec_js."\n".$selfenroll_js."\n".
 5785:                  '// ]]>'."\n".
 5786:                  '</script>'."\n".
 5787:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 5788:  
 5789:     my $visactions = &cat_visibility();
 5790:     my ($cathash,%cattype);
 5791:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 5792:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 5793:         $cathash = $domconfig{'coursecategories'}{'cats'};
 5794:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 5795:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 5796:         if ($cattype{'auth'} eq '') {
 5797:             $cattype{'auth'} = 'std';
 5798:         }
 5799:         if ($cattype{'unauth'} eq '') {
 5800:             $cattype{'unauth'} = 'std';
 5801:         }
 5802:     } else {
 5803:         $cathash = {};
 5804:         $cattype{'auth'} = 'std';
 5805:         $cattype{'unauth'} = 'std';
 5806:     }
 5807:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 5808:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5809:                   '<br />'.
 5810:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5811:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 5812:                   '</ul>');
 5813:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 5814:         if ($currsettings->{'uniquecode'}) {
 5815:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 5816:         } else {
 5817:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 5818:                   '<br />'.
 5819:                   '<br />'.$visactions->{'take'}.'<ul>'.
 5820:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 5821:                   '</ul><br />');
 5822:         }
 5823:     } else {
 5824:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 5825:         if (ref($visactions) eq 'HASH') {
 5826:             if ($visible) {
 5827:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 5828:            } else {
 5829:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 5830:                           .$visactions->{'yous'}.
 5831:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 5832:                 if (ref($vismsgs) eq 'ARRAY') {
 5833:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 5834:                     foreach my $item (@{$vismsgs}) {
 5835:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 5836:                     }
 5837:                     $output .= '</ul>';
 5838:                 }
 5839:                 $output .= '</p>';
 5840:             }
 5841:         }
 5842:     }
 5843:     my $actionhref = '/adm/createuser';
 5844:     if ($context eq 'domain') {
 5845:         $actionhref = '/adm/modifycourse';
 5846:     }
 5847: 
 5848:     my %noedit;
 5849:     unless ($context eq 'domain') {
 5850:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 5851:     }
 5852:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 5853:                &Apache::lonhtmlcommon::start_pick_box();
 5854:     if (ref($row) eq 'ARRAY') {
 5855:         foreach my $item (@{$row}) {
 5856:             my $title = $item; 
 5857:             if (ref($lt) eq 'HASH') {
 5858:                 $title = $lt->{$item};
 5859:             }
 5860:             $output .= &Apache::lonhtmlcommon::row_title($title);
 5861:             if ($item eq 'types') {
 5862:                 my $curr_types;
 5863:                 if (ref($currsettings) eq 'HASH') {
 5864:                     $curr_types = $currsettings->{'selfenroll_types'};
 5865:                 }
 5866:                 if ($noedit{$item}) {
 5867:                     if ($curr_types eq '*') {
 5868:                         $output .= &mt('Any user in any domain');   
 5869:                     } else {
 5870:                         my @entries = split(/;/,$curr_types);
 5871:                         if (@entries > 0) {
 5872:                             $output .= '<ul>'; 
 5873:                             foreach my $entry (@entries) {
 5874:                                 my ($currdom,$typestr) = split(/:/,$entry);
 5875:                                 next if ($typestr eq '');
 5876:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 5877:                                 my @currinsttypes = split(',',$typestr);
 5878:                                 my ($othertitle,$usertypes,$types) = 
 5879:                                     &Apache::loncommon::sorted_inst_types($currdom);
 5880:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5881:                                     $usertypes->{'any'} = &mt('any user'); 
 5882:                                     if (keys(%{$usertypes}) > 0) {
 5883:                                         $usertypes->{'other'} = &mt('other users');
 5884:                                     }
 5885:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 5886:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 5887:                                  }
 5888:                             }
 5889:                             $output .= '</ul>';
 5890:                         } else {
 5891:                             $output .= &mt('None');
 5892:                         }
 5893:                     }
 5894:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5895:                     next;
 5896:                 }
 5897:                 my $showdomdesc = 1;
 5898:                 my $includeempty = 1;
 5899:                 my $num = 0;
 5900:                 $output .= &Apache::loncommon::start_data_table().
 5901:                            &Apache::loncommon::start_data_table_row()
 5902:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 5903:                            .&mt('Any user in any domain:')
 5904:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 5905:                 if ($curr_types eq '*') {
 5906:                     $output .= ' checked="checked" '; 
 5907:                 }
 5908:                 $output .= 'onchange="javascript:update_types('.
 5909:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 5910:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 5911:                 if ($curr_types ne '*') {
 5912:                     $output .= ' checked="checked" ';
 5913:                 }
 5914:                 $output .= ' onchange="javascript:update_types('.
 5915:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 5916:                            &Apache::loncommon::end_data_table_row().
 5917:                            &Apache::loncommon::end_data_table().
 5918:                            &mt('Or').'<br />'.
 5919:                            &Apache::loncommon::start_data_table();
 5920:                 my %currdoms;
 5921:                 if ($curr_types eq '') {
 5922:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 5923:                 } elsif ($curr_types ne '*') {
 5924:                     my @entries = split(/;/,$curr_types);
 5925:                     if (@entries > 0) {
 5926:                         foreach my $entry (@entries) {
 5927:                             my ($currdom,$typestr) = split(/:/,$entry);
 5928:                             $currdoms{$currdom} = 1;
 5929:                             my $domdesc = &Apache::lonnet::domain($currdom);
 5930:                             my @currinsttypes = split(',',$typestr);
 5931:                             $output .= &Apache::loncommon::start_data_table_row()
 5932:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 5933:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 5934:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 5935:                                        .'" value="'.$currdom.'" /></span><br />'
 5936:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 5937:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 5938:                                        .&mt('Delete').'</label></span></td>';
 5939:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 5940:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 5941:                                        .&Apache::loncommon::end_data_table_row();
 5942:                             $num ++;
 5943:                         }
 5944:                     }
 5945:                 }
 5946:                 my $add_domtitle = &mt('Users in additional domain:');
 5947:                 if ($curr_types eq '*') { 
 5948:                     $add_domtitle = &mt('Users in specific domain:');
 5949:                 } elsif ($curr_types eq '') {
 5950:                     $add_domtitle = &mt('Users in other domain:');
 5951:                 }
 5952:                 $output .= &Apache::loncommon::start_data_table_row()
 5953:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 5954:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 5955:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 5956:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 5957:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 5958:                            .&Apache::loncommon::end_data_table();
 5959:             } elsif ($item eq 'registered') {
 5960:                 my ($regon,$regoff);
 5961:                 my $registered;
 5962:                 if (ref($currsettings) eq 'HASH') {
 5963:                     $registered = $currsettings->{'selfenroll_registered'};
 5964:                 }
 5965:                 if ($noedit{$item}) {
 5966:                     if ($registered) {
 5967:                         $output .= &mt('Must be registered in course');
 5968:                     } else {
 5969:                         $output .= &mt('No requirement');
 5970:                     }
 5971:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 5972:                     next;
 5973:                 }
 5974:                 if ($registered) {
 5975:                     $regon = ' checked="checked" ';
 5976:                     $regoff = '';
 5977:                 } else {
 5978:                     $regon = '';
 5979:                     $regoff = ' checked="checked" ';
 5980:                 }
 5981:                 $output .= '<label>'.
 5982:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 5983:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 5984:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 5985:                            &mt('No').'</label>';
 5986:             } elsif ($item eq 'enroll_dates') {
 5987:                 my ($starttime,$endtime);
 5988:                 if (ref($currsettings) eq 'HASH') {
 5989:                     $starttime = $currsettings->{'selfenroll_start_date'};
 5990:                     $endtime = $currsettings->{'selfenroll_end_date'};
 5991:                     if ($starttime eq '') {
 5992:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 5993:                     }
 5994:                     if ($endtime eq '') {
 5995:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 5996:                     }
 5997:                 }
 5998:                 if ($noedit{$item}) {
 5999:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6000:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6001:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6002:                     next;
 6003:                 }
 6004:                 my $startform =
 6005:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6006:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6007:                 my $endform =
 6008:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6009:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6010:                 $output .= &selfenroll_date_forms($startform,$endform);
 6011:             } elsif ($item eq 'access_dates') {
 6012:                 my ($starttime,$endtime);
 6013:                 if (ref($currsettings) eq 'HASH') {
 6014:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6015:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6016:                     if ($starttime eq '') {
 6017:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6018:                     }
 6019:                     if ($endtime eq '') {
 6020:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6021:                     }
 6022:                 }
 6023:                 if ($noedit{$item}) {
 6024:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6025:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6026:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6027:                     next;
 6028:                 }
 6029:                 my $startform =
 6030:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6031:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6032:                 my $endform =
 6033:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6034:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6035:                 $output .= &selfenroll_date_forms($startform,$endform);
 6036:             } elsif ($item eq 'section') {
 6037:                 my $currsec;
 6038:                 if (ref($currsettings) eq 'HASH') {
 6039:                     $currsec = $currsettings->{'selfenroll_section'};
 6040:                 }
 6041:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6042:                 my $newsecval;
 6043:                 if ($currsec ne 'none' && $currsec ne '') {
 6044:                     if (!defined($sections_count{$currsec})) {
 6045:                         $newsecval = $currsec;
 6046:                     }
 6047:                 }
 6048:                 if ($noedit{$item}) {
 6049:                     if ($currsec ne '') {
 6050:                         $output .= $currsec;
 6051:                     } else {
 6052:                         $output .= &mt('No specific section');
 6053:                     }
 6054:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6055:                     next;
 6056:                 }
 6057:                 my $sections_select = 
 6058:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6059:                 $output .= '<table class="LC_createuser">'."\n".
 6060:                            '<tr class="LC_section_row">'."\n".
 6061:                            '<td align="center">'.&mt('Existing sections')."\n".
 6062:                            '<br />'.$sections_select.'</td><td align="center">'.
 6063:                            &mt('New section').'<br />'."\n".
 6064:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6065:                            '<input type="hidden" name="sections" value="" />'."\n".
 6066:                            '</td></tr></table>'."\n";
 6067:             } elsif ($item eq 'approval') {
 6068:                 my ($currnotified,$currapproval,%appchecked);
 6069:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6070:                 if (ref($currsettings) eq 'HASH') {
 6071:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6072:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6073:                 }
 6074:                 if ($currapproval !~ /^[012]$/) {
 6075:                     $currapproval = 0;
 6076:                 }
 6077:                 if ($noedit{$item}) {
 6078:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6079:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6080:                     next;
 6081:                 }
 6082:                 $appchecked{$currapproval} = ' checked="checked"';
 6083:                 for my $i (0..2) {
 6084:                     $output .= '<label>'.
 6085:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6086:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6087:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6088:                 }
 6089:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6090:                 my (@ccs,%notified);
 6091:                 my $ccrole = 'cc';
 6092:                 if ($crstype eq 'Community') {
 6093:                     $ccrole = 'co';
 6094:                 }
 6095:                 if ($advhash{$ccrole}) {
 6096:                     @ccs = split(/,/,$advhash{$ccrole});
 6097:                 }
 6098:                 if ($currnotified) {
 6099:                     foreach my $current (split(/,/,$currnotified)) {
 6100:                         $notified{$current} = 1;
 6101:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6102:                             push(@ccs,$current);
 6103:                         }
 6104:                     }
 6105:                 }
 6106:                 if (@ccs) {
 6107:                     my $style;
 6108:                     unless ($currapproval) {
 6109:                         $style = ' style="display: none;"'; 
 6110:                     }
 6111:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6112:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6113:                                &Apache::loncommon::start_data_table().
 6114:                                &Apache::loncommon::start_data_table_row();
 6115:                     my $count = 0;
 6116:                     my $numcols = 4;
 6117:                     foreach my $cc (sort(@ccs)) {
 6118:                         my $notifyon;
 6119:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6120:                         if ($notified{$cc}) {
 6121:                             $notifyon = ' checked="checked" ';
 6122:                         }
 6123:                         if ($count && !$count%$numcols) {
 6124:                             $output .= &Apache::loncommon::end_data_table_row().
 6125:                                        &Apache::loncommon::start_data_table_row()
 6126:                         }
 6127:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6128:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6129:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6130:                                    '</label></span></td>';
 6131:                         $count ++;
 6132:                     }
 6133:                     my $rem = $count%$numcols;
 6134:                     if ($rem) {
 6135:                         my $emptycols = $numcols - $rem;
 6136:                         for (my $i=0; $i<$emptycols; $i++) { 
 6137:                             $output .= '<td>&nbsp;</td>';
 6138:                         }
 6139:                     }
 6140:                     $output .= &Apache::loncommon::end_data_table_row().
 6141:                                &Apache::loncommon::end_data_table().
 6142:                                '</div>';
 6143:                 }
 6144:             } elsif ($item eq 'limit') {
 6145:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6146:                 if (ref($currsettings) eq 'HASH') {
 6147:                     $currlim = $currsettings->{'selfenroll_limit'};
 6148:                     $currcap = $currsettings->{'selfenroll_cap'};
 6149:                 }
 6150:                 if ($noedit{$item}) {
 6151:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6152:                         if ($currlim eq 'allstudents') {
 6153:                             $output .= &mt('Limit by total students');
 6154:                         } elsif ($currlim eq 'selfenrolled') {
 6155:                             $output .= &mt('Limit by total self-enrolled students');
 6156:                         }
 6157:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6158:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6159:                     } else {
 6160:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6161:                     }
 6162:                     next;
 6163:                 }
 6164:                 if ($currlim eq 'allstudents') {
 6165:                     $crslimit = ' checked="checked" ';
 6166:                     $selflimit = ' ';
 6167:                     $nolimit = ' ';
 6168:                 } elsif ($currlim eq 'selfenrolled') {
 6169:                     $crslimit = ' ';
 6170:                     $selflimit = ' checked="checked" ';
 6171:                     $nolimit = ' '; 
 6172:                 } else {
 6173:                     $crslimit = ' ';
 6174:                     $selflimit = ' ';
 6175:                     $nolimit = ' checked="checked" ';
 6176:                 }
 6177:                 $output .= '<table><tr><td><label>'.
 6178:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6179:                            &mt('No limit').'</label></td><td><label>'.
 6180:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6181:                            &mt('Limit by total students').'</label></td><td><label>'.
 6182:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6183:                            &mt('Limit by total self-enrolled students').
 6184:                            '</td></tr><tr>'.
 6185:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6186:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6187:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6188:             }
 6189:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6190:         }
 6191:     }
 6192:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6193:     unless ($readonly) {
 6194:         $output .= '<input type="button" name="selfenrollconf" value="'
 6195:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6196:     }
 6197:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6198:               .'<input type="hidden" name="state" value="done" />'."\n"
 6199:               .$additional.'</form>';
 6200:     $r->print($output);
 6201:     return;
 6202: }
 6203: 
 6204: sub get_noedit_fields {
 6205:     my ($cdom,$cnum,$crstype,$row) = @_;
 6206:     my %noedit;
 6207:     if (ref($row) eq 'ARRAY') {
 6208:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6209:                                                            'internal.selfenrollmgrdc',
 6210:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6211:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6212:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6213:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6214:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6215:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6216:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6217: 
 6218:         foreach my $item (@{$row}) {
 6219:             next if ($specific_managebycc{$item});
 6220:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6221:                 $noedit{$item} = 1;
 6222:             }
 6223:         }
 6224:     }
 6225:     return %noedit;
 6226: } 
 6227: 
 6228: sub visible_in_stdcat {
 6229:     my ($cdom,$cnum,$domconf) = @_;
 6230:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6231:     unless (ref($domconf) eq 'HASH') {
 6232:         return ($visible,$cansetvis,\@vismsgs);
 6233:     }
 6234:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6235:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6236:             $settable{'togglecats'} = 1;
 6237:         }
 6238:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6239:             $settable{'categorize'} = 1;
 6240:         }
 6241:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6242:     }
 6243:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6244:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6245:     } elsif ($settable{'togglecats'}) {
 6246:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6247:     } elsif ($settable{'categorize'}) {
 6248:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6249:     } else {
 6250:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6251:     }
 6252:      
 6253:     my %currsettings =
 6254:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6255:                              $cdom,$cnum);
 6256:     $visible = 0;
 6257:     if ($currsettings{'internal.coursecode'} ne '') {
 6258:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6259:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6260:             if (ref($cathash) eq 'HASH') {
 6261:                 if ($cathash->{'instcode::0'} eq '') {
 6262:                     push(@vismsgs,'dc_addinst'); 
 6263:                 } else {
 6264:                     $visible = 1;
 6265:                 }
 6266:             } else {
 6267:                 $visible = 1;
 6268:             }
 6269:         } else {
 6270:             $visible = 1;
 6271:         }
 6272:     } else {
 6273:         if (ref($cathash) eq 'HASH') {
 6274:             if ($cathash->{'instcode::0'} ne '') {
 6275:                 push(@vismsgs,'dc_instcode');
 6276:             }
 6277:         } else {
 6278:             push(@vismsgs,'dc_instcode');
 6279:         }
 6280:     }
 6281:     if ($currsettings{'categories'} ne '') {
 6282:         my $cathash;
 6283:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6284:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6285:             if (ref($cathash) eq 'HASH') {
 6286:                 if (keys(%{$cathash}) == 0) {
 6287:                     push(@vismsgs,'dc_catalog');
 6288:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6289:                     push(@vismsgs,'dc_categories');
 6290:                 } else {
 6291:                     my @currcategories = split('&',$currsettings{'categories'});
 6292:                     my $matched = 0;
 6293:                     foreach my $cat (@currcategories) {
 6294:                         if ($cathash->{$cat} ne '') {
 6295:                             $visible = 1;
 6296:                             $matched = 1;
 6297:                             last;
 6298:                         }
 6299:                     }
 6300:                     if (!$matched) {
 6301:                         if ($settable{'categorize'}) { 
 6302:                             push(@vismsgs,'chgcat');
 6303:                         } else {
 6304:                             push(@vismsgs,'dc_chgcat');
 6305:                         }
 6306:                     }
 6307:                 }
 6308:             }
 6309:         }
 6310:     } else {
 6311:         if (ref($cathash) eq 'HASH') {
 6312:             if ((keys(%{$cathash}) > 1) || 
 6313:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6314:                 if ($settable{'categorize'}) {
 6315:                     push(@vismsgs,'addcat');
 6316:                 } else {
 6317:                     push(@vismsgs,'dc_addcat');
 6318:                 }
 6319:             }
 6320:         }
 6321:     }
 6322:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6323:         $visible = 0;
 6324:         if ($settable{'togglecats'}) {
 6325:             unshift(@vismsgs,'unhide');
 6326:         } else {
 6327:             unshift(@vismsgs,'dc_unhide')
 6328:         }
 6329:     }
 6330:     return ($visible,$cansetvis,\@vismsgs);
 6331: }
 6332: 
 6333: sub cat_visibility {
 6334:     my %visactions = &Apache::lonlocal::texthash(
 6335:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6336:                    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.',
 6337:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6338:                    none => 'Display of a course catalog is disabled for this domain.',
 6339:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6340:                    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.',
 6341:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6342:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6343:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6344:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6345:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6346:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6347:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6348:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6349:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6350:                    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',
 6351:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6352:     );
 6353:     $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>"');
 6354:     $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>"');
 6355:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6356:     return \%visactions;
 6357: }
 6358: 
 6359: sub new_selfenroll_dom_row {
 6360:     my ($newdom,$num) = @_;
 6361:     my $domdesc = &Apache::lonnet::domain($newdom);
 6362:     my $output;
 6363:     if ($domdesc ne '') {
 6364:         $output .= &Apache::loncommon::start_data_table_row()
 6365:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6366:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6367:                    .'" value="'.$newdom.'" /></span><br />'
 6368:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6369:                    .'name="selfenroll_activate" value="'.$num.'" '
 6370:                    .'onchange="javascript:update_types('
 6371:                    ."'selfenroll_activate','$num'".');" />'
 6372:                    .&mt('Activate').'</label></span></td>';
 6373:         my @currinsttypes;
 6374:         $output .= '<td>'.&mt('User types:').'<br />'
 6375:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6376:                    .&Apache::loncommon::end_data_table_row();
 6377:     }
 6378:     return $output;
 6379: }
 6380: 
 6381: sub selfenroll_inst_types {
 6382:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6383:     my $output;
 6384:     my $numinrow = 4;
 6385:     my $count = 0;
 6386:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6387:     my $othervalue = 'any';
 6388:     my $disabled;
 6389:     if ($readonly) {
 6390:         $disabled = ' disabled="disabled"';
 6391:     }
 6392:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6393:         if (keys(%{$usertypes}) > 0) {
 6394:             $othervalue = 'other';
 6395:         }
 6396:         $output .= '<table><tr>';
 6397:         foreach my $type (@{$types}) {
 6398:             if (($count > 0) && ($count%$numinrow == 0)) {
 6399:                 $output .= '</tr><tr>';
 6400:             }
 6401:             if (defined($usertypes->{$type})) {
 6402:                 my $esc_type = &escape($type);
 6403:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6404:                            $esc_type.'" ';
 6405:                 if (ref($currinsttypes) eq 'ARRAY') {
 6406:                     if (@{$currinsttypes} > 0) {
 6407:                         if (grep(/^any$/,@{$currinsttypes})) {
 6408:                             $output .= 'checked="checked"';
 6409:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6410:                             $output .= 'checked="checked"';
 6411:                         }
 6412:                     } else {
 6413:                         $output .= 'checked="checked"';
 6414:                     }
 6415:                 }
 6416:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6417:             }
 6418:             $count ++;
 6419:         }
 6420:         if (($count > 0) && ($count%$numinrow == 0)) {
 6421:             $output .= '</tr><tr>';
 6422:         }
 6423:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6424:         if (ref($currinsttypes) eq 'ARRAY') {
 6425:             if (@{$currinsttypes} > 0) {
 6426:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6427:                     $output .= ' checked="checked"';
 6428:                 } elsif ($othervalue eq 'other') {
 6429:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6430:                         $output .= ' checked="checked"';
 6431:                     }
 6432:                 }
 6433:             } else {
 6434:                 $output .= ' checked="checked"';
 6435:             }
 6436:         } else {
 6437:             $output .= ' checked="checked"';
 6438:         }
 6439:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6440:     }
 6441:     return $output;
 6442: }
 6443: 
 6444: sub selfenroll_date_forms {
 6445:     my ($startform,$endform) = @_;
 6446:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6447:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6448:                                                     'LC_oddrow_value')."\n".
 6449:                   $startform."\n".
 6450:                   &Apache::lonhtmlcommon::row_closure(1).
 6451:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6452:                                                    'LC_oddrow_value')."\n".
 6453:                   $endform."\n".
 6454:                   &Apache::lonhtmlcommon::row_closure(1).
 6455:                   &Apache::lonhtmlcommon::end_pick_box();
 6456:     return $output;
 6457: }
 6458: 
 6459: sub print_userchangelogs_display {
 6460:     my ($r,$context,$permission,$brcrum) = @_;
 6461:     my $formname = 'rolelog';
 6462:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6463:     if ($context eq 'domain') {
 6464:         $domain = $env{'request.role.domain'};
 6465:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6466:     } else {
 6467:         if ($context eq 'course') { 
 6468:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6469:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6470:             $crstype = &Apache::loncommon::course_type();
 6471:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6472:             my %saveable_parameters = ('show' => 'scalar',);
 6473:             &Apache::loncommon::store_course_settings('roles_log',
 6474:                                                       \%saveable_parameters);
 6475:             &Apache::loncommon::restore_course_settings('roles_log',
 6476:                                                         \%saveable_parameters);
 6477:         } elsif ($context eq 'author') {
 6478:             $domain = $env{'user.domain'}; 
 6479:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6480:                 $username = $env{'user.name'};
 6481:             } else {
 6482:                 undef($domain);
 6483:             }
 6484:         }
 6485:         if ($domain ne '' && $username ne '') { 
 6486:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6487:         }
 6488:     }
 6489:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6490: 
 6491:     my $helpitem;
 6492:     if ($context eq 'course') {
 6493:         $helpitem = 'Course_User_Logs';
 6494:     }
 6495:     push (@{$brcrum},
 6496:              {href => '/adm/createuser?action=changelogs',
 6497:               text => 'User Management Logs',
 6498:               help => $helpitem});
 6499:     my $bread_crumbs_component = 'User Changes';
 6500:     my $args = { bread_crumbs           => $brcrum,
 6501:                  bread_crumbs_component => $bread_crumbs_component};
 6502: 
 6503:     # Create navigation javascript
 6504:     my $jsnav = &userlogdisplay_js($formname);
 6505: 
 6506:     my $jscript = (<<ENDSCRIPT);
 6507: <script type="text/javascript">
 6508: // <![CDATA[
 6509: $jsnav
 6510: // ]]>
 6511: </script>
 6512: ENDSCRIPT
 6513: 
 6514:     # print page header
 6515:     $r->print(&header($jscript,$args));
 6516: 
 6517:     # set defaults
 6518:     my $now = time();
 6519:     my $defstart = $now - (7*24*3600); #7 days ago 
 6520:     my %defaults = (
 6521:                      page               => '1',
 6522:                      show               => '10',
 6523:                      role               => 'any',
 6524:                      chgcontext         => 'any',
 6525:                      rolelog_start_date => $defstart,
 6526:                      rolelog_end_date   => $now,
 6527:                    );
 6528:     my $more_records = 0;
 6529: 
 6530:     # set current
 6531:     my %curr;
 6532:     foreach my $item ('show','page','role','chgcontext') {
 6533:         $curr{$item} = $env{'form.'.$item};
 6534:     }
 6535:     my ($startdate,$enddate) = 
 6536:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6537:     $curr{'rolelog_start_date'} = $startdate;
 6538:     $curr{'rolelog_end_date'} = $enddate;
 6539:     foreach my $key (keys(%defaults)) {
 6540:         if ($curr{$key} eq '') {
 6541:             $curr{$key} = $defaults{$key};
 6542:         }
 6543:     }
 6544:     my (%whodunit,%changed,$version);
 6545:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6546:     my ($minshown,$maxshown);
 6547:     $minshown = 1;
 6548:     my $count = 0;
 6549:     if ($curr{'show'} =~ /\D/) {
 6550:         $curr{'page'} = 1;
 6551:     } else {
 6552:         $maxshown = $curr{'page'} * $curr{'show'};
 6553:         if ($curr{'page'} > 1) {
 6554:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6555:         }
 6556:     }
 6557: 
 6558:     # Form Header
 6559:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6560:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6561:                                    $version,$crstype));
 6562: 
 6563:     my $showntableheader = 0;
 6564: 
 6565:     # Table Header
 6566:     my $tableheader = 
 6567:         &Apache::loncommon::start_data_table_header_row()
 6568:        .'<th>&nbsp;</th>'
 6569:        .'<th>'.&mt('When').'</th>'
 6570:        .'<th>'.&mt('Who made the change').'</th>'
 6571:        .'<th>'.&mt('Changed User').'</th>'
 6572:        .'<th>'.&mt('Role').'</th>';
 6573: 
 6574:     if ($context eq 'course') {
 6575:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6576:     }
 6577:     $tableheader .=
 6578:         '<th>'.&mt('Context').'</th>'
 6579:        .'<th>'.&mt('Start').'</th>'
 6580:        .'<th>'.&mt('End').'</th>'
 6581:        .&Apache::loncommon::end_data_table_header_row();
 6582: 
 6583:     # Display user change log data
 6584:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6585:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6586:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6587:         if ($curr{'show'} !~ /\D/) {
 6588:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6589:                 $more_records = 1;
 6590:                 last;
 6591:             }
 6592:         }
 6593:         if ($curr{'role'} ne 'any') {
 6594:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6595:         }
 6596:         if ($curr{'chgcontext'} ne 'any') {
 6597:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6598:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6599:             } else {
 6600:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6601:             }
 6602:         }
 6603:         if (($context eq 'course') && ($viewablesec ne '')) {
 6604:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6605:         }
 6606:         $count ++;
 6607:         next if ($count < $minshown);
 6608:         unless ($showntableheader) {
 6609:             $r->print(&Apache::loncommon::start_data_table()
 6610:                      .$tableheader);
 6611:             $r->rflush();
 6612:             $showntableheader = 1;
 6613:         }
 6614:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6615:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6616:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6617:         }
 6618:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6619:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6620:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6621:         }
 6622:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6623:         if ($sec eq '') {
 6624:             $sec = &mt('None');
 6625:         }
 6626:         my ($rolestart,$roleend);
 6627:         if ($roleslog{$id}{'delflag'}) {
 6628:             $rolestart = &mt('deleted');
 6629:             $roleend = &mt('deleted');
 6630:         } else {
 6631:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6632:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6633:             if ($rolestart eq '' || $rolestart == 0) {
 6634:                 $rolestart = &mt('No start date'); 
 6635:             } else {
 6636:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6637:             }
 6638:             if ($roleend eq '' || $roleend == 0) { 
 6639:                 $roleend = &mt('No end date');
 6640:             } else {
 6641:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6642:             }
 6643:         }
 6644:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6645:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6646:             $chgcontext = 'selfenroll';
 6647:         }
 6648:         my %lt = &rolechg_contexts($context,$crstype);
 6649:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6650:             $chgcontext = $lt{$chgcontext};
 6651:         }
 6652:         $r->print(
 6653:             &Apache::loncommon::start_data_table_row()
 6654:            .'<td>'.$count.'</td>'
 6655:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6656:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6657:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6658:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6659:         if ($context eq 'course') { 
 6660:             $r->print('<td>'.$sec.'</td>');
 6661:         }
 6662:         $r->print(
 6663:             '<td>'.$chgcontext.'</td>'
 6664:            .'<td>'.$rolestart.'</td>'
 6665:            .'<td>'.$roleend.'</td>'
 6666:            .&Apache::loncommon::end_data_table_row()."\n");
 6667:     }
 6668: 
 6669:     if ($showntableheader) { # Table footer, if content displayed above
 6670:         $r->print(&Apache::loncommon::end_data_table().
 6671:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6672:     } else { # No content displayed above
 6673:         $r->print('<p class="LC_info">'
 6674:                  .&mt('There are no records to display.')
 6675:                  .'</p>'
 6676:         );
 6677:     }
 6678: 
 6679:     # Form Footer
 6680:     $r->print( 
 6681:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6682:        .'<input type="hidden" name="action" value="changelogs" />'
 6683:        .'</form>');
 6684:     return;
 6685: }
 6686: 
 6687: sub print_useraccesslogs_display {
 6688:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6689:     my $formname = 'accesslog';
 6690:     my $form = 'document.accesslog';
 6691: 
 6692: # set breadcrumbs
 6693:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6694:     my $prevphasestr;
 6695:     if ($env{'form.popup'}) {
 6696:         $brcrum = [];
 6697:     } else {
 6698:         push (@{$brcrum},
 6699:             {href => "javascript:backPage($form)",
 6700:              text => $breadcrumb_text{'search'}});
 6701:         my @prevphases;
 6702:         if ($env{'form.prevphases'}) {
 6703:             @prevphases = split(/,/,$env{'form.prevphases'});
 6704:             $prevphasestr = $env{'form.prevphases'};
 6705:         }
 6706:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6707:             push(@{$brcrum},
 6708:                   {href => "javascript:backPage($form,'get_user_info','select')",
 6709:                    text => $breadcrumb_text{'userpicked'}});
 6710:             if ($env{'form.phase'} eq 'userpicked') {
 6711:                 $prevphasestr = 'userpicked';
 6712:             }
 6713:         }
 6714:     }
 6715:     push(@{$brcrum},
 6716:              {href => '/adm/createuser?action=accesslogs',
 6717:               text => 'User access logs',
 6718:               help => 'Domain_User_Access_Logs'});
 6719:     my $bread_crumbs_component = 'User Access Logs';
 6720:     my $args = { bread_crumbs           => $brcrum,
 6721:                  bread_crumbs_component => 'User Management'};
 6722:     if ($env{'form.popup'}) {
 6723:         $args->{'no_nav_bar'} = 1;
 6724:         $args->{'bread_crumbs_nomenu'} = 1;
 6725:     }
 6726: 
 6727: # set javascript
 6728:     my ($jsback,$elements) = &crumb_utilities();
 6729:     my $jsnav = &userlogdisplay_js($formname);
 6730: 
 6731:     my $jscript = (<<ENDSCRIPT);
 6732: <script type="text/javascript">
 6733: // <![CDATA[
 6734: 
 6735: $jsback
 6736: $jsnav
 6737: 
 6738: // ]]>
 6739: </script>
 6740: 
 6741: ENDSCRIPT
 6742: 
 6743: # print page header
 6744:     $r->print(&header($jscript,$args));
 6745: 
 6746: # early out unless log data can be displayed.
 6747:     unless ($permission->{'activity'}) {
 6748:         $r->print('<p class="LC_warning">'
 6749:                  .&mt('You do not have rights to display user access logs.')
 6750:                  .'</p>');
 6751:         if ($env{'form.popup'}) {
 6752:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 6753:         } else {
 6754:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6755:         }
 6756:         return;
 6757:     }
 6758: 
 6759:     unless ($udom eq $env{'request.role.domain'}) {
 6760:         $r->print('<p class="LC_warning">'
 6761:                  .&mt("User's domain must match role's domain")
 6762:                  .'</p>'
 6763:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6764:         return;
 6765:     }
 6766: 
 6767:     if (($uname eq '') || ($udom eq '')) {
 6768:         $r->print('<p class="LC_warning">'
 6769:                  .&mt('Invalid username or domain')
 6770:                  .'</p>'
 6771:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6772:         return;
 6773:     }
 6774: 
 6775:     if (&Apache::lonnet::privileged($uname,$udom,
 6776:                                     [$env{'request.role.domain'}],['dc','su'])) {
 6777:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 6778:                                             [$env{'request.role.domain'}],['dc','su'])) {
 6779:             $r->print('<p class="LC_warning">'
 6780:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 6781:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 6782:                                                          $uname,$udom))
 6783:                  .'</p>');
 6784:             if ($env{'form.popup'}) {
 6785:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 6786:             } else {
 6787:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 6788:             }
 6789:             return;
 6790:         }
 6791:     }
 6792: 
 6793: # set defaults
 6794:     my $now = time();
 6795:     my $defstart = $now - (7*24*3600);
 6796:     my %defaults = (
 6797:                      page                 => '1',
 6798:                      show                 => '10',
 6799:                      activity             => 'any',
 6800:                      accesslog_start_date => $defstart,
 6801:                      accesslog_end_date   => $now,
 6802:                    );
 6803:     my $more_records = 0;
 6804: 
 6805: # set current
 6806:     my %curr;
 6807:     foreach my $item ('show','page','activity') {
 6808:         $curr{$item} = $env{'form.'.$item};
 6809:     }
 6810:     my ($startdate,$enddate) =
 6811:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 6812:     $curr{'accesslog_start_date'} = $startdate;
 6813:     $curr{'accesslog_end_date'} = $enddate;
 6814:     foreach my $key (keys(%defaults)) {
 6815:         if ($curr{$key} eq '') {
 6816:             $curr{$key} = $defaults{$key};
 6817:         }
 6818:     }
 6819:     my ($minshown,$maxshown);
 6820:     $minshown = 1;
 6821:     my $count = 0;
 6822:     if ($curr{'show'} =~ /\D/) {
 6823:         $curr{'page'} = 1;
 6824:     } else {
 6825:         $maxshown = $curr{'page'} * $curr{'show'};
 6826:         if ($curr{'page'} > 1) {
 6827:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6828:         }
 6829:     }
 6830: 
 6831: # form header
 6832:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6833:               &activity_display_filter($formname,\%curr));
 6834: 
 6835:     my $showntableheader = 0;
 6836:     my ($nav_script,$nav_links);
 6837: 
 6838: # table header
 6839:     my $tableheader = '<h3>'.
 6840:         &mt('User access logs for: [_1]',
 6841:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>'
 6842:        .&Apache::loncommon::start_data_table_header_row()
 6843:        .'<th>&nbsp;</th>'
 6844:        .'<th>'.&mt('When').'</th>'
 6845:        .'<th>'.&mt('HostID').'</th>'
 6846:        .'<th>'.&mt('Event').'</th>'
 6847:        .'<th>'.&mt('Other data').'</th>'
 6848:        .&Apache::loncommon::end_data_table_header_row();
 6849: 
 6850:     my %filters=(
 6851:         start  => $curr{'accesslog_start_date'},
 6852:         end    => $curr{'accesslog_end_date'},
 6853:         action => $curr{'activity'},
 6854:     );
 6855: 
 6856:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 6857:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6858:         my (%courses,%missing);
 6859:         my @results = split(/\&/,$reply);
 6860:         foreach my $item (reverse(@results)) {
 6861:             my ($timestamp,$host,$event) = split(/:/,$item);
 6862:             next unless ($event =~ /^(Log|Role)/);
 6863:             if ($curr{'show'} !~ /\D/) {
 6864:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 6865:                     $more_records = 1;
 6866:                     last;
 6867:                 }
 6868:             }
 6869:             $count ++;
 6870:             next if ($count < $minshown);
 6871:             unless ($showntableheader) {
 6872:                 $r->print($nav_script
 6873:                          .&Apache::loncommon::start_data_table()
 6874:                          .$tableheader);
 6875:                 $r->rflush();
 6876:                 $showntableheader = 1;
 6877:             }
 6878:             my ($shown,$extra);
 6879:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 6880:             if ($event eq 'Role') {
 6881:                 my ($rolecode,$extent) = split(/\./,$data,2);
 6882:                 next if ($extent eq '');
 6883:                 my ($crstype,$desc,$info);
 6884:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 6885:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 6886:                     my $cid = $cdom.'_'.$cnum;
 6887:                     if (exists($courses{$cid})) {
 6888:                         $crstype = $courses{$cid}{'type'};
 6889:                         $desc = $courses{$cid}{'description'};
 6890:                     } elsif ($missing{$cid}) {
 6891:                         $crstype = 'Course';
 6892:                         $desc = 'Course/Community';
 6893:                     } else {
 6894:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6895:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 6896:                             $courses{$cid} = $crsinfo{$cid};
 6897:                             $crstype = $crsinfo{$cid}{'type'};
 6898:                             $desc = $crsinfo{$cid}{'description'};
 6899:                         } else {
 6900:                             $missing{$cid} = 1;
 6901:                         }
 6902:                     }
 6903:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 6904:                     if ($sec ne '') {
 6905:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 6906:                     }
 6907:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 6908:                     my ($dom,$name) = ($1,$2);
 6909:                     if ($rolecode eq 'au') {
 6910:                         $extra = '';
 6911:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 6912:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 6913:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 6914:                         $extra = &mt('Domain: [_1]',$dom);
 6915:                     }
 6916:                 }
 6917:                 my $rolename;
 6918:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 6919:                     my $role = $3;
 6920:                     my $owner = "($2:$1)";
 6921:                     if ($2 eq $1.'-domainconfig') {
 6922:                         $owner = '(ad hoc)';
 6923:                     }
 6924:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 6925:                 } else {
 6926:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 6927:                 }
 6928:                 $shown = &mt('Role selection: [_1]',$rolename);
 6929:             } else {
 6930:                 $shown = &mt($event);
 6931:                 if ($data =~ /^webdav/) {
 6932:                     my ($path,$clientip) = split(/\s+/,$data,2);
 6933:                     $path =~ s/^webdav//;
 6934:                     if ($clientip ne '') {
 6935:                         $extra = &mt('Client IP address: [_1]',$clientip);
 6936:                     }
 6937:                     if ($path ne '') {
 6938:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 6939:                     }
 6940:                 } elsif ($data ne '') {
 6941:                     $extra = &mt('Client IP address: [_1]',$data);
 6942:                 }
 6943:             }
 6944:             $r->print(
 6945:             &Apache::loncommon::start_data_table_row()
 6946:            .'<td>'.$count.'</td>'
 6947:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 6948:            .'<td>'.$host.'</td>'
 6949:            .'<td>'.$shown.'</td>'
 6950:            .'<td>'.$extra.'</td>'
 6951:            .&Apache::loncommon::end_data_table_row()."\n");
 6952:         }
 6953:     }
 6954: 
 6955:     if ($showntableheader) { # Table footer, if content displayed above
 6956:         $r->print(&Apache::loncommon::end_data_table().
 6957:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6958:     } else { # No content displayed above
 6959:         $r->print('<p class="LC_info">'
 6960:                  .&mt('There are no records to display.')
 6961:                  .'</p>');
 6962:     }
 6963: 
 6964:     if ($env{'form.popup'} == 1) {
 6965:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 6966:     }
 6967: 
 6968:     # Form Footer
 6969:     $r->print(
 6970:         '<input type="hidden" name="currstate" value="" />'
 6971:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 6972:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 6973:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6974:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 6975:        .'<input type="hidden" name="phase" value="activity" />'
 6976:        .'<input type="hidden" name="action" value="accesslogs" />'
 6977:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 6978:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 6979:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 6980:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 6981:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 6982:        .'</form>');
 6983:     return;
 6984: }
 6985: 
 6986: sub earlyout_accesslog_form {
 6987:     my ($formname,$prevphasestr,$udom) = @_;
 6988:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 6989:    return <<"END";
 6990: <form action="/adm/createuser" method="post" name="$formname">
 6991: <input type="hidden" name="currstate" value="" />
 6992: <input type="hidden" name="prevphases" value="$prevphasestr" />
 6993: <input type="hidden" name="phase" value="activity" />
 6994: <input type="hidden" name="action" value="accesslogs" />
 6995: <input type="hidden" name="srchdomain" value="$udom" />
 6996: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 6997: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 6998: <input type="hidden" name="srchterm" value="$srchterm" />
 6999: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7000: </form>
 7001: END
 7002: }
 7003: 
 7004: sub activity_display_filter {
 7005:     my ($formname,$curr) = @_;
 7006:     my $nolink = 1;
 7007:     my $output = '<table><tr><td valign="top">'.
 7008:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7009:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7010:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7011:                  '</td><td>&nbsp;&nbsp;</td>';
 7012:     my $startform =
 7013:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7014:                                             $curr->{'accesslog_start_date'},undef,
 7015:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7016:     my $endform =
 7017:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7018:                                             $curr->{'accesslog_end_date'},undef,
 7019:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7020:     my %lt = &Apache::lonlocal::texthash (
 7021:                                           activity => 'Activity',
 7022:                                           Role     => 'Role selection',
 7023:                                           log      => 'Log-in or Logout',
 7024:     );
 7025:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7026:                '<table><tr><td>'.&mt('After:').
 7027:                '</td><td>'.$startform.'</td></tr>'.
 7028:                '<tr><td>'.&mt('Before:').'</td>'.
 7029:                '<td>'.$endform.'</td></tr></table>'.
 7030:                '</td>'.
 7031:                '<td>&nbsp;&nbsp;</td>'.
 7032:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7033:                '<select name="activity"><option value="any"';
 7034:     if ($curr->{'activity'} eq 'any') {
 7035:         $output .= ' selected="selected"';
 7036:     }
 7037:     $output .= '>'.&mt('Any').'</option>'."\n";
 7038:     foreach my $activity ('Role','log') {
 7039:         my $selstr = '';
 7040:         if ($activity eq $curr->{'activity'}) {
 7041:             $selstr = ' selected="selected"';
 7042:         }
 7043:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7044:     }
 7045:     $output .= '</select></td>'.
 7046:                '</tr></table>';
 7047:     # Update Display button
 7048:     $output .= '<p>'
 7049:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7050:               .'</p><hr />';
 7051:     return $output;
 7052: }
 7053: 
 7054: sub userlogdisplay_js {
 7055:     my ($formname) = @_;
 7056:     return <<"ENDSCRIPT";
 7057: 
 7058: function chgPage(caller) {
 7059:     if (caller == 'previous') {
 7060:         document.$formname.page.value --;
 7061:     }
 7062:     if (caller == 'next') {
 7063:         document.$formname.page.value ++;
 7064:     }
 7065:     document.$formname.submit();
 7066:     return;
 7067: }
 7068: ENDSCRIPT
 7069: }
 7070: 
 7071: sub userlogdisplay_navlinks {
 7072:     my ($curr,$more_records) = @_;
 7073:     return unless(ref($curr) eq 'HASH');
 7074:     # Navigation Buttons
 7075:     my $nav_links = '<p>';
 7076:     if (($curr->{'page'} > 1) || ($more_records)) {
 7077:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7078:             $nav_links .= '<input type="button"'
 7079:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7080:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7081:                          .'" /> ';
 7082:         }
 7083:         if ($more_records) {
 7084:             $nav_links .= '<input type="button"'
 7085:                          .' onclick="javascript:chgPage('."'next'".');"'
 7086:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7087:                          .'" />';
 7088:         }
 7089:     }
 7090:     $nav_links .= '</p>';
 7091:     return $nav_links;
 7092: }
 7093: 
 7094: sub role_display_filter {
 7095:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7096:     my $lctype;
 7097:     if ($context eq 'course') {
 7098:         $lctype = lc($crstype);
 7099:     }
 7100:     my $nolink = 1;
 7101:     my $output = '<table><tr><td valign="top">'.
 7102:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7103:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7104:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7105:                  '</td><td>&nbsp;&nbsp;</td>';
 7106:     my $startform =
 7107:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7108:                                             $curr->{'rolelog_start_date'},undef,
 7109:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7110:     my $endform =
 7111:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7112:                                             $curr->{'rolelog_end_date'},undef,
 7113:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7114:     my %lt = &rolechg_contexts($context,$crstype);
 7115:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7116:                '<table><tr><td>'.&mt('After:').
 7117:                '</td><td>'.$startform.'</td></tr>'.
 7118:                '<tr><td>'.&mt('Before:').'</td>'.
 7119:                '<td>'.$endform.'</td></tr></table>'.
 7120:                '</td>'.
 7121:                '<td>&nbsp;&nbsp;</td>'.
 7122:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7123:                '<select name="role"><option value="any"';
 7124:     if ($curr->{'role'} eq 'any') {
 7125:         $output .= ' selected="selected"';
 7126:     }
 7127:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7128:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7129:     foreach my $role (@roles) {
 7130:         my $plrole;
 7131:         if ($role eq 'cr') {
 7132:             $plrole = &mt('Custom Role');
 7133:         } else {
 7134:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7135:         }
 7136:         my $selstr = '';
 7137:         if ($role eq $curr->{'role'}) {
 7138:             $selstr = ' selected="selected"';
 7139:         }
 7140:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7141:     }
 7142:     $output .= '</select></td>'.
 7143:                '<td>&nbsp;&nbsp;</td>'.
 7144:                '<td valign="top"><b>'.
 7145:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7146:     my @posscontexts;
 7147:     if ($context eq 'course') {
 7148:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7149:     } elsif ($context eq 'domain') {
 7150:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7151:     } else {
 7152:         @posscontexts = ('any','author','domain');
 7153:     } 
 7154:     foreach my $chgtype (@posscontexts) {
 7155:         my $selstr = '';
 7156:         if ($curr->{'chgcontext'} eq $chgtype) {
 7157:             $selstr = ' selected="selected"';
 7158:         }
 7159:         if ($context eq 'course') {
 7160:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7161:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7162:             }
 7163:         }
 7164:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7165:     }
 7166:     $output .= '</select></td>'
 7167:               .'</tr></table>';
 7168: 
 7169:     # Update Display button
 7170:     $output .= '<p>'
 7171:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7172:               .'</p>';
 7173: 
 7174:     # Server version info
 7175:     my $needsrev = '2.11.0';
 7176:     if ($context eq 'course') {
 7177:         $needsrev = '2.7.0';
 7178:     }
 7179:     
 7180:     $output .= '<p class="LC_info">'
 7181:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7182:                   ,$needsrev);
 7183:     if ($version) {
 7184:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7185:     }
 7186:     $output .= '</p><hr />';
 7187:     return $output;
 7188: }
 7189: 
 7190: sub rolechg_contexts {
 7191:     my ($context,$crstype) = @_;
 7192:     my %lt;
 7193:     if ($context eq 'course') {
 7194:         %lt = &Apache::lonlocal::texthash (
 7195:                                              any          => 'Any',
 7196:                                              automated    => 'Automated Enrollment',
 7197:                                              updatenow    => 'Roster Update',
 7198:                                              createcourse => 'Course Creation',
 7199:                                              course       => 'User Management in course',
 7200:                                              domain       => 'User Management in domain',
 7201:                                              selfenroll   => 'Self-enrolled',
 7202:                                              requestcourses => 'Course Request',
 7203:                                          );
 7204:         if ($crstype eq 'Community') {
 7205:             $lt{'createcourse'} = &mt('Community Creation');
 7206:             $lt{'course'} = &mt('User Management in community');
 7207:             $lt{'requestcourses'} = &mt('Community Request');
 7208:         }
 7209:     } elsif ($context eq 'domain') {
 7210:         %lt = &Apache::lonlocal::texthash (
 7211:                                              any           => 'Any',
 7212:                                              domain        => 'User Management in domain',
 7213:                                              requestauthor => 'Authoring Request',
 7214:                                              server        => 'Command line script (DC role)',
 7215:                                              domconfig     => 'Self-enrolled',
 7216:                                          );
 7217:     } else {
 7218:         %lt = &Apache::lonlocal::texthash (
 7219:                                              any    => 'Any',
 7220:                                              domain => 'User Management in domain',
 7221:                                              author => 'User Management by author',
 7222:                                          );
 7223:     } 
 7224:     return %lt;
 7225: }
 7226: 
 7227: sub print_helpdeskaccess_display {
 7228:     my ($r,$permission,$brcrum) = @_;
 7229:     my $formname = 'helpdeskaccess';
 7230:     my $helpitem = 'Course_Helpdesk_Access';
 7231:     push (@{$brcrum},
 7232:              {href => '/adm/createuser?action=helpdesk',
 7233:               text => 'Helpdesk Access',
 7234:               help => $helpitem});
 7235:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7236:     my $args = { bread_crumbs           => $brcrum,
 7237:                  bread_crumbs_component => $bread_crumbs_component};
 7238: 
 7239:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7240:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7241:     my $confname = $cdom.'-domainconfig';
 7242:     my $crstype = &Apache::loncommon::course_type();
 7243: 
 7244:     my @accesstypes = ('all','dh','da','none');
 7245:     my ($numstatustypes,@jsarray);
 7246:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7247:     if (ref($types) eq 'ARRAY') {
 7248:         if (@{$types} > 0) {
 7249:             $numstatustypes = scalar(@{$types});
 7250:             push(@accesstypes,'status');
 7251:             @jsarray = ('bystatus');
 7252:         }
 7253:     }
 7254:     my %customroles = &get_domain_customroles($cdom,$confname);
 7255:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7256:     if (keys(%domhelpdesk)) {
 7257:        push(@accesstypes,('inc','exc'));
 7258:        push(@jsarray,('notinc','notexc'));
 7259:     }
 7260:     push(@jsarray,'privs');
 7261:     my $hiddenstr = join("','",@jsarray);
 7262:     my $rolestr = join("','",sort(keys(%customroles)));
 7263: 
 7264:     my $jscript;
 7265:     my (%settings,%overridden);
 7266:     if (keys(%customroles)) {
 7267:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7268:                                 $types,\%customroles,\%settings,\%overridden);
 7269:         my %jsfull=();
 7270:         my %jslevels= (
 7271:                      course => {},
 7272:                      domain => {},
 7273:                      system => {},
 7274:                     );
 7275:         my %jslevelscurrent=(
 7276:                            course => {},
 7277:                            domain => {},
 7278:                            system => {},
 7279:                           );
 7280:         my (%privs,%jsprivs);
 7281:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7282:         foreach my $priv (keys(%jsfull)) {
 7283:             if ($jslevels{'course'}{$priv}) {
 7284:                 $jsprivs{$priv} = 1;
 7285:             }
 7286:         }
 7287:         my (%elements,%stored);
 7288:         foreach my $role (keys(%customroles)) {
 7289:             $elements{$role.'_access'} = 'radio';
 7290:             $elements{$role.'_incrs'} = 'radio';
 7291:             if ($numstatustypes) {
 7292:                 $elements{$role.'_status'} = 'checkbox';
 7293:             }
 7294:             if (keys(%domhelpdesk) > 0) {
 7295:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7296:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7297:             }
 7298:             $elements{$role.'_override'} = 'checkbox';
 7299:             if (ref($settings{$role}) eq 'HASH') {
 7300:                 if ($settings{$role}{'access'} ne '') {
 7301:                     my $curraccess = $settings{$role}{'access'};
 7302:                     $stored{$role.'_access'} = $curraccess;
 7303:                     $stored{$role.'_incrs'} = 1;
 7304:                     if ($curraccess eq 'status') {
 7305:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7306:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7307:                         }
 7308:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7309:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7310:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7311:                         }
 7312:                     }
 7313:                 } else {
 7314:                     $stored{$role.'_incrs'} = 0;
 7315:                 }
 7316:                 $stored{$role.'_override'} = [];
 7317:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7318:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7319:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7320:                             push(@{$stored{$role.'_override'}},$priv);
 7321:                         }
 7322:                     }
 7323:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7324:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7325:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7326:                                 push(@{$stored{$role.'_override'}},$priv);
 7327:                             }
 7328:                         }
 7329:                     }
 7330:                 }
 7331:             } else {
 7332:                 $stored{$role.'_incrs'} = 0;
 7333:             }
 7334:         }
 7335:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7336:     }
 7337: 
 7338:     my $js = <<"ENDJS";
 7339: <script type="text/javascript">
 7340: // <![CDATA[
 7341: $jscript;
 7342: 
 7343: function switchRoleTab(caller,role) {
 7344:     if (document.getElementById(role+'_maindiv')) {
 7345:         if (caller.id != 'LC_current_minitab') {
 7346:             if (document.getElementById('LC_current_minitab')) {
 7347:                 document.getElementById('LC_current_minitab').id=null;
 7348:             }
 7349:             var roledivs = Array('$rolestr');
 7350:             if (roledivs.length > 0) {
 7351:                 for (var i=0; i<roledivs.length; i++) {
 7352:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7353:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7354:                     }
 7355:                 }
 7356:             }
 7357:             caller.id = 'LC_current_minitab';
 7358:             document.getElementById(role+'_maindiv').style.display='block';
 7359:         }
 7360:     }
 7361:     return false;
 7362: }
 7363: 
 7364: function helpdeskAccess(role) {
 7365:     var curraccess = null;
 7366:     if (document.$formname.elements[role+'_access'].length) {
 7367:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7368:             if (document.$formname.elements[role+'_access'][i].checked) {
 7369:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7370:             }
 7371:         }
 7372:     }
 7373:     var shown = Array();
 7374:     var hidden = Array();
 7375:     if (curraccess == 'none') {
 7376:         hidden = Array ('$hiddenstr');
 7377:     } else {
 7378:         if (curraccess == 'status') {
 7379:             shown = Array ('bystatus','privs');
 7380:             hidden = Array ('notinc','notexc');
 7381:         } else {
 7382:             if (curraccess == 'exc') {
 7383:                 shown = Array ('notexc','privs');
 7384:                 hidden = Array ('notinc','bystatus');
 7385:             }
 7386:             if (curraccess == 'inc') {
 7387:                 shown = Array ('notinc','privs');
 7388:                 hidden = Array ('notexc','bystatus');
 7389:             }
 7390:             if (curraccess == 'all') {
 7391:                 shown = Array ('privs');
 7392:                 hidden = Array ('notinc','notexc','bystatus');
 7393:             }
 7394:         }
 7395:     }
 7396:     if (hidden.length > 0) {
 7397:         for (var i=0; i<hidden.length; i++) {
 7398:             if (document.getElementById(role+'_'+hidden[i])) {
 7399:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7400:             }
 7401:         }
 7402:     }
 7403:     if (shown.length > 0) {
 7404:         for (var i=0; i<shown.length; i++) {
 7405:             if (document.getElementById(role+'_'+shown[i])) {
 7406:                 if (shown[i] == 'privs') {
 7407:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7408:                 } else {
 7409:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7410:                 }
 7411:             }
 7412:         }
 7413:     }
 7414:     return;
 7415: }
 7416: 
 7417: function toggleAccess(role) {
 7418:     if ((document.getElementById(role+'_setincrs')) &&
 7419:         (document.getElementById(role+'_setindom'))) {
 7420:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7421:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7422:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7423:                     document.getElementById(role+'_setindom').style.display = 'none';
 7424:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7425:                 } else {
 7426:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7427:                     document.getElementById(role+'_setindom').style.display = 'block';
 7428:                 }
 7429:                 break;
 7430:             }
 7431:         }
 7432:     }
 7433:     return;
 7434: }
 7435: 
 7436: // ]]>
 7437: </script>
 7438: ENDJS
 7439: 
 7440:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7441: 
 7442:     # print page header
 7443:     $r->print(&header($js,$args));
 7444:     # print form header
 7445:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7446: 
 7447:     if (keys(%customroles)) {
 7448:         my %lt = &Apache::lonlocal::texthash(
 7449:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7450:                     'rou'    => 'Role usage',
 7451:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7452:                     'udd'    => 'Use domain default',
 7453:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7454:                     'dh'     => 'All with domain helpdesk role',
 7455:                     'da'     => 'All with domain helpdesk assistant role',
 7456:                     'none'   => 'None',
 7457:                     'status' => 'Determined based on institutional status',
 7458:                     'inc'    => 'Include all, but exclude specific personnel',
 7459:                     'exc'    => 'Exclude all, but include specific personnel',
 7460:                     'hel'    => 'Helpdesk',
 7461:                     'rpr'    => 'Role privileges',
 7462:                  );
 7463:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7464:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7465:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7466:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7467:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7468:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7469:             }
 7470:         }
 7471:         my $count = 0;
 7472:         foreach my $role (sort(keys(%customroles))) {
 7473:             my ($order,$desc,$access_in_dom);
 7474:             if (ref($domcurrent{$role}) eq 'HASH') {
 7475:                 $order = $domcurrent{$role}{'order'};
 7476:                 $desc = $domcurrent{$role}{'desc'};
 7477:                 $access_in_dom = $domcurrent{$role}{'access'};
 7478:             }
 7479:             if ($order eq '') {
 7480:                 $order = $count;
 7481:             }
 7482:             $ordered{$order} = $role;
 7483:             if ($desc ne '') {
 7484:                 $description{$role} = $desc;
 7485:             } else {
 7486:                 $description{$role}= $role;
 7487:             }
 7488:             $count++;
 7489:         }
 7490:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7491:         my @roles_by_num = ();
 7492:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7493:             push(@roles_by_num,$ordered{$item});
 7494:         }
 7495:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7496:         if ($permission->{'owner'}) {
 7497:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7498:             $r->print('<input type="hidden" name="state" value="process" />'.
 7499:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7500:         } else {
 7501:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7502:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7503:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7504:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7505:             }
 7506:             $disabled = ' disabled="disabled"';
 7507:         }
 7508:         $r->print('</p>');
 7509: 
 7510:         $r->print('<div id="LC_minitab_header"><ul>');
 7511:         my $count = 0;
 7512:         my %visibility;
 7513:         foreach my $role (@roles_by_num) {
 7514:             my $id;
 7515:             if ($count == 0) {
 7516:                 $id=' id="LC_current_minitab"';
 7517:                 $visibility{$role} = ' style="display:block"';
 7518:             } else {
 7519:                 $visibility{$role} = ' style="display:none"';
 7520:             }
 7521:             $count ++;
 7522:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7523:         }
 7524:         $r->print('</ul></div>');
 7525: 
 7526:         foreach my $role (@roles_by_num) {
 7527:             my %usecheck = (
 7528:                              all => ' checked="checked"',
 7529:                            );
 7530:             my %displaydiv = (
 7531:                                 status => 'none',
 7532:                                 inc    => 'none',
 7533:                                 exc    => 'none',
 7534:                                 priv   => 'block',
 7535:                              );
 7536:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7537:             if (ref($settings{$role}) eq 'HASH') {
 7538:                 if ($settings{$role}{'access'} ne '') {
 7539:                     $indomvis = ' style="display:none"';
 7540:                     $incrsvis = ' style="display:block"';
 7541:                     $incrscheck = ' checked="checked"';
 7542:                     if ($settings{$role}{'access'} ne 'all') {
 7543:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7544:                         delete($usecheck{'all'});
 7545:                         if ($settings{$role}{'access'} eq 'status') {
 7546:                             my $access = 'status';
 7547:                             $displaydiv{$access} = 'inline';
 7548:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7549:                                 $selected{$access} = $settings{$role}{$access};
 7550:                             }
 7551:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7552:                             my $access = $1;
 7553:                             $displaydiv{$access} = 'inline';
 7554:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7555:                                 $selected{$access} = $settings{$role}{$access};
 7556:                             }
 7557:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7558:                             $displaydiv{'priv'} = 'none';
 7559:                         }
 7560:                     }
 7561:                 } else {
 7562:                     $indomcheck = ' checked="checked"';
 7563:                     $indomvis = ' style="display:block"';
 7564:                     $incrsvis = ' style="display:none"';
 7565:                 }
 7566:             } else {
 7567:                 $indomcheck = ' checked="checked"';
 7568:                 $indomvis = ' style="display:block"';
 7569:                 $incrsvis = ' style="display:none"';
 7570:             }
 7571:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7572:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7573:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7574:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7575:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7576:                       '<span>'.('&nbsp;'x2).
 7577:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7578:                       $lt{'udd'}.'</label><span></p>'.
 7579:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7580:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7581:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7582:             foreach my $access (@accesstypes) {
 7583:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7584:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7585:                 if ($access eq 'status') {
 7586:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7587:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7588:                                                                         $othertitle,$usertypes,$types,$disabled).
 7589:                               '</div>');
 7590:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7591:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7592:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7593:                                                                  \%domhelpdesk,$disabled).
 7594:                               '</div>');
 7595:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7596:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7597:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7598:                                                                  \%domhelpdesk,$disabled).
 7599:                               '</div>');
 7600:                 }
 7601:                 $r->print('</p>');
 7602:             }
 7603:             $r->print('</div></fieldset>');
 7604:             my %full=();
 7605:             my %levels= (
 7606:                          course => {},
 7607:                          domain => {},
 7608:                          system => {},
 7609:                         );
 7610:             my %levelscurrent=(
 7611:                                course => {},
 7612:                                domain => {},
 7613:                                system => {},
 7614:                               );
 7615:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7616:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7617:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7618:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7619:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7620:         }
 7621:         if ($permission->{'owner'}) {
 7622:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7623:         }
 7624:     } else {
 7625:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7626:     }
 7627:     # Form Footer
 7628:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7629:              .'</form>');
 7630:     return;
 7631: }
 7632: 
 7633: sub domain_adhoc_access {
 7634:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7635:     my %domusage;
 7636:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7637:     foreach my $role (keys(%{$roles})) {
 7638:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7639:             my $access = $domcurrent->{$role}{'access'};
 7640:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7641:                 $access = 'all';
 7642:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7643:                                                                                           &Apache::lonnet::plaintext('da'));
 7644:             } elsif ($access eq 'status') {
 7645:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7646:                     my @shown;
 7647:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7648:                         unless ($type eq 'default') {
 7649:                             if ($usertypes->{$type}) {
 7650:                                 push(@shown,$usertypes->{$type});
 7651:                             }
 7652:                         }
 7653:                     }
 7654:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7655:                         push(@shown,$othertitle);
 7656:                     }
 7657:                     if (@shown) {
 7658:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7659:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7660:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7661:                     } else {
 7662:                         $domusage{$role} = &mt('No one in the domain');
 7663:                     }
 7664:                 }
 7665:             } elsif ($access eq 'inc') {
 7666:                 my @dominc = ();
 7667:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7668:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7669:                         my ($uname,$udom) = split(/:/,$user);
 7670:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7671:                     }
 7672:                     my $showninc = join(', ',@dominc);
 7673:                     if ($showninc ne '') {
 7674:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7675:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7676:                     } else {
 7677:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7678:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7679:                     }
 7680:                 }
 7681:             } elsif ($access eq 'exc') {
 7682:                 my @domexc = ();
 7683:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7684:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7685:                         my ($uname,$udom) = split(/:/,$user);
 7686:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7687:                     }
 7688:                 }
 7689:                 my $shownexc = join(', ',@domexc);
 7690:                 if ($shownexc ne '') {
 7691:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 7692:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 7693:                 } else {
 7694:                     $domusage{$role} = &mt('No one in the domain');
 7695:                 }
 7696:             } elsif ($access eq 'none') {
 7697:                 $domusage{$role} = &mt('No one in the domain');
 7698:             } elsif ($access eq 'dh') {
 7699:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7700:             } elsif ($access eq 'da') {
 7701:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 7702:             } elsif ($access eq 'all') {
 7703:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7704:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7705:             }
 7706:         } else {
 7707:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7708:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7709:         }
 7710:     }
 7711:     return %domusage;
 7712: }
 7713: 
 7714: sub get_domain_customroles {
 7715:     my ($cdom,$confname) = @_;
 7716:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 7717:     my %customroles;
 7718:     foreach my $key (keys(%existing)) {
 7719:         if ($key=~/^rolesdef\_(\w+)$/) {
 7720:             my $rolename = $1;
 7721:             my %privs;
 7722:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 7723:             $customroles{$rolename} = \%privs;
 7724:         }
 7725:     }
 7726:     return %customroles;
 7727: }
 7728: 
 7729: sub role_priv_table {
 7730:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 7731:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7732:                    (ref($levelscurrent) eq 'HASH'));
 7733:     my %lt=&Apache::lonlocal::texthash (
 7734:                     'crl'  => 'Course Level Privilege',
 7735:                     'def'  => 'Domain Defaults',
 7736:                     'ove'  => 'Override in Course',
 7737:                     'ine'  => 'In effect',
 7738:                     'dis'  => 'Disabled',
 7739:                     'ena'  => 'Enabled',
 7740:                    );
 7741:     if ($crstype eq 'Community') {
 7742:         $lt{'ove'} = 'Override in Community',
 7743:     }
 7744:     my @status = ('Disabled','Enabled');
 7745:     my (%on,%off);
 7746:     if (ref($overridden) eq 'HASH') {
 7747:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 7748:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 7749:         }
 7750:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 7751:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 7752:         }
 7753:     }
 7754:     my $output=&Apache::loncommon::start_data_table().
 7755:                &Apache::loncommon::start_data_table_header_row().
 7756:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 7757:                '</th><th>'.$lt{'ine'}.'</th>'.
 7758:                &Apache::loncommon::end_data_table_header_row();
 7759:     foreach my $priv (sort(keys(%{$full}))) {
 7760:         next unless ($levels->{'course'}{$priv});
 7761:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 7762:         my ($default,$ineffect);
 7763:         if ($levelscurrent->{'course'}{$priv}) {
 7764:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7765:             $ineffect = $default;
 7766:         }
 7767:         my ($customstatus,$checked);
 7768:         $output .= &Apache::loncommon::start_data_table_row().
 7769:                    '<td>'.$privtext.'</td>'.
 7770:                    '<td>'.$default.'</td><td>';
 7771:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 7772:             if ($permission->{'owner'}) {
 7773:                 $checked = ' checked="checked"';
 7774:             }
 7775:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 7776:             $ineffect = $customstatus;
 7777:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 7778:             if ($permission->{'owner'}) {
 7779:                 $checked = ' checked="checked"';
 7780:             }
 7781:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 7782:             $ineffect = $customstatus;
 7783:         }
 7784:         if ($permission->{'owner'}) {
 7785:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 7786:         } else {
 7787:             $output .= $customstatus;
 7788:         }
 7789:         $output .= '</td><td>'.$ineffect.'</td>'.
 7790:                    &Apache::loncommon::end_data_table_row();
 7791:     }
 7792:     $output .= &Apache::loncommon::end_data_table();
 7793:     return $output;
 7794: }
 7795: 
 7796: sub get_adhocrole_settings {
 7797:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 7798:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 7799:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 7800:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 7801:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 7802:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 7803:             $settings->{$role}{'access'} = $curraccess;
 7804:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 7805:                 my @status = split(/,/,$rest);
 7806:                 my @currstatus;
 7807:                 foreach my $type (@status) {
 7808:                     if ($type eq 'default') {
 7809:                         push(@currstatus,$type);
 7810:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7811:                         push(@currstatus,$type);
 7812:                     }
 7813:                 }
 7814:                 if (@currstatus) {
 7815:                     $settings->{$role}{$curraccess} = \@currstatus;
 7816:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7817:                     my @personnel = split(/,/,$rest);
 7818:                     $settings->{$role}{$curraccess} = \@personnel;
 7819:                 }
 7820:             }
 7821:         }
 7822:     }
 7823:     foreach my $role (keys(%{$customroles})) {
 7824:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 7825:             my %currentprivs;
 7826:             if (ref($customroles->{$role}) eq 'HASH') {
 7827:                 if (exists($customroles->{$role}{'course'})) {
 7828:                     my %full=();
 7829:                     my %levels= (
 7830:                                   course => {},
 7831:                                   domain => {},
 7832:                                   system => {},
 7833:                                 );
 7834:                     my %levelscurrent=(
 7835:                                         course => {},
 7836:                                         domain => {},
 7837:                                         system => {},
 7838:                                       );
 7839:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 7840:                     %currentprivs = %{$levelscurrent{'course'}};
 7841:                 }
 7842:             }
 7843:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 7844:                 next if ($item eq '');
 7845:                 my ($rule,$rest) = split(/=/,$item);
 7846:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 7847:                 foreach my $priv (split(/:/,$rest)) {
 7848:                     if ($priv ne '') {
 7849:                         if ($rule eq 'off') {
 7850:                             push(@{$overridden->{$role}{'off'}},$priv);
 7851:                             if ($currentprivs{$priv}) {
 7852:                                 push(@{$settings->{$role}{'off'}},$priv);
 7853:                             }
 7854:                         } else {
 7855:                             push(@{$overridden->{$role}{'on'}},$priv);
 7856:                             unless ($currentprivs{$priv}) {
 7857:                                 push(@{$settings->{$role}{'on'}},$priv);
 7858:                             }
 7859:                         }
 7860:                     }
 7861:                 }
 7862:             }
 7863:         }
 7864:     }
 7865:     return;
 7866: }
 7867: 
 7868: sub update_helpdeskaccess {
 7869:     my ($r,$permission,$brcrum) = @_;
 7870:     my $helpitem = 'Course_Helpdesk_Access';
 7871:     push (@{$brcrum},
 7872:              {href => '/adm/createuser?action=helpdesk',
 7873:               text => 'Helpdesk Access',
 7874:               help => $helpitem},
 7875:              {href => '/adm/createuser?action=helpdesk',
 7876:               text => 'Result',
 7877:               help => $helpitem}
 7878:          );
 7879:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7880:     my $args = { bread_crumbs           => $brcrum,
 7881:                  bread_crumbs_component => $bread_crumbs_component};
 7882: 
 7883:     # print page header
 7884:     $r->print(&header('',$args));
 7885:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 7886:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 7887:         return;
 7888:     }
 7889:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 7890:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7891:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7892:     my $confname = $cdom.'-domainconfig';
 7893:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7894:     my $crstype = &Apache::loncommon::course_type();
 7895:     my %customroles = &get_domain_customroles($cdom,$confname);
 7896:     my (%settings,%overridden);
 7897:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7898:                             $types,\%customroles,\%settings,\%overridden);
 7899:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7900:     my (%changed,%storehash,@todelete);
 7901: 
 7902:     if (keys(%customroles)) {
 7903:         my (%newsettings,@incrs);
 7904:         foreach my $role (keys(%customroles)) {
 7905:             $newsettings{$role} = {
 7906:                                     access => '',
 7907:                                     status => '',
 7908:                                     exc    => '',
 7909:                                     inc    => '',
 7910:                                     on     => '',
 7911:                                     off    => '',
 7912:                                   };
 7913:             my %current;
 7914:             if (ref($settings{$role}) eq 'HASH') {
 7915:                 %current = %{$settings{$role}};
 7916:             }
 7917:             if (ref($overridden{$role}) eq 'HASH') {
 7918:                 $current{'overridden'} = $overridden{$role};
 7919:             }
 7920:             if ($env{'form.'.$role.'_incrs'}) {
 7921:                 my $access = $env{'form.'.$role.'_access'};
 7922:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 7923:                     push(@incrs,$role);
 7924:                     unless ($current{'access'} eq $access) {
 7925:                         $changed{$role}{'access'} = 1;
 7926:                         $storehash{'internal.adhoc.'.$role} = $access;
 7927:                     }
 7928:                     if ($access eq 'status') {
 7929:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 7930:                         my @stored;
 7931:                         my @shownstatus;
 7932:                         if (ref($types) eq 'ARRAY') {
 7933:                             foreach my $type (sort(@statuses)) {
 7934:                                 if ($type eq 'default') {
 7935:                                     push(@stored,$type);
 7936:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 7937:                                     push(@stored,$type);
 7938:                                     push(@shownstatus,$usertypes->{$type});
 7939:                                 }
 7940:                             }
 7941:                             if (grep(/^default$/,@statuses)) {
 7942:                                 push(@shownstatus,$othertitle);
 7943:                             }
 7944:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 7945:                         }
 7946:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 7947:                         if (ref($current{'status'}) eq 'ARRAY') {
 7948:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 7949:                             if (@diffs) {
 7950:                                 $changed{$role}{'status'} = 1;
 7951:                             }
 7952:                         } elsif (@stored) {
 7953:                             $changed{$role}{'status'} = 1;
 7954:                         }
 7955:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 7956:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 7957:                         my @newspecstaff;
 7958:                         my @stored;
 7959:                         my @currstaff;
 7960:                         foreach my $person (sort(@personnel)) {
 7961:                             if ($domhelpdesk{$person}) {
 7962:                                 push(@stored,$person);
 7963:                             }
 7964:                         }
 7965:                         if (ref($current{$access}) eq 'ARRAY') {
 7966:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 7967:                             if (@diffs) {
 7968:                                 $changed{$role}{$access} = 1;
 7969:                             }
 7970:                         } elsif (@stored) {
 7971:                             $changed{$role}{$access} = 1;
 7972:                         }
 7973:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 7974:                         foreach my $person (@stored) {
 7975:                             my ($uname,$udom) = split(/:/,$person);
 7976:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 7977:                         }
 7978:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 7979:                     }
 7980:                     $newsettings{$role}{'access'} = $access;
 7981:                 }
 7982:             } else {
 7983:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 7984:                     $changed{$role}{'access'} = 1;
 7985:                     $newsettings{$role} = {};
 7986:                     push(@todelete,'internal.adhoc.'.$role);
 7987:                 }
 7988:             }
 7989:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 7990:                 if (ref($current{'overridden'}) eq 'HASH') {
 7991:                     push(@todelete,'internal.adhocpriv.'.$role);
 7992:                 }
 7993:             } else {
 7994:                 my %full=();
 7995:                 my %levels= (
 7996:                              course => {},
 7997:                              domain => {},
 7998:                              system => {},
 7999:                             );
 8000:                 my %levelscurrent=(
 8001:                                    course => {},
 8002:                                    domain => {},
 8003:                                    system => {},
 8004:                                   );
 8005:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8006:                 my (@updatedon,@updatedoff,@override);
 8007:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8008:                 if (@override) {
 8009:                     foreach my $priv (sort(keys(%full))) {
 8010:                         next unless ($levels{'course'}{$priv});
 8011:                         if (grep(/^\Q$priv\E$/,@override)) {
 8012:                             if ($levelscurrent{'course'}{$priv}) {
 8013:                                 push(@updatedoff,$priv);
 8014:                             } else {
 8015:                                 push(@updatedon,$priv);
 8016:                             }
 8017:                         }
 8018:                     }
 8019:                 }
 8020:                 if (@updatedon) {
 8021:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8022:                 }
 8023:                 if (@updatedoff) {
 8024:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8025:                 }
 8026:                 if (ref($current{'overridden'}) eq 'HASH') {
 8027:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8028:                         if (@updatedon) {
 8029:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8030:                             if (@diffs) {
 8031:                                 $changed{$role}{'on'} = 1;
 8032:                             }
 8033:                         } else {
 8034:                             $changed{$role}{'on'} = 1;
 8035:                         }
 8036:                     } elsif (@updatedon) {
 8037:                         $changed{$role}{'on'} = 1;
 8038:                     }
 8039:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8040:                         if (@updatedoff) {
 8041:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8042:                             if (@diffs) {
 8043:                                 $changed{$role}{'off'} = 1;
 8044:                             }
 8045:                         } else {
 8046:                             $changed{$role}{'off'} = 1;
 8047:                         }
 8048:                     } elsif (@updatedoff) {
 8049:                         $changed{$role}{'off'} = 1;
 8050:                     }
 8051:                 } else {
 8052:                     if (@updatedon) {
 8053:                         $changed{$role}{'on'} = 1;
 8054:                     }
 8055:                     if (@updatedoff) {
 8056:                         $changed{$role}{'off'} = 1;
 8057:                     }
 8058:                 }
 8059:                 if (ref($changed{$role}) eq 'HASH') {
 8060:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8061:                         my $newpriv;
 8062:                         if (@updatedon) {
 8063:                             $newpriv = 'on='.join(':',@updatedon);
 8064:                         }
 8065:                         if (@updatedoff) {
 8066:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8067:                         }
 8068:                         if ($newpriv eq '') {
 8069:                             push(@todelete,'internal.adhocpriv.'.$role);
 8070:                         } else {
 8071:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8072:                         }
 8073:                     }
 8074:                 }
 8075:             }
 8076:         }
 8077:         if (@incrs) {
 8078:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8079:         } elsif (@todelete) {
 8080:             push(@todelete,'internal.adhocaccess');
 8081:         }
 8082:         if (keys(%changed)) {
 8083:             my ($putres,$delres);
 8084:             if (keys(%storehash)) {
 8085:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8086:                 my %newenvhash;
 8087:                 foreach my $key (keys(%storehash)) {
 8088:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8089:                 }
 8090:                 &Apache::lonnet::appenv(\%newenvhash);
 8091:             }
 8092:             if (@todelete) {
 8093:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8094:                 foreach my $key (@todelete) {
 8095:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8096:                 }
 8097:             }
 8098:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8099:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8100:                 my (%domcurrent,%ordered,%description,%domusage);
 8101:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8102:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8103:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8104:                     }
 8105:                 }
 8106:                 my $count = 0;
 8107:                 foreach my $role (sort(keys(%customroles))) {
 8108:                     my ($order,$desc);
 8109:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8110:                         $order = $domcurrent{$role}{'order'};
 8111:                         $desc = $domcurrent{$role}{'desc'};
 8112:                     }
 8113:                     if ($order eq '') {
 8114:                         $order = $count;
 8115:                     }
 8116:                     $ordered{$order} = $role;
 8117:                     if ($desc ne '') {
 8118:                         $description{$role} = $desc;
 8119:                     } else {
 8120:                         $description{$role}= $role;
 8121:                     }
 8122:                     $count++;
 8123:                 }
 8124:                 my @roles_by_num = ();
 8125:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8126:                     push(@roles_by_num,$ordered{$item});
 8127:                 }
 8128:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8129:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8130:                 $r->print('<ul>');
 8131:                 foreach my $role (@roles_by_num) {
 8132:                     next unless (ref($changed{$role}) eq 'HASH');
 8133:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8134:                               '<ul>');
 8135:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8136:                         $r->print('<li>');
 8137:                         if ($env{'form.'.$role.'_incrs'}) {
 8138:                             if ($newsettings{$role}{'access'} eq 'all') {
 8139:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8140:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8141:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8142:                                               &Apache::lonnet::plaintext('dh')));
 8143:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8144:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8145:                                               &Apache::lonnet::plaintext('da')));
 8146:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8147:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8148:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8149:                                 if ($newsettings{$role}{'status'}) {
 8150:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8151:                                     if (split(/,/,$rest) > 1) {
 8152:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8153:                                                       $newsettings{$role}{'status'}));
 8154:                                     } else {
 8155:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8156:                                                       $newsettings{$role}{'status'}));
 8157:                                     }
 8158:                                 } else {
 8159:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8160:                                 }
 8161:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8162:                                 if ($newsettings{$role}{'exc'}) {
 8163:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8164:                                 } else {
 8165:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8166:                                 }
 8167:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8168:                                 if ($newsettings{$role}{'inc'}) {
 8169:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8170:                                 } else {
 8171:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8172:                                 }
 8173:                             }
 8174:                         } else {
 8175:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8176:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8177:                         }
 8178:                         $r->print('</li>');
 8179:                     }
 8180:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8181:                         if ($changed{$role}{'off'}) {
 8182:                             if ($newsettings{$role}{'off'}) {
 8183:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8184:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8185:                             } else {
 8186:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8187:                             }
 8188:                         }
 8189:                         if ($changed{$role}{'on'}) {
 8190:                             if ($newsettings{$role}{'on'}) {
 8191:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8192:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8193:                             } else {
 8194:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8195:                             }
 8196:                         }
 8197:                     }
 8198:                     $r->print('</ul></li>');
 8199:                 }
 8200:                 $r->print('</ul>');
 8201:             }
 8202:         } else {
 8203:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8204:         }
 8205:     }
 8206:     return;
 8207: }
 8208: 
 8209: #-------------------------------------------------- functions for &phase_two
 8210: sub user_search_result {
 8211:     my ($context,$srch) = @_;
 8212:     my %allhomes;
 8213:     my %inst_matches;
 8214:     my %srch_results;
 8215:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8216:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8217:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8218:         $response = &mt('Invalid search.');
 8219:     }
 8220:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8221:         $response = &mt('Invalid search.');
 8222:     }
 8223:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8224:         $response = &mt('Invalid search.');
 8225:     }
 8226:     if ($srch->{'srchterm'} eq '') {
 8227:         $response = &mt('You must enter a search term.');
 8228:     }
 8229:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8230:         $response = &mt('Your search term must contain more than just spaces.');
 8231:     }
 8232:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8233:         if (($srch->{'srchdomain'} eq '') || 
 8234: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8235:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8236:         }
 8237:     }
 8238:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8239:         ($srch->{'srchin'} eq 'alc')) {
 8240:         if ($srch->{'srchby'} eq 'uname') {
 8241:             my $unamecheck = $srch->{'srchterm'};
 8242:             if ($srch->{'srchtype'} eq 'contains') {
 8243:                 if ($unamecheck !~ /^\w/) {
 8244:                     $unamecheck = 'a'.$unamecheck; 
 8245:                 }
 8246:             }
 8247:             if ($unamecheck !~ /^$match_username$/) {
 8248:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8249:             }
 8250:         }
 8251:     }
 8252:     if ($response ne '') {
 8253:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8254:     }
 8255:     if ($srch->{'srchin'} eq 'instd') {
 8256:         my $instd_chk = &instdirectorysrch_check($srch);
 8257:         if ($instd_chk ne 'ok') {
 8258:             my $domd_chk = &domdirectorysrch_check($srch);
 8259:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8260:             if ($domd_chk eq 'ok') {
 8261:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 8262:             }
 8263:             $response .= '<br />';
 8264:         }
 8265:     } else {
 8266:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8267:             my $domd_chk = &domdirectorysrch_check($srch);
 8268:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8269:                 my $instd_chk = &instdirectorysrch_check($srch);
 8270:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8271:                 if ($instd_chk eq 'ok') {
 8272:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 8273:                 }
 8274:                 $response .= '<br />';
 8275:             }
 8276:         }
 8277:     }
 8278:     if ($response ne '') {
 8279:         return ($currstate,$response);
 8280:     }
 8281:     if ($srch->{'srchby'} eq 'uname') {
 8282:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8283:             if ($env{'form.forcenew'}) {
 8284:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8285:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8286:                     if ($uhome eq 'no_host') {
 8287:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8288:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8289:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8290:                     } else {
 8291:                         $currstate = 'modify';
 8292:                     }
 8293:                 } else {
 8294:                     $currstate = 'modify';
 8295:                 }
 8296:             } else {
 8297:                 if ($srch->{'srchin'} eq 'dom') {
 8298:                     if ($srch->{'srchtype'} eq 'exact') {
 8299:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8300:                         if ($uhome eq 'no_host') {
 8301:                             ($currstate,$response,$forcenewuser) =
 8302:                                 &build_search_response($context,$srch,%srch_results);
 8303:                         } else {
 8304:                             $currstate = 'modify';
 8305:                             if ($env{'form.action'} eq 'accesslogs') {
 8306:                                 $currstate = 'activity';
 8307:                             }
 8308:                             my $uname = $srch->{'srchterm'};
 8309:                             my $udom = $srch->{'srchdomain'};
 8310:                             $srch_results{$uname.':'.$udom} =
 8311:                                 { &Apache::lonnet::get('environment',
 8312:                                                        ['firstname',
 8313:                                                         'lastname',
 8314:                                                         'permanentemail'],
 8315:                                                          $udom,$uname)
 8316:                                 };
 8317:                         }
 8318:                     } else {
 8319:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8320:                         ($currstate,$response,$forcenewuser) =
 8321:                             &build_search_response($context,$srch,%srch_results);
 8322:                     }
 8323:                 } else {
 8324:                     my $courseusers = &get_courseusers();
 8325:                     if ($srch->{'srchtype'} eq 'exact') {
 8326:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8327:                             $currstate = 'modify';
 8328:                         } else {
 8329:                             ($currstate,$response,$forcenewuser) =
 8330:                                 &build_search_response($context,$srch,%srch_results);
 8331:                         }
 8332:                     } else {
 8333:                         foreach my $user (keys(%$courseusers)) {
 8334:                             my ($cuname,$cudomain) = split(/:/,$user);
 8335:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8336:                                 my $matched = 0;
 8337:                                 if ($srch->{'srchtype'} eq 'begins') {
 8338:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8339:                                         $matched = 1;
 8340:                                     }
 8341:                                 } else {
 8342:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8343:                                         $matched = 1;
 8344:                                     }
 8345:                                 }
 8346:                                 if ($matched) {
 8347:                                     $srch_results{$user} = 
 8348: 					{&Apache::lonnet::get('environment',
 8349: 							     ['firstname',
 8350: 							      'lastname',
 8351: 							      'permanentemail'],
 8352: 							      $cudomain,$cuname)};
 8353:                                 }
 8354:                             }
 8355:                         }
 8356:                         ($currstate,$response,$forcenewuser) =
 8357:                             &build_search_response($context,$srch,%srch_results);
 8358:                     }
 8359:                 }
 8360:             }
 8361:         } elsif ($srch->{'srchin'} eq 'alc') {
 8362:             $currstate = 'query';
 8363:         } elsif ($srch->{'srchin'} eq 'instd') {
 8364:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8365:             if ($dirsrchres eq 'ok') {
 8366:                 ($currstate,$response,$forcenewuser) = 
 8367:                     &build_search_response($context,$srch,%srch_results);
 8368:             } else {
 8369:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8370:                 $response = '<span class="LC_warning">'.
 8371:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8372:                     '</span><br />'.
 8373:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8374:                     '<br />'; 
 8375:             }
 8376:         }
 8377:     } else {
 8378:         if ($srch->{'srchin'} eq 'dom') {
 8379:             %srch_results = &Apache::lonnet::usersearch($srch);
 8380:             ($currstate,$response,$forcenewuser) = 
 8381:                 &build_search_response($context,$srch,%srch_results); 
 8382:         } elsif ($srch->{'srchin'} eq 'crs') {
 8383:             my $courseusers = &get_courseusers(); 
 8384:             foreach my $user (keys(%$courseusers)) {
 8385:                 my ($uname,$udom) = split(/:/,$user);
 8386:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8387:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8388:                 if ($srch->{'srchby'} eq 'lastname') {
 8389:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8390:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8391:                         (($srch->{'srchtype'} eq 'begins') &&
 8392:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8393:                         (($srch->{'srchtype'} eq 'contains') &&
 8394:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8395:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8396:                                             lastname => $names{'lastname'},
 8397:                                             permanentemail => $emails{'permanentemail'},
 8398:                                            };
 8399:                     }
 8400:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8401:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8402:                     $srchlast =~ s/\s+$//;
 8403:                     $srchfirst =~ s/^\s+//;
 8404:                     if ($srch->{'srchtype'} eq 'exact') {
 8405:                         if (($names{'lastname'} eq $srchlast) &&
 8406:                             ($names{'firstname'} eq $srchfirst)) {
 8407:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8408:                                                 lastname => $names{'lastname'},
 8409:                                                 permanentemail => $emails{'permanentemail'},
 8410: 
 8411:                                            };
 8412:                         }
 8413:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8414:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8415:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8416:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8417:                                                 lastname => $names{'lastname'},
 8418:                                                 permanentemail => $emails{'permanentemail'},
 8419:                                                };
 8420:                         }
 8421:                     } else {
 8422:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8423:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8424:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8425:                                                 lastname => $names{'lastname'},
 8426:                                                 permanentemail => $emails{'permanentemail'},
 8427:                                                };
 8428:                         }
 8429:                     }
 8430:                 }
 8431:             }
 8432:             ($currstate,$response,$forcenewuser) = 
 8433:                 &build_search_response($context,$srch,%srch_results); 
 8434:         } elsif ($srch->{'srchin'} eq 'alc') {
 8435:             $currstate = 'query';
 8436:         } elsif ($srch->{'srchin'} eq 'instd') {
 8437:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8438:             if ($dirsrchres eq 'ok') {
 8439:                 ($currstate,$response,$forcenewuser) = 
 8440:                     &build_search_response($context,$srch,%srch_results);
 8441:             } else {
 8442:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8443:                 $response = '<span class="LC_warning">'.
 8444:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8445:                     '</span><br />'.
 8446:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8447:                     '<br />';
 8448:             }
 8449:         }
 8450:     }
 8451:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8452: }
 8453: 
 8454: sub domdirectorysrch_check {
 8455:     my ($srch) = @_;
 8456:     my $response;
 8457:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8458:                                              ['directorysrch'],$srch->{'srchdomain'});
 8459:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8460:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8461:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8462:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8463:         }
 8464:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8465:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8466:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8467:             }
 8468:         }
 8469:     }
 8470:     return 'ok';
 8471: }
 8472: 
 8473: sub instdirectorysrch_check {
 8474:     my ($srch) = @_;
 8475:     my $can_search = 0;
 8476:     my $response;
 8477:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8478:                                              ['directorysrch'],$srch->{'srchdomain'});
 8479:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8480:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8481:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8482:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8483:         }
 8484:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8485:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8486:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8487:             }
 8488:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8489:             if (!@usertypes) {
 8490:                 push(@usertypes,'default');
 8491:             }
 8492:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8493:                 foreach my $type (@usertypes) {
 8494:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8495:                         $can_search = 1;
 8496:                         last;
 8497:                     }
 8498:                 }
 8499:             }
 8500:             if (!$can_search) {
 8501:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8502:                 my @longtypes; 
 8503:                 foreach my $item (@usertypes) {
 8504:                     if (defined($insttypes->{$item})) { 
 8505:                         push (@longtypes,$insttypes->{$item});
 8506:                     } elsif ($item eq 'default') {
 8507:                         push (@longtypes,&mt('other')); 
 8508:                     }
 8509:                 }
 8510:                 my $insttype_str = join(', ',@longtypes); 
 8511:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8512:             }
 8513:         } else {
 8514:             $can_search = 1;
 8515:         }
 8516:     } else {
 8517:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8518:     }
 8519:     my %longtext = &Apache::lonlocal::texthash (
 8520:                        uname     => 'username',
 8521:                        lastfirst => 'last name, first name',
 8522:                        lastname  => 'last name',
 8523:                        contains  => 'contains',
 8524:                        exact     => 'as exact match to',
 8525:                        begins    => 'begins with',
 8526:                    );
 8527:     if ($can_search) {
 8528:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8529:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8530:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8531:             }
 8532:         } else {
 8533:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8534:         }
 8535:     }
 8536:     if ($can_search) {
 8537:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8538:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8539:                 return 'ok';
 8540:             } else {
 8541:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8542:             }
 8543:         } else {
 8544:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8545:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8546:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8547:                 return 'ok';
 8548:             } else {
 8549:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8550:             }
 8551:         }
 8552:     }
 8553: }
 8554: 
 8555: sub get_courseusers {
 8556:     my %advhash;
 8557:     my $classlist = &Apache::loncoursedata::get_classlist();
 8558:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8559:     foreach my $role (sort(keys(%coursepersonnel))) {
 8560:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8561: 	    if (!exists($classlist->{$user})) {
 8562: 		$classlist->{$user} = [];
 8563: 	    }
 8564:         }
 8565:     }
 8566:     return $classlist;
 8567: }
 8568: 
 8569: sub build_search_response {
 8570:     my ($context,$srch,%srch_results) = @_;
 8571:     my ($currstate,$response,$forcenewuser);
 8572:     my %names = (
 8573:           'uname'     => 'username',
 8574:           'lastname'  => 'last name',
 8575:           'lastfirst' => 'last name, first name',
 8576:           'crs'       => 'this course',
 8577:           'dom'       => 'LON-CAPA domain',
 8578:           'instd'     => 'the institutional directory for domain',
 8579:     );
 8580: 
 8581:     my %single = (
 8582:                    begins   => 'A match',
 8583:                    contains => 'A match',
 8584:                    exact    => 'An exact match',
 8585:                  );
 8586:     my %nomatch = (
 8587:                    begins   => 'No match',
 8588:                    contains => 'No match',
 8589:                    exact    => 'No exact match',
 8590:                   );
 8591:     if (keys(%srch_results) > 1) {
 8592:         $currstate = 'select';
 8593:     } else {
 8594:         if (keys(%srch_results) == 1) {
 8595:             if ($env{'form.action'} eq 'accesslogs') {
 8596:                 $currstate = 'activity';
 8597:             } else {
 8598:                 $currstate = 'modify';
 8599:             }
 8600:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8601:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8602:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8603:             }
 8604:         } else { # Search has nothing found. Prepare message to user.
 8605:             $response = '<span class="LC_warning">';
 8606:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8607:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8608:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8609:                                  &display_domain_info($srch->{'srchdomain'}));
 8610:             } else {
 8611:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8612:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8613:             }
 8614:             $response .= '</span>';
 8615: 
 8616:             if ($srch->{'srchin'} ne 'alc') {
 8617:                 $forcenewuser = 1;
 8618:                 my $cansrchinst = 0; 
 8619:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8620:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8621:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8622:                         if ($domconfig{'directorysrch'}{'available'}) {
 8623:                             $cansrchinst = 1;
 8624:                         } 
 8625:                     }
 8626:                 }
 8627:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8628:                      ($srch->{'srchby'} eq 'lastname')) &&
 8629:                     ($srch->{'srchin'} eq 'dom')) {
 8630:                     if ($cansrchinst) {
 8631:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8632:                     }
 8633:                 }
 8634:                 if ($srch->{'srchin'} eq 'crs') {
 8635:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8636:                 }
 8637:             }
 8638:             my $createdom = $env{'request.role.domain'};
 8639:             if ($context eq 'requestcrs') {
 8640:                 if ($env{'form.coursedom'} ne '') {
 8641:                     $createdom = $env{'form.coursedom'};
 8642:                 }
 8643:             }
 8644:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8645:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8646:                 my $cancreate =
 8647:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8648:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8649:                 if ($cancreate) {
 8650:                     my $showdom = &display_domain_info($createdom); 
 8651:                     $response .= '<br /><br />'
 8652:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8653:                                 .'<br />';
 8654:                     if ($context eq 'requestcrs') {
 8655:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8656:                     } else {
 8657:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8658:                     }
 8659:                     $response .='<ul><li>'
 8660:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8661:                                 .'</li><li>'
 8662:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8663:                                 .'</li><li>'
 8664:                                 .&mt('Provide the proposed username')
 8665:                                 .'</li><li>'
 8666:                                 .&mt("Click 'Search'")
 8667:                                 .'</li></ul><br />';
 8668:                 } else {
 8669:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8670:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8671:                         $response .= '<br /><br />';
 8672:                         if ($context eq 'requestcrs') {
 8673:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8674:                         } else {
 8675:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8676:                         }
 8677:                         $response .= '<br />'
 8678:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8679:                                         ,' <a'.$helplink.'>'
 8680:                                         ,'</a>')
 8681:                                      .'<br />';
 8682:                     }
 8683:                 }
 8684:             }
 8685:         }
 8686:     }
 8687:     return ($currstate,$response,$forcenewuser);
 8688: }
 8689: 
 8690: sub display_domain_info {
 8691:     my ($dom) = @_;
 8692:     my $output = $dom;
 8693:     if ($dom ne '') { 
 8694:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8695:         if ($domdesc ne '') {
 8696:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8697:         }
 8698:     }
 8699:     return $output;
 8700: }
 8701: 
 8702: sub crumb_utilities {
 8703:     my %elements = (
 8704:        crtuser => {
 8705:            srchterm => 'text',
 8706:            srchin => 'selectbox',
 8707:            srchby => 'selectbox',
 8708:            srchtype => 'selectbox',
 8709:            srchdomain => 'selectbox',
 8710:        },
 8711:        crtusername => {
 8712:            srchterm => 'text',
 8713:            srchdomain => 'selectbox',
 8714:        },
 8715:        docustom => {
 8716:            rolename => 'selectbox',
 8717:            newrolename => 'textbox',
 8718:        },
 8719:        studentform => {
 8720:            srchterm => 'text',
 8721:            srchin => 'selectbox',
 8722:            srchby => 'selectbox',
 8723:            srchtype => 'selectbox',
 8724:            srchdomain => 'selectbox',
 8725:        },
 8726:     );
 8727: 
 8728:     my $jsback .= qq|
 8729: function backPage(formname,prevphase,prevstate) {
 8730:     if (typeof prevphase == 'undefined') {
 8731:         formname.phase.value = '';
 8732:     }
 8733:     else {  
 8734:         formname.phase.value = prevphase;
 8735:     }
 8736:     if (typeof prevstate == 'undefined') {
 8737:         formname.currstate.value = '';
 8738:     }
 8739:     else {
 8740:         formname.currstate.value = prevstate;
 8741:     }
 8742:     formname.submit();
 8743: }
 8744: |;
 8745:     return ($jsback,\%elements);
 8746: }
 8747: 
 8748: sub course_level_table {
 8749:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 8750:     return unless (ref($inccourses) eq 'HASH');
 8751:     my $table = '';
 8752: # Custom Roles?
 8753: 
 8754:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8755:     my %lt=&Apache::lonlocal::texthash(
 8756:             'exs'  => "Existing sections",
 8757:             'new'  => "Define new section",
 8758:             'ssd'  => "Set Start Date",
 8759:             'sed'  => "Set End Date",
 8760:             'crl'  => "Course Level",
 8761:             'act'  => "Activate",
 8762:             'rol'  => "Role",
 8763:             'ext'  => "Extent",
 8764:             'grs'  => "Section",
 8765:             'crd'  => "Credits",
 8766:             'sta'  => "Start",
 8767:             'end'  => "End"
 8768:     );
 8769: 
 8770:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 8771: 	my $thiscourse=$protectedcourse;
 8772: 	$thiscourse=~s:_:/:g;
 8773: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 8774:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 8775: 	my $area=$coursedata{'description'};
 8776:         my $crstype=$coursedata{'type'};
 8777: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 8778: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 8779:         my %sections_count;
 8780:         if (defined($env{'request.course.id'})) {
 8781:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 8782:                 %sections_count = 
 8783: 		    &Apache::loncommon::get_sections($domain,$cnum);
 8784:             }
 8785:         }
 8786:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 8787: 	foreach my $role (@roles) {
 8788:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8789: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 8790:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 8791:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8792:                                             $plrole,\%sections_count,\%lt,
 8793:                                             $showcredits,$defaultcredits,$crstype);
 8794:             } elsif ($env{'request.course.sec'} ne '') {
 8795:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 8796:                                              $env{'request.course.sec'})) {
 8797:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8798:                                                 $plrole,\%sections_count,\%lt,
 8799:                                                 $showcredits,$defaultcredits,$crstype);
 8800:                 }
 8801:             }
 8802:         }
 8803:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 8804:             foreach my $cust (sort(keys(%customroles))) {
 8805:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 8806:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 8807:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 8808:                                             $cust,\%sections_count,\%lt,
 8809:                                             $showcredits,$defaultcredits,$crstype);
 8810:             }
 8811: 	}
 8812:     }
 8813:     return '' if ($table eq ''); # return nothing if there is nothing 
 8814:                                  # in the table
 8815:     my $result;
 8816:     if (!$env{'request.course.id'}) {
 8817:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 8818:     }
 8819:     $result .= 
 8820: &Apache::loncommon::start_data_table().
 8821: &Apache::loncommon::start_data_table_header_row().
 8822: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8823: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 8824:     if ($showcredits) {
 8825:         $result .= $lt{'crd'}.'</th>';
 8826:     }
 8827:     $result .=
 8828: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 8829: '<th>'.$lt{'end'}.'</th>'.
 8830: &Apache::loncommon::end_data_table_header_row().
 8831: $table.
 8832: &Apache::loncommon::end_data_table();
 8833:     return $result;
 8834: }
 8835: 
 8836: sub course_level_row {
 8837:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 8838:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 8839:     my $creditem;
 8840:     my $row = &Apache::loncommon::start_data_table_row().
 8841:               ' <td><input type="checkbox" name="act_'.
 8842:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 8843:               ' <td>'.$plrole.'</td>'."\n".
 8844:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 8845:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 8846:         $row .= 
 8847:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 8848:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 8849:     } else {
 8850:         $row .= '<td>&nbsp;</td>';
 8851:     }
 8852:     if (($role eq 'cc') || ($role eq 'co')) {
 8853:         $row .= '<td>&nbsp;</td>';
 8854:     } elsif ($env{'request.course.sec'} ne '') {
 8855:         $row .= ' <td><input type="hidden" value="'.
 8856:                 $env{'request.course.sec'}.'" '.
 8857:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 8858:                 $env{'request.course.sec'}.'</td>';
 8859:     } else {
 8860:         if (ref($sections_count) eq 'HASH') {
 8861:             my $currsec = 
 8862:                 &Apache::lonuserutils::course_sections($sections_count,
 8863:                                                        $protectedcourse.'_'.$role);
 8864:             $row .= '<td><table class="LC_createuser">'."\n".
 8865:                     '<tr class="LC_section_row">'."\n".
 8866:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 8867:                        $currsec.'</td>'."\n".
 8868:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 8869:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 8870:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 8871:                      '" value="" />'.
 8872:                      '<input type="hidden" '.
 8873:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 8874:                      '</tr></table></td>'."\n";
 8875:         } else {
 8876:             $row .= '<td><input type="text" size="10" '.
 8877:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 8878:         }
 8879:     }
 8880:     $row .= <<ENDTIMEENTRY;
 8881: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 8882: <a href=
 8883: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 8884: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 8885: <a href=
 8886: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 8887: ENDTIMEENTRY
 8888:     $row .= &Apache::loncommon::end_data_table_row();
 8889:     return $row;
 8890: }
 8891: 
 8892: sub course_level_dc {
 8893:     my ($dcdom,$showcredits) = @_;
 8894:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 8895:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 8896:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 8897:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 8898:                       '<input type="hidden" name="dccourse" value="" />';
 8899:     my $courseform=&Apache::loncommon::selectcourse_link
 8900:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 8901:     my $credit_elem;
 8902:     if ($showcredits) {
 8903:         $credit_elem = 'credits';
 8904:     }
 8905:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 8906:     my %lt=&Apache::lonlocal::texthash(
 8907:                     'rol'  => "Role",
 8908:                     'grs'  => "Section",
 8909:                     'exs'  => "Existing sections",
 8910:                     'new'  => "Define new section", 
 8911:                     'sta'  => "Start",
 8912:                     'end'  => "End",
 8913:                     'ssd'  => "Set Start Date",
 8914:                     'sed'  => "Set End Date",
 8915:                     'scc'  => "Course/Community",
 8916:                     'crd'  => "Credits",
 8917:                   );
 8918:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 8919:                  &Apache::loncommon::start_data_table().
 8920:                  &Apache::loncommon::start_data_table_header_row().
 8921:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 8922:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 8923:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 8924:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 8925:                  &Apache::loncommon::end_data_table_header_row();
 8926:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 8927:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 8928:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 8929:                      '<td valign="top"><br /><select name="role">'."\n";
 8930:     foreach my $role (@roles) {
 8931:         my $plrole=&Apache::lonnet::plaintext($role);
 8932:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 8933:     }
 8934:     if ( keys(%customroles) > 0) {
 8935:         foreach my $cust (sort(keys(%customroles))) {
 8936:             my $custrole='cr_cr_'.$env{'user.domain'}.
 8937:                     '_'.$env{'user.name'}.'_'.$cust;
 8938:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 8939:         }
 8940:     }
 8941:     $otheritems .= '</select></td><td>'.
 8942:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 8943:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 8944:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 8945:                      '<td>&nbsp;&nbsp;</td>'.
 8946:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 8947:                      '<input type="text" name="newsec" value="" />'.
 8948:                      '<input type="hidden" name="section" value="" />'.
 8949:                      '<input type="hidden" name="groups" value="" />'.
 8950:                      '<input type="hidden" name="crstype" value="" /></td>'.
 8951:                      '</tr></table></td>'."\n";
 8952:     if ($showcredits) {
 8953:         $otheritems .= '<td><br />'."\n".
 8954:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 8955:     }
 8956:     $otheritems .= <<ENDTIMEENTRY;
 8957: <td><br /><input type="hidden" name="start" value='' />
 8958: <a href=
 8959: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 8960: <td><br /><input type="hidden" name="end" value='' />
 8961: <a href=
 8962: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 8963: ENDTIMEENTRY
 8964:     $otheritems .= &Apache::loncommon::end_data_table_row().
 8965:                    &Apache::loncommon::end_data_table()."\n";
 8966:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 8967: }
 8968: 
 8969: sub update_selfenroll_config {
 8970:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 8971:     return unless (ref($currsettings) eq 'HASH');
 8972:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 8973:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8974:     my (%changes,%warning);
 8975:     my $curr_types;
 8976:     my %noedit;
 8977:     unless ($context eq 'domain') {
 8978:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 8979:     }
 8980:     if (ref($row) eq 'ARRAY') {
 8981:         foreach my $item (@{$row}) {
 8982:             next if ($noedit{$item});
 8983:             if ($item eq 'enroll_dates') {
 8984:                 my (%currenrolldate,%newenrolldate);
 8985:                 foreach my $type ('start','end') {
 8986:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 8987:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 8988:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 8989:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 8990:                     }
 8991:                 }
 8992:             } elsif ($item eq 'access_dates') {
 8993:                 my (%currdate,%newdate);
 8994:                 foreach my $type ('start','end') {
 8995:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 8996:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 8997:                     if ($newdate{$type} ne $currdate{$type}) {
 8998:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 8999:                     }
 9000:                 }
 9001:             } elsif ($item eq 'types') {
 9002:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9003:                 if ($env{'form.selfenroll_all'}) {
 9004:                     if ($curr_types ne '*') {
 9005:                         $changes{'internal.selfenroll_types'} = '*';
 9006:                     } else {
 9007:                         next;
 9008:                     }
 9009:                 } else {
 9010:                     my %currdoms;
 9011:                     my @entries = split(/;/,$curr_types);
 9012:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9013:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9014:                     my $newnum = 0;
 9015:                     my @latesttypes;
 9016:                     foreach my $num (@activations) {
 9017:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9018:                         if (@types > 0) {
 9019:                             @types = sort(@types);
 9020:                             my $typestr = join(',',@types);
 9021:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9022:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9023:                             $currdoms{$typedom} = 1;
 9024:                             $newnum ++;
 9025:                         }
 9026:                     }
 9027:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9028:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9029:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9030:                             if (@types > 0) {
 9031:                                 @types = sort(@types);
 9032:                                 my $typestr = join(',',@types);
 9033:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9034:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9035:                                 $currdoms{$typedom} = 1;
 9036:                                 $newnum ++;
 9037:                             }
 9038:                         }
 9039:                     }
 9040:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9041:                         my $typedom = $env{'form.selfenroll_newdom'};
 9042:                         if ((!defined($currdoms{$typedom})) && 
 9043:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9044:                             my $typestr;
 9045:                             my ($othertitle,$usertypes,$types) = 
 9046:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9047:                             my $othervalue = 'any';
 9048:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9049:                                 if (@{$types} > 0) {
 9050:                                     my @esc_types = map { &escape($_); } @{$types};
 9051:                                     $othervalue = 'other';
 9052:                                     $typestr = join(',',(@esc_types,$othervalue));
 9053:                                 }
 9054:                                 $typestr = $othervalue;
 9055:                             } else {
 9056:                                 $typestr = $othervalue;
 9057:                             } 
 9058:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9059:                             $newnum ++ ;
 9060:                         }
 9061:                     }
 9062:                     my $selfenroll_types = join(';',@latesttypes);
 9063:                     if ($selfenroll_types ne $curr_types) {
 9064:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9065:                     }
 9066:                 }
 9067:             } elsif ($item eq 'limit') {
 9068:                 my $newlimit = $env{'form.selfenroll_limit'};
 9069:                 my $newcap = $env{'form.selfenroll_cap'};
 9070:                 $newcap =~s/\s+//g;
 9071:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9072:                 $currlimit = 'none' if ($currlimit eq '');
 9073:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9074:                 if ($newlimit ne $currlimit) {
 9075:                     if ($newlimit ne 'none') {
 9076:                         if ($newcap =~ /^\d+$/) {
 9077:                             if ($newcap ne $currcap) {
 9078:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9079:                             }
 9080:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9081:                         } else {
 9082:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9083:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9084:                         }
 9085:                     } elsif ($currcap ne '') {
 9086:                         $changes{'internal.selfenroll_cap'} = '';
 9087:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9088:                     }
 9089:                 } elsif ($currlimit ne 'none') {
 9090:                     if ($newcap =~ /^\d+$/) {
 9091:                         if ($newcap ne $currcap) {
 9092:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9093:                         }
 9094:                     } else {
 9095:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9096:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9097:                     }
 9098:                 }
 9099:             } elsif ($item eq 'approval') {
 9100:                 my (@currnotified,@newnotified);
 9101:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9102:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9103:                 if ($currnotifylist ne '') {
 9104:                     @currnotified = split(/,/,$currnotifylist);
 9105:                     @currnotified = sort(@currnotified);
 9106:                 }
 9107:                 my $newapproval = $env{'form.selfenroll_approval'};
 9108:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9109:                 @newnotified = sort(@newnotified);
 9110:                 if ($newapproval ne $currapproval) {
 9111:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9112:                     if (!$newapproval) {
 9113:                         if ($currnotifylist ne '') {
 9114:                             $changes{'internal.selfenroll_notifylist'} = '';
 9115:                         }
 9116:                     } else {
 9117:                         my @differences =  
 9118:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9119:                         if (@differences > 0) {
 9120:                             if (@newnotified > 0) {
 9121:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9122:                             } else {
 9123:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9124:                             }
 9125:                         }
 9126:                     }
 9127:                 } else {
 9128:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9129:                     if (@differences > 0) {
 9130:                         if (@newnotified > 0) {
 9131:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9132:                         } else {
 9133:                             $changes{'internal.selfenroll_notifylist'} = '';
 9134:                         }
 9135:                     }
 9136:                 }
 9137:             } else {
 9138:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9139:                 my $newval = $env{'form.selfenroll_'.$item};
 9140:                 if ($item eq 'section') {
 9141:                     $newval = $env{'form.sections'};
 9142:                     if (defined($curr_groups{$newval})) {
 9143:                         $newval = $curr_val;
 9144:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9145:                                           &mt('Group names and section names must be distinct');
 9146:                     } elsif ($newval eq 'all') {
 9147:                         $newval = $curr_val;
 9148:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9149:                     }
 9150:                     if ($newval eq '') {
 9151:                         $newval = 'none';
 9152:                     }
 9153:                 }
 9154:                 if ($newval ne $curr_val) {
 9155:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9156:                 }
 9157:             }
 9158:         }
 9159:         if (keys(%warning) > 0) {
 9160:             foreach my $item (@{$row}) {
 9161:                 if (exists($warning{$item})) {
 9162:                     $r->print($warning{$item}.'<br />');
 9163:                 }
 9164:             } 
 9165:         }
 9166:         if (keys(%changes) > 0) {
 9167:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9168:             if ($putresult eq 'ok') {
 9169:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9170:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9171:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9172:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9173:                                                                 $cnum,undef,undef,'Course');
 9174:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9175:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9176:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9177:                             if (exists($changes{'internal.'.$item})) {
 9178:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9179:                             }
 9180:                         }
 9181:                         my $crsputresult =
 9182:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9183:                                                          $chome,'notime');
 9184:                     }
 9185:                 }
 9186:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9187:                 foreach my $item (@{$row}) {
 9188:                     my $title = $item;
 9189:                     if (ref($lt) eq 'HASH') {
 9190:                         $title = $lt->{$item};
 9191:                     }
 9192:                     if ($item eq 'enroll_dates') {
 9193:                         foreach my $type ('start','end') {
 9194:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9195:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9196:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9197:                                           $title,$type,$newdate).'</li>');
 9198:                             }
 9199:                         }
 9200:                     } elsif ($item eq 'access_dates') {
 9201:                         foreach my $type ('start','end') {
 9202:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9203:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9204:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9205:                                           $title,$type,$newdate).'</li>');
 9206:                             }
 9207:                         }
 9208:                     } elsif ($item eq 'limit') {
 9209:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9210:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9211:                             my ($newval,$newcap);
 9212:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9213:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9214:                             } else {
 9215:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9216:                             }
 9217:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9218:                                 $newval = &mt('No limit');
 9219:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9220:                                      'allstudents') {
 9221:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9222:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9223:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9224:                             } else {
 9225:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9226:                                 if ($currlimit eq 'allstudents') {
 9227:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9228:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9229:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9230:                                 }
 9231:                             }
 9232:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9233:                         }
 9234:                     } elsif ($item eq 'approval') {
 9235:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9236:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9237:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9238:                             my ($newval,$newnotify);
 9239:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9240:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9241:                             } else {   
 9242:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9243:                             }
 9244:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9245:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9246:                                     $changes{'internal.selfenroll_approval'} = '0';
 9247:                                 }
 9248:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9249:                             } else {
 9250:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9251:                                 if ($currapproval !~ /^[012]$/) {
 9252:                                     $currapproval = 0;
 9253:                                 }
 9254:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9255:                             }
 9256:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9257:                             if ($newnotify) {
 9258:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9259:                             } else {
 9260:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9261:                             }
 9262:                             $r->print('</li>'."\n");
 9263:                         }
 9264:                     } else {
 9265:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9266:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9267:                             if ($item eq 'types') {
 9268:                                 if ($newval eq '') {
 9269:                                     $newval = &mt('None');
 9270:                                 } elsif ($newval eq '*') {
 9271:                                     $newval = &mt('Any user in any domain');
 9272:                                 }
 9273:                             } elsif ($item eq 'registered') {
 9274:                                 if ($newval eq '1') {
 9275:                                     $newval = &mt('Yes');
 9276:                                 } elsif ($newval eq '0') {
 9277:                                     $newval = &mt('No');
 9278:                                 }
 9279:                             }
 9280:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9281:                         }
 9282:                     }
 9283:                 }
 9284:                 $r->print('</ul>');
 9285:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9286:                     my %newenvhash;
 9287:                     foreach my $key (keys(%changes)) {
 9288:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9289:                     }
 9290:                     &Apache::lonnet::appenv(\%newenvhash);
 9291:                 }
 9292:             } else {
 9293:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9294:                           &mt('The error was: [_1].',$putresult));
 9295:             }
 9296:         } else {
 9297:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9298:         }
 9299:     } else {
 9300:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9301:     }
 9302:     my $visactions = &cat_visibility();
 9303:     my ($cathash,%cattype);
 9304:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9305:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9306:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9307:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9308:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9309:     } else {
 9310:         $cathash = {};
 9311:         $cattype{'auth'} = 'std';
 9312:         $cattype{'unauth'} = 'std';
 9313:     }
 9314:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9315:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9316:                   '<br />'.
 9317:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9318:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9319:                   '</ul>');
 9320:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9321:         if ($currsettings->{'uniquecode'}) {
 9322:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9323:         } else {
 9324:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9325:                   '<br />'.
 9326:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9327:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9328:                   '</ul><br />');
 9329:         }
 9330:     } else {
 9331:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9332:         if (ref($visactions) eq 'HASH') {
 9333:             if (!$visible) {
 9334:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9335:                           '<br />');
 9336:                 if (ref($vismsgs) eq 'ARRAY') {
 9337:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9338:                     foreach my $item (@{$vismsgs}) {
 9339:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9340:                     }
 9341:                     $r->print('</ul>');
 9342:                 }
 9343:                 $r->print($cansetvis);
 9344:             }
 9345:         }
 9346:     } 
 9347:     return;
 9348: }
 9349: 
 9350: #---------------------------------------------- end functions for &phase_two
 9351: 
 9352: #--------------------------------- functions for &phase_two and &phase_three
 9353: 
 9354: #--------------------------end of functions for &phase_two and &phase_three
 9355: 
 9356: 1;
 9357: __END__
 9358: 
 9359: 

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