File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.406.2.20.2.5: download - view: text, annotated - select for diffs
Thu Feb 29 21:43:33 2024 UTC (4 months ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.406.2.20: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.470 (part), 1.474, 1.475, 1.476 and part of 1.456
  (omitted in 1.406.2.20 backport).

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.406.2.20.2.5 2024/02/29 21:43:33 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: use HTML::Entities;
   75: 
   76: my $loginscript; # piece of javascript used in two separate instances
   77: my $authformnop;
   78: my $authformkrb;
   79: my $authformint;
   80: my $authformfsys;
   81: my $authformloc;
   82: 
   83: sub initialize_authen_forms {
   84:     my ($dom,$formname,$curr_authtype,$mode,$readonly) = @_;
   85:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   86:     my %param = ( formname => $formname,
   87:                   kerb_def_dom => $krbdefdom,
   88:                   kerb_def_auth => $krbdef,
   89:                   domain => $dom,
   90:                 );
   91:     my %abv_auth = &auth_abbrev();
   92:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
   93:         my $long_auth = $1;
   94:         my $curr_autharg = $2;
   95:         my %abv_auth = &auth_abbrev();
   96:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   97:         if ($long_auth =~ /^krb(4|5)$/) {
   98:             $param{'curr_kerb_ver'} = $1;
   99:             $param{'curr_autharg'} = $curr_autharg;
  100:         }
  101:         if ($mode eq 'modifyuser') {
  102:             $param{'mode'} = $mode;
  103:         }
  104:     }
  105:     if ($readonly) {
  106:         $param{'readonly'} = 1;
  107:     }
  108:     $loginscript  = &Apache::loncommon::authform_header(%param);
  109:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  110:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  111:     $authformint  = &Apache::loncommon::authform_internal(%param);
  112:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  113:     $authformloc  = &Apache::loncommon::authform_local(%param);
  114: }
  115: 
  116: sub auth_abbrev {
  117:     my %abv_auth = (
  118:                      krb5      => 'krb',
  119:                      krb4      => 'krb',
  120:                      internal  => 'int',
  121:                      localauth => 'loc',
  122:                      unix      => 'fsys',
  123:                    );
  124:     return %abv_auth;
  125: }
  126: 
  127: # ====================================================
  128: 
  129: sub user_quotas {
  130:     my ($ccuname,$ccdomain,$name) = @_;
  131:     my %lt = &Apache::lonlocal::texthash(
  132:                    'cust'      => "Custom quota",
  133:                    'chqu'      => "Change quota",
  134:     );
  135:     my ($output,$longinsttype);
  136:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  137:     my %titles = &Apache::lonlocal::texthash (
  138:                     portfolio => "Disk space allocated to user's portfolio files",
  139:                     author    => "Disk space allocated to user's Authoring Space",
  140:                  );
  141:     my ($currquota,$quotatype,$inststatus,$defquota) =
  142:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  143:     if ($longinsttype eq '') { 
  144:         if ($inststatus ne '') {
  145:             if ($usertypes->{$inststatus} ne '') {
  146:                 $longinsttype = $usertypes->{$inststatus};
  147:             }
  148:         }
  149:     }
  150:     my ($showquota,$custom_on,$custom_off,$defaultinfo,$colspan);
  151:     $custom_on = ' ';
  152:     $custom_off = ' checked="checked" ';
  153:     $colspan = ' colspan="2"';
  154:     if ($quotatype eq 'custom') {
  155:         $custom_on = $custom_off;
  156:         $custom_off = ' ';
  157:         $showquota = $currquota;
  158:         if ($longinsttype eq '') {
  159:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
  160:                               .' MB.',$defquota);
  161:         } else {
  162:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
  163:                                " MB,[_2]as determined by the user's institutional".
  164:                                " affiliation ([_3]).",$defquota,'<br />',$longinsttype);
  165:         }
  166:     } else {
  167:         if ($longinsttype eq '') {
  168:             $defaultinfo = &mt('For this user, the default quota is [_1]'
  169:                               .' MB.',$defquota);
  170:         } else {
  171:             $defaultinfo = &mt("For this user, the default quota of [_1]".
  172:                                " MB,[_2]is determined by the user's institutional".
  173:                                " affiliation ([_3]).",$defquota,'<br />',$longinsttype);
  174:         }
  175:     }
  176: 
  177:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  178:         $output .= '<tr class="LC_info_row">'."\n".
  179:                    '    <td'.$colspan.'>'.$titles{$name}.'</td>'."\n".
  180:                    '  </tr>'."\n".
  181:                    &Apache::loncommon::start_data_table_row()."\n".
  182:                    '  <td'.$colspan.'><span class="LC_nobreak">'.
  183:                    &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  184:                    $defaultinfo.'</td>'."\n".
  185:                    &Apache::loncommon::end_data_table_row()."\n".
  186:                    &Apache::loncommon::start_data_table_row()."\n".
  187:                    '<td'.$colspan.'><span class="LC_nobreak">'.$lt{'chqu'}.
  188:                    ': <label>'.
  189:                    '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  190:                    'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  191:                    ' /><span class="LC_nobreak">'.
  192:                    &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  193:                    '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  194:                    'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  195:                    ' />'.$lt{'cust'}.':</label>&nbsp;'.
  196:                    '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  197:                    'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  198:                    ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  199:                    &Apache::loncommon::end_data_table_row()."\n";
  200:     }
  201:     return $output;
  202: }
  203: 
  204: sub user_quota_js {
  205:     return  <<"END_SCRIPT";
  206: <script type="text/javascript">
  207: // <![CDATA[
  208: function quota_changes(caller,context) {
  209:     var customoff = document.getElementById('custom_'+context+'quota_off');
  210:     var customon = document.getElementById('custom_'+context+'quota_on');
  211:     var number = document.getElementById(context+'quota');
  212:     if (caller == "custom") {
  213:         if (customoff) {
  214:             if (customoff.checked) {
  215:                 number.value = "";
  216:             }
  217:         }
  218:     }
  219:     if (caller == "quota") {
  220:         if (customon) {
  221:             customon.checked = true;
  222:         }
  223:     }
  224:     return;
  225: }
  226: // ]]>
  227: </script>
  228: END_SCRIPT
  229: 
  230: }
  231: 
  232: sub set_custom_js {
  233:     return  <<"END_SCRIPT";
  234: 
  235: <script type="text/javascript">
  236: // <![CDATA[
  237: function toggleCustom(form,item,name) {
  238:     if (document.getElementById(item)) {
  239:         var divid = document.getElementById(item);
  240:         var radioname = form.elements[name];
  241:         if (radioname) {
  242:             if (radioname.length > 0) {
  243:                 var setvis;
  244:                 var RegExp = /^customtext_(aboutme|blog|portfolio|timezone|webdav)\$/;
  245:                 for (var i=0; i<radioname.length; i++) {
  246:                     if (radioname[i].checked == true) {
  247:                         if (radioname[i].value == 1) {
  248:                             if (RegExp.test(item)) {
  249:                                 divid.style.display = 'inline';
  250:                             } else {
  251:                                 divid.style.display = 'block';
  252:                             }
  253:                             setvis = 1;
  254:                         }
  255:                         break;
  256:                     }
  257:                 }
  258:                 if (!setvis) {
  259:                     divid.style.display = 'none';
  260:                 }
  261:             }
  262:         }
  263:     }
  264:     return;
  265: }
  266: // ]]>
  267: </script>
  268: 
  269: END_SCRIPT
  270: 
  271: }
  272: 
  273: sub build_tools_display {
  274:     my ($ccuname,$ccdomain,$context) = @_;
  275:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  276:         $colspan,$isadv,%domconfig,@defaulteditors,@customeditors);
  277:     my %lt = &Apache::lonlocal::texthash (
  278:                    'blog'       => "Personal User Blog",
  279:                    'aboutme'    => "Personal Information Page",
  280:                    'webdav'     => "WebDAV access to Authoring Spaces (https)",
  281:                    'editors'    => "Available Editors",
  282:                    'portfolio'  => "Personal User Portfolio",
  283:                    'timezone'   => "Can set Time Zone",
  284:                    'avai'       => "Available",
  285:                    'cusa'       => "availability",
  286:                    'chse'       => "Change setting",
  287:                    'usde'       => "Use default",
  288:                    'uscu'       => "Use custom",
  289:                    'official'   => 'Can request creation of official courses',
  290:                    'unofficial' => 'Can request creation of unofficial courses',
  291:                    'community'  => 'Can request creation of communities',
  292:                    'textbook'   => 'Can request creation of textbook courses',
  293:                    'requestauthor'  => 'Can request author space',
  294:                    'edit'       => 'Standard editor (Edit)',
  295:                    'xml'        => 'Text editor (EditXML)',
  296:                    'daxe'       => 'Daxe editor (Daxe)',
  297:     );
  298:     $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  299:     if ($context eq 'requestcourses') {
  300:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  301:                       'requestcourses.official','requestcourses.unofficial',
  302:                       'requestcourses.community','requestcourses.textbook');
  303:         @usertools = ('official','unofficial','community','textbook');
  304:         @options =('norequest','approval','autolimit','validate');
  305:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  306:         %reqtitles = &courserequest_titles();
  307:         %reqdisplay = &courserequest_display();
  308:         %domconfig =
  309:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  310:     } elsif ($context eq 'requestauthor') {
  311:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'requestauthor');
  312:         @usertools = ('requestauthor');
  313:         @options =('norequest','approval','automatic');
  314:         %reqtitles = &requestauthor_titles();
  315:         %reqdisplay = &requestauthor_display();
  316:         %domconfig =
  317:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  318:     } elsif ($context eq 'authordefaults') {
  319:         %domconfig =
  320:             &Apache::lonnet::get_dom('configuration',['quotas','authordefaults'],$ccdomain);
  321:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'tools.webdav',
  322:                                                     'authoreditors');
  323:         @usertools = ('webdav','editors');
  324:         $colspan = ' colspan="2"';
  325:     } else {
  326:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  327:                           'tools.aboutme','tools.portfolio','tools.blog',
  328:                           'tools.timezone');
  329:         @usertools = ('aboutme','blog','portfolio','timezone');
  330:         $colspan = ' colspan="2"';
  331:     }
  332:     foreach my $item (@usertools) {
  333:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  334:             $currdisp,$custdisp,$custradio,$onclick,$customsty,$editorsty);
  335:         $cust_off = 'checked="checked" ';
  336:         $tool_on = 'checked="checked" ';
  337:         unless (($context eq 'authordefaults') && ($item ne 'webdav')) {
  338:             $curr_access =
  339:                 &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  340:                                                   $context,\%userenv,'',
  341:                                                   {'is_adv' => $isadv});
  342:         }
  343:         if ($context eq 'requestauthor') {
  344:             if ($userenv{$context} ne '') {
  345:                 $cust_on = ' checked="checked" ';
  346:                 $cust_off = '';
  347:             }
  348:         } elsif ($context eq 'authordefaults') {
  349:             if ($item eq 'editors') {
  350:                 if ($userenv{'author'.$item} ne '') {
  351:                     $cust_on = ' checked="checked" ';
  352:                     $cust_off = '';
  353:                 }
  354:             } elsif ($item eq 'webdav') {
  355:                 if ($userenv{'tools.'.$item} ne '') {
  356:                     $cust_on = ' checked="checked" ';
  357:                     $cust_off = '';
  358:                 }
  359:             }
  360:         } elsif ($userenv{$context.'.'.$item} ne '') {
  361:             $cust_on = ' checked="checked" ';
  362:             $cust_off = '';
  363:         }
  364:         if ($context eq 'requestcourses') {
  365:             if ($userenv{$context.'.'.$item} eq '') {
  366:                 $custom_access = &mt('Currently from default setting.');
  367:                 $customsty = ' style="display:none;"';
  368:             } else {
  369:                 $custom_access = &mt('Currently from custom setting.');
  370:                 $customsty = ' style="display:block;"';
  371:             }
  372:         } elsif ($context eq 'requestauthor') {
  373:             if ($userenv{$context} eq '') {
  374:                 $custom_access = &mt('Currently from default setting.');
  375:                 $customsty = ' style="display:none;"';
  376:             } else {
  377:                 $custom_access = &mt('Currently from custom setting.');
  378:                 $customsty = ' style="display:block;"';
  379:             }
  380:         } elsif ($item eq 'editors') {
  381:             if ($userenv{'author'.$item} eq '') {
  382:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
  383:                     @defaulteditors = @{$domconfig{'authordefaults'}{'editors'}};
  384:                 } else {
  385:                     @defaulteditors = ('edit','xml');
  386:                 }
  387:                 $custom_access = &mt('Can use: [_1]',
  388:                                                join(', ', map { $lt{$_} } @defaulteditors));
  389:                 $editorsty = ' style="display:none;"';
  390:             } else {
  391:                 $custom_access = &mt('Currently from custom setting.');
  392:                 foreach my $editor (split(/,/,$userenv{'author'.$item})) {
  393:                     if ($editor =~ /^(edit|daxe|xml)$/) {
  394:                         push(@customeditors,$editor);
  395:                     }
  396:                 }
  397:                 if (@customeditors) {
  398:                     if (@customeditors > 1) {
  399:                         $custom_access .= '<br /><span>';
  400:                     } else {
  401:                         $custom_access .= ' <span class="LC_nobreak">';
  402:                     }
  403:                     $custom_access .= &mt('Can use: [_1]',
  404:                                           join(', ', map { $lt{$_} } @customeditors)).
  405:                                       '</span>';
  406:                 } else {
  407:                     $custom_access .= ' '.&mt('No available editors');
  408:                 }
  409:                 $editorsty = ' style="display:block;"';
  410:             }
  411:         } else {
  412:             my $current = $userenv{$context.'.'.$item};
  413:             if ($item eq 'webdav') {
  414:                 $current = $userenv{'tools.webdav'};
  415:             }
  416:             if ($current eq '') {
  417:                 $custom_access =
  418:                     &mt('Availability determined currently from default setting.');
  419:                 if (!$curr_access) {
  420:                     $tool_off = 'checked="checked" ';
  421:                     $tool_on = '';
  422:                 }
  423:                 $customsty = ' style="display:none;"';
  424:             } else {
  425:                 $custom_access =
  426:                     &mt('Availability determined currently from custom setting.');
  427:                 if ($current == 0) {
  428:                     $tool_off = 'checked="checked" ';
  429:                     $tool_on = '';
  430:                 }
  431:                 $customsty = ' style="display:inline;"';
  432:             }
  433:         }
  434:         $output .= '  <tr class="LC_info_row">'."\n".
  435:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  436:                    '  </tr>'."\n".
  437:                    &Apache::loncommon::start_data_table_row()."\n";
  438:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  439:             my ($curroption,$currlimit);
  440:             my $envkey = $context.'.'.$item;
  441:             if ($context eq 'requestauthor') {
  442:                 $envkey = $context;
  443:             }
  444:             if ($userenv{$envkey} ne '') {
  445:                 $curroption = $userenv{$envkey};
  446:             } else {
  447:                 my (@inststatuses);
  448:                 if ($context eq 'requestcourses') {
  449:                     $curroption =
  450:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  451:                                                                       $isadv,$ccdomain,$item,
  452:                                                                       \@inststatuses,\%domconfig);
  453:                 } else {
  454:                      $curroption = 
  455:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  456:                                                                        $isadv,$ccdomain,undef,
  457:                                                                        \@inststatuses,\%domconfig);
  458:                 }
  459:             }
  460:             if (!$curroption) {
  461:                 $curroption = 'norequest';
  462:             }
  463:             my $name = 'crsreq_'.$item;
  464:             if ($context eq 'requestauthor') {
  465:                 $name = $item;
  466:             }
  467:             $onclick = ' onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');"';
  468:             if ($curroption =~ /^autolimit=(\d*)$/) {
  469:                 $currlimit = $1;
  470:                 if ($currlimit eq '') {
  471:                     $currdisp = &mt('Yes, automatic creation');
  472:                 } else {
  473:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  474:                 }
  475:             } else {
  476:                 $currdisp = $reqdisplay{$curroption};
  477:             }
  478:             $custdisp = '<fieldset id="customtext_'.$item.'"'.$customsty.'>';
  479:             foreach my $option (@options) {
  480:                 my $val = $option;
  481:                 if ($option eq 'norequest') {
  482:                     $val = 0;
  483:                 }
  484:                 if ($option eq 'validate') {
  485:                     my $canvalidate = 0;
  486:                     if (ref($validations{$item}) eq 'HASH') {
  487:                         if ($validations{$item}{'_custom_'}) {
  488:                             $canvalidate = 1;
  489:                         }
  490:                     }
  491:                     next if (!$canvalidate);
  492:                 }
  493:                 my $checked = '';
  494:                 if ($option eq $curroption) {
  495:                     $checked = ' checked="checked"';
  496:                 } elsif ($option eq 'autolimit') {
  497:                     if ($curroption =~ /^autolimit/) {
  498:                         $checked = ' checked="checked"';
  499:                     }
  500:                 }
  501:                 if ($option eq 'autolimit') {
  502:                     $custdisp .= '<br />';
  503:                 }
  504:                 $custdisp .= '<span class="LC_nobreak"><label>'.
  505:                              '<input type="radio" name="'.$name.'" '.
  506:                              'value="'.$val.'"'.$checked.' />'.
  507:                              $reqtitles{$option}.'</label>&nbsp;';
  508:                 if ($option eq 'autolimit') {
  509:                     $custdisp .= '<input type="text" name="'.$name.
  510:                                  '_limit" size="1" '.
  511:                                  'value="'.$currlimit.'" />&nbsp;'.
  512:                                  $reqtitles{'unlimited'}.'</span>';
  513:                 } else {
  514:                     $custdisp .= '</span>';
  515:                 }
  516:                 $custdisp .= ' ';
  517:             }
  518:             $custdisp .= '</fieldset>';
  519:             $custradio = '<br />'.$custdisp;
  520:         } elsif ($item eq 'editors') {
  521:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  522:                        &Apache::loncommon::end_data_table_row()."\n";
  523:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  524:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  525:                           '<td'.$colspan.'><span class="LC_nobreak">'.
  526:                           $lt{'chse'}.': <label>'.
  527:                           '<input type="radio" name="custom'.$item.'" value="0" '.
  528:                           $cust_off.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  529:                           $lt{'usde'}.'</label>'.('&nbsp;' x3).
  530:                           '<label><input type="radio" name="custom'.$item.'" value="1" '.
  531:                           $cust_on.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  532:                           $lt{'uscu'}.'</label></span><br />'.
  533:                           '<fieldset id="customtext_'.$item.'"'.$editorsty.'>';
  534:                 foreach my $editor ('edit','xml','daxe') {
  535:                     my $checked;
  536:                     if ($userenv{'author'.$item} eq '') {
  537:                         if (grep(/^\Q$editor\E$/,@defaulteditors)) {
  538:                             $checked = ' checked="checked"';
  539:                         }
  540:                     } elsif (grep(/^\Q$editor\E$/,@customeditors)) {
  541:                         $checked = ' checked="checked"';
  542:                     }
  543:                     $output .= '<span style="LC_nobreak"><label>'.
  544:                                '<input type="checkbox" name="custom_editor" '.
  545:                                'value="'.$editor.'"'.$checked.' />'.
  546:                                $lt{$editor}.'</label></span> ';
  547:                 }
  548:                 $output .= '</fieldset></td>'.
  549:                            &Apache::loncommon::end_data_table_row()."\n";
  550:             }
  551:         } else {
  552:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  553:             my $name = $context.'_'.$item;
  554:             $onclick = 'onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');" ';
  555:             $custdisp = '<span class="LC_nobreak"><label>'.
  556:                         '<input type="radio" name="'.$name.'"'.
  557:                         ' value="1" '.$tool_on.$onclick.'/>'.&mt('On').'</label>&nbsp;<label>'.
  558:                         '<input type="radio" name="'.$name.'" value="0" '.
  559:                         $tool_off.$onclick.'/>'.&mt('Off').'</label></span>';
  560:             $custradio = '<span id="customtext_'.$item.'"'.$customsty.' class="LC_nobreak">'.
  561:                          '--'.$lt{'cusa'}.':&nbsp;'.$custdisp.'</span>';
  562:         }
  563:         unless ($item eq 'editors') {
  564:             $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  565:                        $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  566:                        &Apache::loncommon::end_data_table_row()."\n";
  567:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  568:                 $output .=
  569:                    &Apache::loncommon::start_data_table_row()."\n".
  570:                    '<td><span class="LC_nobreak">'.
  571:                    $lt{'chse'}.': <label>'.
  572:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  573:                    $cust_off.$onclick.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  574:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  575:                    $cust_on.$onclick.'/>'.$lt{'uscu'}.'</label></span>';
  576:                 if ($colspan) {
  577:                     $output .= '</td><td>';
  578:                 }
  579:                 $output .= $custradio.'</td>'.
  580:                            &Apache::loncommon::end_data_table_row()."\n";
  581:             }
  582:         }
  583:     }
  584:     return $output;
  585: }
  586: 
  587: sub coursereq_externaluser {
  588:     my ($ccuname,$ccdomain,$cdom) = @_;
  589:     my (@usertools,@options,%validations,%userenv,$output);
  590:     my %lt = &Apache::lonlocal::texthash (
  591:                    'official'   => 'Can request creation of official courses',
  592:                    'unofficial' => 'Can request creation of unofficial courses',
  593:                    'community'  => 'Can request creation of communities',
  594:                    'textbook'   => 'Can request creation of textbook courses',
  595:     );
  596: 
  597:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  598:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  599:                       'reqcrsotherdom.community','reqcrsotherdom.textbook');
  600:     @usertools = ('official','unofficial','community','textbook');
  601:     @options = ('approval','validate','autolimit');
  602:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  603:     my $optregex = join('|',@options);
  604:     my %reqtitles = &courserequest_titles();
  605:     foreach my $item (@usertools) {
  606:         my ($curroption,$currlimit,$tooloff);
  607:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  608:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  609:             foreach my $req (@curr) {
  610:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  611:                     $curroption = $1;
  612:                     $currlimit = $2;
  613:                     last;
  614:                 }
  615:             }
  616:             if (!$curroption) {
  617:                 $curroption = 'norequest';
  618:                 $tooloff = ' checked="checked"';
  619:             }
  620:         } else {
  621:             $curroption = 'norequest';
  622:             $tooloff = ' checked="checked"';
  623:         }
  624:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  625:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  626:                   '<table><tr><td valign="top">'."\n".
  627:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  628:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  629:                   '</label></td>';
  630:         foreach my $option (@options) {
  631:             if ($option eq 'validate') {
  632:                 my $canvalidate = 0;
  633:                 if (ref($validations{$item}) eq 'HASH') {
  634:                     if ($validations{$item}{'_external_'}) {
  635:                         $canvalidate = 1;
  636:                     }
  637:                 }
  638:                 next if (!$canvalidate);
  639:             }
  640:             my $checked = '';
  641:             if ($option eq $curroption) {
  642:                 $checked = ' checked="checked"';
  643:             }
  644:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  645:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  646:                        '" value="'.$option.'"'.$checked.' />'.
  647:                        $reqtitles{$option}.'</label>';
  648:             if ($option eq 'autolimit') {
  649:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  650:                            $item.'_limit" size="1" '.
  651:                            'value="'.$currlimit.'" /></span>'.
  652:                            '<br />'.$reqtitles{'unlimited'};
  653:             } else {
  654:                 $output .= '</span>';
  655:             }
  656:             $output .= '</td>';
  657:         }
  658:         $output .= '</td></tr></table></td>'."\n".
  659:                    &Apache::loncommon::end_data_table_row()."\n";
  660:     }
  661:     return $output;
  662: }
  663: 
  664: sub domainrole_req {
  665:     my ($ccuname,$ccdomain) = @_;
  666:     return '<br /><h3>'.
  667:            &mt('Can Request Assignment of Domain Roles?').
  668:            '</h3>'."\n".
  669:            &Apache::loncommon::start_data_table().
  670:            &build_tools_display($ccuname,$ccdomain,
  671:                                 'requestauthor').
  672:            &Apache::loncommon::end_data_table();
  673: }
  674: 
  675: sub authoring_defaults {
  676:     my ($ccuname,$ccdomain) = @_;
  677:     return '<br /><h3>'.
  678:            &mt('Authoring Space defaults (if role assigned)').
  679:            '</h3>'."\n".
  680:            &Apache::loncommon::start_data_table().
  681:            &build_tools_display($ccuname,$ccdomain,
  682:                                 'authordefaults').
  683:            &user_quotas($ccuname,$ccdomain,'author').
  684:            &Apache::loncommon::end_data_table();
  685: }
  686: 
  687: sub courserequest_titles {
  688:     my %titles = &Apache::lonlocal::texthash (
  689:                                    official   => 'Official',
  690:                                    unofficial => 'Unofficial',
  691:                                    community  => 'Communities',
  692:                                    textbook   => 'Textbook',
  693:                                    norequest  => 'Not allowed',
  694:                                    approval   => 'Approval by Dom. Coord.',
  695:                                    validate   => 'With validation',
  696:                                    autolimit  => 'Numerical limit',
  697:                                    unlimited  => '(blank for unlimited)',
  698:                  );
  699:     return %titles;
  700: }
  701: 
  702: sub courserequest_display {
  703:     my %titles = &Apache::lonlocal::texthash (
  704:                                    approval   => 'Yes, need approval',
  705:                                    validate   => 'Yes, with validation',
  706:                                    norequest  => 'No',
  707:    );
  708:    return %titles;
  709: }
  710: 
  711: sub requestauthor_titles {
  712:     my %titles = &Apache::lonlocal::texthash (
  713:                                    norequest  => 'Not allowed',
  714:                                    approval   => 'Approval by Dom. Coord.',
  715:                                    automatic  => 'Automatic approval',
  716:                  );
  717:     return %titles;
  718: 
  719: }
  720: 
  721: sub requestauthor_display {
  722:     my %titles = &Apache::lonlocal::texthash (
  723:                                    approval   => 'Yes, need approval',
  724:                                    automatic  => 'Yes, automatic approval',
  725:                                    norequest  => 'No',
  726:    );
  727:    return %titles;
  728: }
  729: 
  730: sub requestchange_display {
  731:     my %titles = &Apache::lonlocal::texthash (
  732:                                    approval   => "availability set to 'on' (approval required)", 
  733:                                    automatic  => "availability set to 'on' (automatic approval)",
  734:                                    norequest  => "availability set to 'off'",
  735:    );
  736:    return %titles;
  737: }
  738: 
  739: sub curr_requestauthor {
  740:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  741:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  742:     if ($uname eq '' || $udom eq '') {
  743:         $uname = $env{'user.name'};
  744:         $udom = $env{'user.domain'};
  745:         $isadv = $env{'user.adv'};
  746:     }
  747:     my (%userenv,%settings,$val);
  748:     my @options = ('automatic','approval');
  749:     %userenv =
  750:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  751:     if ($userenv{'requestauthor'}) {
  752:         $val = $userenv{'requestauthor'};
  753:         @{$inststatuses} = ('_custom_');
  754:     } else {
  755:         my %alltasks;
  756:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  757:             %settings = %{$domconfig->{'requestauthor'}};
  758:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  759:                 $val = $settings{'_LC_adv'};
  760:                 @{$inststatuses} = ('_LC_adv_');
  761:             } else {
  762:                 if ($userenv{'inststatus'} ne '') {
  763:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  764:                 } else {
  765:                     @{$inststatuses} = ('default');
  766:                 }
  767:                 foreach my $status (@{$inststatuses}) {
  768:                     if (exists($settings{$status})) {
  769:                         my $value = $settings{$status};
  770:                         next unless ($value);
  771:                         unless (exists($alltasks{$value})) {
  772:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  773:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  774:                                     push(@{$alltasks{$value}},$status);
  775:                                 }
  776:                             } else {
  777:                                 @{$alltasks{$value}} = ($status);
  778:                             }
  779:                         }
  780:                     }
  781:                 }
  782:                 foreach my $option (@options) {
  783:                     if ($alltasks{$option}) {
  784:                         $val = $option;
  785:                         last;
  786:                     }
  787:                 }
  788:             }
  789:         }
  790:     }
  791:     return $val;
  792: }
  793: 
  794: # =================================================================== Phase one
  795: 
  796: sub print_username_entry_form {
  797:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  798:         $permission) = @_;
  799:     my $defdom=$env{'request.role.domain'};
  800:     my $formtoset = 'crtuser';
  801:     if (exists($env{'form.startrolename'})) {
  802:         $formtoset = 'docustom';
  803:         $env{'form.rolename'} = $env{'form.startrolename'};
  804:     } elsif ($env{'form.origform'} eq 'crtusername') {
  805:         $formtoset =  $env{'form.origform'};
  806:     }
  807: 
  808:     my ($jsback,$elements) = &crumb_utilities();
  809: 
  810:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  811:         '<script type="text/javascript">'."\n".
  812:         '// <![CDATA['."\n".
  813:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  814:         '// ]]>'."\n".
  815:         '</script>'."\n";
  816: 
  817:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  818:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  819:         && (&Apache::lonnet::allowed('mcr','/'))) {
  820:         $jscript .= &customrole_javascript();
  821:     }
  822:     my $helpitem = 'Course_Change_Privileges';
  823:     if ($env{'form.action'} eq 'custom') {
  824:         if ($context eq 'course') {
  825:             $helpitem = 'Course_Editing_Custom_Roles';
  826:         } elsif ($context eq 'domain') {
  827:             $helpitem = 'Domain_Editing_Custom_Roles';
  828:         }
  829:     } elsif ($env{'form.action'} eq 'singlestudent') {
  830:         $helpitem = 'Course_Add_Student';
  831:     } elsif ($env{'form.action'} eq 'accesslogs') {
  832:         $helpitem = 'Domain_User_Access_Logs';
  833:     } elsif ($context eq 'author') {
  834:         $helpitem = 'Author_Change_Privileges';
  835:     } elsif ($context eq 'domain') {
  836:         if ($permission->{'cusr'}) {
  837:             $helpitem = 'Domain_Change_Privileges';
  838:         } elsif ($permission->{'view'}) {
  839:             $helpitem = 'Domain_View_Privileges';
  840:         } else {
  841:             undef($helpitem);
  842:         }
  843:     }
  844:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  845:     if ($env{'form.action'} eq 'custom') {
  846:         push(@{$brcrum},
  847:                  {href=>"javascript:backPage(document.crtuser)",       
  848:                   text=>"Pick custom role",
  849:                   help => $helpitem,}
  850:                  );
  851:     } else {
  852:         push (@{$brcrum},
  853:                   {href => "javascript:backPage(document.crtuser)",
  854:                    text => $breadcrumb_text{'search'},
  855:                    help => $helpitem,
  856:                    faq  => 282,
  857:                    bug  => 'Instructor Interface',}
  858:                   );
  859:     }
  860:     my %loaditems = (
  861:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  862:                     );
  863:     my $args = {bread_crumbs           => $brcrum,
  864:                 bread_crumbs_component => 'User Management',
  865:                 add_entries            => \%loaditems,};
  866:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  867: 
  868:     my %lt=&Apache::lonlocal::texthash(
  869:                     'srst' => 'Search for a user and enroll as a student',
  870:                     'srme' => 'Search for a user and enroll as a member',
  871:                     'srad' => 'Search for a user and modify/add user information or roles',
  872:                     'srvu' => 'Search for a user and view user information and roles',
  873:                     'srva' => 'Search for a user and view access log information',
  874: 		    'usr'  => "Username",
  875:                     'dom'  => "Domain",
  876:                     'ecrp' => "Define or Edit Custom Role",
  877:                     'nr'   => "role name",
  878:                     'cre'  => "Next",
  879: 				       );
  880: 
  881:     if ($env{'form.action'} eq 'custom') {
  882:         if (&Apache::lonnet::allowed('mcr','/')) {
  883:             my $newroletext = &mt('Define new custom role:');
  884:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  885:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  886:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  887:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  888:                       &Apache::loncommon::start_data_table().
  889:                       &Apache::loncommon::start_data_table_row().
  890:                       '<td>');
  891:             if (keys(%existingroles) > 0) {
  892:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  893:             } else {
  894:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  895:             }
  896:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  897:                       &Apache::loncommon::end_data_table_row());
  898:             if (keys(%existingroles) > 0) {
  899:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  900:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  901:                           &mt('View/Modify existing role:').'</b></label></td>'.
  902:                           '<td align="center"><br />'.
  903:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  904:                           '<option value="" selected="selected">'.
  905:                           &mt('Select'));
  906:                 foreach my $role (sort(keys(%existingroles))) {
  907:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  908:                 }
  909:                 $r->print('</select>'.
  910:                           '</td>'.
  911:                           &Apache::loncommon::end_data_table_row());
  912:             }
  913:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  914:                       '<input name="customeditor" type="submit" value="'.
  915:                       $lt{'cre'}.'" /></p>'.
  916:                       '</form>');
  917:         }
  918:     } else {
  919:         my $actiontext = $lt{'srad'};
  920:         my $fixeddom;
  921:         if ($env{'form.action'} eq 'singlestudent') {
  922:             if ($crstype eq 'Community') {
  923:                 $actiontext = $lt{'srme'};
  924:             } else {
  925:                 $actiontext = $lt{'srst'};
  926:             }
  927:         } elsif ($env{'form.action'} eq 'accesslogs') {
  928:             $actiontext = $lt{'srva'};
  929:             $fixeddom = 1;
  930:         } elsif (($env{'form.action'} eq 'singleuser') &&
  931:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  932:             $actiontext = $lt{'srvu'};
  933:             $fixeddom = 1;
  934:         }
  935:         $r->print("<h3>$actiontext</h3>");
  936:         if ($env{'form.origform'} ne 'crtusername') {
  937:             if ($response) {
  938:                $r->print("\n<div>$response</div>".
  939:                          '<br clear="all" />');
  940:             }
  941:         }
  942:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  943:     }
  944: }
  945: 
  946: sub customrole_javascript {
  947:     my $js = <<"END";
  948: <script type="text/javascript">
  949: // <![CDATA[
  950: 
  951: function setCustomFields() {
  952:     if (document.docustom.customroleaction.length > 0) {
  953:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  954:             if (document.docustom.customroleaction[i].checked) {
  955:                 if (document.docustom.customroleaction[i].value == 'new') {
  956:                     document.docustom.rolename.selectedIndex = 0;
  957:                 } else {
  958:                     document.docustom.newrolename.value = '';
  959:                 }
  960:             }
  961:         }
  962:     }
  963:     return;
  964: }
  965: 
  966: function setCustomAction(caller) {
  967:     if (document.docustom.customroleaction.length > 0) {
  968:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  969:             if (document.docustom.customroleaction[i].value == caller) {
  970:                 document.docustom.customroleaction[i].checked = true;
  971:             }
  972:         }
  973:     }
  974:     setCustomFields();
  975:     return;
  976: }
  977: 
  978: // ]]>
  979: </script>
  980: END
  981:     return $js;
  982: }
  983: 
  984: sub entry_form {
  985:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  986:     my ($usertype,$inexact);
  987:     if (ref($srch) eq 'HASH') {
  988:         if (($srch->{'srchin'} eq 'dom') &&
  989:             ($srch->{'srchby'} eq 'uname') &&
  990:             ($srch->{'srchtype'} eq 'exact') &&
  991:             ($srch->{'srchdomain'} ne '') &&
  992:             ($srch->{'srchterm'} ne '')) {
  993:             my (%curr_rules,%got_rules);
  994:             my ($rules,$ruleorder) =
  995:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  996:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  997:         } else {
  998:             $inexact = 1;
  999:         }
 1000:     }
 1001:     my ($cancreate,$noinstd);
 1002:     if ($env{'form.action'} eq 'accesslogs') {
 1003:         $noinstd = 1;
 1004:     } else {
 1005:         $cancreate =
 1006:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
 1007:     }
 1008:     my ($userpicker,$cansearch) = 
 1009:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
 1010:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
 1011:     my $srchbutton = &mt('Search');
 1012:     if ($env{'form.action'} eq 'singlestudent') {
 1013:         $srchbutton = &mt('Search and Enroll');
 1014:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1015:         $srchbutton = &mt('Search');
 1016:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
 1017:         $srchbutton = &mt('Search or Add New User');
 1018:     }
 1019:     my $output;
 1020:     if ($cansearch) {
 1021:         $output = <<"ENDBLOCK";
 1022: <form action="/adm/createuser" method="post" name="crtuser">
 1023: <input type="hidden" name="action" value="$env{'form.action'}" />
 1024: <input type="hidden" name="phase" value="get_user_info" />
 1025: $userpicker
 1026: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 1027: </form>
 1028: ENDBLOCK
 1029:     } else {
 1030:         $output = '<p>'.$userpicker.'</p>';
 1031:     }
 1032:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
 1033:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1034:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
 1035:         my $defdom=$env{'request.role.domain'};
 1036:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
 1037:         my %lt=&Apache::lonlocal::texthash(
 1038:                   'enro' => 'Enroll one student',
 1039:                   'enrm' => 'Enroll one member',
 1040:                   'admo' => 'Add/modify a single user',
 1041:                   'crea' => 'create new user if required',
 1042:                   'uskn' => "username is known",
 1043:                   'crnu' => 'Create a new user',
 1044:                   'usr'  => 'Username',
 1045:                   'dom'  => 'in domain',
 1046:                   'enrl' => 'Enroll',
 1047:                   'cram'  => 'Create/Modify user',
 1048:         );
 1049:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
 1050:         my ($title,$buttontext,$showresponse);
 1051:         if ($env{'form.action'} eq 'singlestudent') {
 1052:             if ($crstype eq 'Community') {
 1053:                 $title = $lt{'enrm'};
 1054:             } else {
 1055:                 $title = $lt{'enro'};
 1056:             }
 1057:             $buttontext = $lt{'enrl'};
 1058:         } else {
 1059:             $title = $lt{'admo'};
 1060:             $buttontext = $lt{'cram'};
 1061:         }
 1062:         if ($cancreate) {
 1063:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
 1064:         } else {
 1065:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
 1066:         }
 1067:         if ($env{'form.origform'} eq 'crtusername') {
 1068:             $showresponse = $responsemsg;
 1069:         }
 1070:         $output .= <<"ENDDOCUMENT";
 1071: <br />
 1072: <form action="/adm/createuser" method="post" name="crtusername">
 1073: <input type="hidden" name="action" value="$env{'form.action'}" />
 1074: <input type="hidden" name="phase" value="createnewuser" />
 1075: <input type="hidden" name="srchtype" value="exact" />
 1076: <input type="hidden" name="srchby" value="uname" />
 1077: <input type="hidden" name="srchin" value="dom" />
 1078: <input type="hidden" name="forcenewuser" value="1" />
 1079: <input type="hidden" name="origform" value="crtusername" />
 1080: <h3>$title</h3>
 1081: $showresponse
 1082: <table>
 1083:  <tr>
 1084:   <td>$lt{'usr'}:</td>
 1085:   <td><input type="text" size="15" name="srchterm" /></td>
 1086:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
 1087:   <td>&nbsp;$sellink&nbsp;</td>
 1088:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
 1089:  </tr>
 1090: </table>
 1091: </form>
 1092: ENDDOCUMENT
 1093:     }
 1094:     return $output;
 1095: }
 1096: 
 1097: sub user_modification_js {
 1098:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1099:     
 1100:     return <<END;
 1101: <script type="text/javascript" language="Javascript">
 1102: // <![CDATA[
 1103: 
 1104:     $pjump_def
 1105:     $dc_setcourse_code
 1106: 
 1107:     function dateset() {
 1108:         eval("document.cu."+document.cu.pres_marker.value+
 1109:             ".value=document.cu.pres_value.value");
 1110:         modalWindow.close();
 1111:     }
 1112: 
 1113:     $nondc_setsection_code
 1114: // ]]>
 1115: </script>
 1116: END
 1117: }
 1118: 
 1119: # =================================================================== Phase two
 1120: sub print_user_selection_page {
 1121:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1122:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1123:     my $sortby = $env{'form.sortby'};
 1124: 
 1125:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1126:         $sortby = 'lastname';
 1127:     }
 1128: 
 1129:     my ($jsback,$elements) = &crumb_utilities();
 1130: 
 1131:     my $jscript = (<<ENDSCRIPT);
 1132: <script type="text/javascript">
 1133: // <![CDATA[
 1134: function pickuser(uname,udom) {
 1135:     document.usersrchform.seluname.value=uname;
 1136:     document.usersrchform.seludom.value=udom;
 1137:     document.usersrchform.phase.value="userpicked";
 1138:     document.usersrchform.submit();
 1139: }
 1140: 
 1141: $jsback
 1142: // ]]>
 1143: </script>
 1144: ENDSCRIPT
 1145: 
 1146:     my %lt=&Apache::lonlocal::texthash(
 1147:                                        'usrch'          => "User Search to add/modify roles",
 1148:                                        'stusrch'        => "User Search to enroll student",
 1149:                                        'memsrch'        => "User Search to enroll member",
 1150:                                        'srcva'          => "Search for a user and view access log information",
 1151:                                        'usrvu'          => "User Search to view user roles",
 1152:                                        'usel'           => "Select a user to add/modify roles",
 1153:                                        'suvr'           => "Select a user to view roles",
 1154:                                        'stusel'         => "Select a user to enroll as a student",
 1155:                                        'memsel'         => "Select a user to enroll as a member",
 1156:                                        'vacsel'         => "Select a user to view access log",
 1157:                                        'username'       => "username",
 1158:                                        'domain'         => "domain",
 1159:                                        'lastname'       => "last name",
 1160:                                        'firstname'      => "first name",
 1161:                                        'permanentemail' => "permanent e-mail",
 1162:                                       );
 1163:     if ($context eq 'requestcrs') {
 1164:         $r->print('<div>');
 1165:     } else {
 1166:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1167:         my $helpitem;
 1168:         if ($env{'form.action'} eq 'singleuser') {
 1169:             $helpitem = 'Course_Change_Privileges';
 1170:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1171:             $helpitem = 'Course_Add_Student';
 1172:         } elsif ($context eq 'author') {
 1173:             $helpitem = 'Author_Change_Privileges';
 1174:         } elsif ($context eq 'domain') {
 1175:             $helpitem = 'Domain_Change_Privileges';
 1176:         }
 1177:         push (@{$brcrum},
 1178:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1179:                    text => $breadcrumb_text{'search'},
 1180:                    faq  => 282,
 1181:                    bug  => 'Instructor Interface',},
 1182:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1183:                    text => $breadcrumb_text{'userpicked'},
 1184:                    faq  => 282,
 1185:                    bug  => 'Instructor Interface',
 1186:                    help => $helpitem}
 1187:                   );
 1188:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1189:         if ($env{'form.action'} eq 'singleuser') {
 1190:             my $readonly;
 1191:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1192:                 $readonly = 1;
 1193:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1194:             } else {
 1195:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1196:             }
 1197:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1198:             if ($readonly) {
 1199:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1200:             } else {
 1201:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1202:             }
 1203:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1204:             $r->print($jscript."<b>");
 1205:             if ($crstype eq 'Community') {
 1206:                 $r->print($lt{'memsrch'});
 1207:             } else {
 1208:                 $r->print($lt{'stusrch'});
 1209:             }
 1210:             $r->print("</b><br />");
 1211:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1212:             $r->print('</form><h3>');
 1213:             if ($crstype eq 'Community') {
 1214:                 $r->print($lt{'memsel'});
 1215:             } else {
 1216:                 $r->print($lt{'stusel'});
 1217:             }
 1218:             $r->print('</h3>');
 1219:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1220:             $r->print("<b>$lt{'srcva'}</b><br />");
 1221:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1222:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1223:         }
 1224:     }
 1225:     $r->print('<form name="usersrchform" method="post" action="">'.
 1226:               &Apache::loncommon::start_data_table()."\n".
 1227:               &Apache::loncommon::start_data_table_header_row()."\n".
 1228:               ' <th> </th>'."\n");
 1229:     foreach my $field (@fields) {
 1230:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1231:                   "'".$field."'".';document.usersrchform.submit();">'.
 1232:                   $lt{$field}.'</a></th>'."\n");
 1233:     }
 1234:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1235: 
 1236:     my @sorted_users = sort {
 1237:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1238:             ||
 1239:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1240:             ||
 1241:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1242: 	    ||
 1243: 	lc($a) cmp lc($b)
 1244:         } (keys(%$srch_results));
 1245: 
 1246:     foreach my $user (@sorted_users) {
 1247:         my ($uname,$udom) = split(/:/,$user);
 1248:         my $onclick;
 1249:         if ($context eq 'requestcrs') {
 1250:             $onclick =
 1251:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1252:                                                "'$srch_results->{$user}->{firstname}',".
 1253:                                                "'$srch_results->{$user}->{lastname}',".
 1254:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1255:         } else {
 1256:             $onclick =
 1257:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1258:         }
 1259:         $r->print(&Apache::loncommon::start_data_table_row().
 1260:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1261:                   $onclick.' /></td>'.
 1262:                   '<td><tt>'.$uname.'</tt></td>'.
 1263:                   '<td><tt>'.$udom.'</tt></td>');
 1264:         foreach my $field ('lastname','firstname','permanentemail') {
 1265:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1266:         }
 1267:         $r->print(&Apache::loncommon::end_data_table_row());
 1268:     }
 1269:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1270:     if (ref($srcharray) eq 'ARRAY') {
 1271:         foreach my $item (@{$srcharray}) {
 1272:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1273:         }
 1274:     }
 1275:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1276:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1277:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1278:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1279:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1280:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1281:     if ($context eq 'requestcrs') {
 1282:         $r->print($opener_elements.'</form></div>');
 1283:     } else {
 1284:         $r->print($response.'</form>');
 1285:     }
 1286: }
 1287: 
 1288: sub print_user_query_page {
 1289:     my ($r,$caller,$brcrum) = @_;
 1290: # FIXME - this is for a network-wide name search (similar to catalog search)
 1291: # To use frames with similar behavior to catalog/portfolio search.
 1292: # To be implemented. 
 1293:     return;
 1294: }
 1295: 
 1296: sub print_user_modification_page {
 1297:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1298:         $brcrum,$showcredits) = @_;
 1299:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1300:         my $usermsg = &mt('No username and/or domain provided.');
 1301:         $env{'form.phase'} = '';
 1302: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1303:                                    $permission);
 1304:         return;
 1305:     }
 1306:     my ($form,$formname);
 1307:     if ($env{'form.action'} eq 'singlestudent') {
 1308:         $form = 'document.enrollstudent';
 1309:         $formname = 'enrollstudent';
 1310:     } else {
 1311:         $form = 'document.cu';
 1312:         $formname = 'cu';
 1313:     }
 1314:     my %abv_auth = &auth_abbrev();
 1315:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1316:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1317:     if ($uhome eq 'no_host') {
 1318:         my $usertype;
 1319:         my ($rules,$ruleorder) =
 1320:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1321:             $usertype =
 1322:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1323:                                                       \%curr_rules,\%got_rules);
 1324:         my $cancreate =
 1325:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1326:                                                    $usertype);
 1327:         if (!$cancreate) {
 1328:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1329:             my %usertypetext = (
 1330:                 official   => 'institutional',
 1331:                 unofficial => 'non-institutional',
 1332:             );
 1333:             my $response;
 1334:             if ($env{'form.origform'} eq 'crtusername') {
 1335:                 $response = '<span class="LC_warning">'.
 1336:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1337:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1338:                             '</span><br />';
 1339:             }
 1340:             $response .= '<p class="LC_warning">'
 1341:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1342:                         .' ';
 1343:             if ($context eq 'domain') {
 1344:                 $response .= &mt('Please contact a [_1] for assistance.',
 1345:                                  &Apache::lonnet::plaintext('dc'));
 1346:             } else {
 1347:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1348:                                 ,'<a href="'.$helplink.'">','</a>');
 1349:             }
 1350:             $response .= '</p><br />';
 1351:             $env{'form.phase'} = '';
 1352:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1353:                                        $permission);
 1354:             return;
 1355:         }
 1356:         $newuser = 1;
 1357:         my $checkhash;
 1358:         my $checks = { 'username' => 1 };
 1359:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1360:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1361:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1362:         if (ref($alerts{'username'}) eq 'HASH') {
 1363:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1364:                 my $domdesc =
 1365:                     &Apache::lonnet::domain($ccdomain,'description');
 1366:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1367:                     my $userchkmsg;
 1368:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1369:                         $userchkmsg = 
 1370:                             &Apache::loncommon::instrule_disallow_msg('username',
 1371:                                                                  $domdesc,1).
 1372:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1373:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1374:                             'username');
 1375:                     }
 1376:                     $env{'form.phase'} = '';
 1377:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1378:                                                $permission);
 1379:                     return;
 1380:                 }
 1381:             }
 1382:         }
 1383:     } else {
 1384:         $newuser = 0;
 1385:     }
 1386:     if ($response) {
 1387:         $response = '<br />'.$response;
 1388:     }
 1389: 
 1390:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1391:     my $dc_setcourse_code = '';
 1392:     my $nondc_setsection_code = '';                                        
 1393:     my %loaditem;
 1394: 
 1395:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1396: 
 1397:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1398:                                     $crstype,$groupslist,$newuser,
 1399:                                     $formname,\%loaditem,$permission);
 1400:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1401:     my $helpitem = 'Course_Change_Privileges';
 1402:     if ($env{'form.action'} eq 'singlestudent') {
 1403:         $helpitem = 'Course_Add_Student';
 1404:     } elsif ($context eq 'author') {
 1405:         $helpitem = 'Author_Change_Privileges';
 1406:     } elsif ($context eq 'domain') {
 1407:         $helpitem = 'Domain_Change_Privileges';
 1408:         $js .= &set_custom_js();
 1409:     }
 1410:     push (@{$brcrum},
 1411:         {href => "javascript:backPage($form)",
 1412:          text => $breadcrumb_text{'search'},
 1413:          faq  => 282,
 1414:          bug  => 'Instructor Interface',});
 1415:     if ($env{'form.phase'} eq 'userpicked') {
 1416:        push(@{$brcrum},
 1417:               {href => "javascript:backPage($form,'get_user_info','select')",
 1418:                text => $breadcrumb_text{'userpicked'},
 1419:                faq  => 282,
 1420:                bug  => 'Instructor Interface',});
 1421:     }
 1422:     push(@{$brcrum},
 1423:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1424:              text => $breadcrumb_text{'modify'},
 1425:              faq  => 282,
 1426:              bug  => 'Instructor Interface',
 1427:              help => $helpitem});
 1428:     my $args = {'add_entries'           => \%loaditem,
 1429:                 'bread_crumbs'          => $brcrum,
 1430:                 'bread_crumbs_component' => 'User Management'};
 1431:     if ($env{'form.popup'}) {
 1432:         $args->{'no_nav_bar'} = 1;
 1433:     }
 1434:     if (($context eq 'domain') && ($env{'request.role.domain'} eq $ccdomain)) {
 1435:         my @toggles;
 1436:         if (&Apache::lonnet::allowed('cau',$ccdomain)) {
 1437:             my ($isadv,$isauthor) =
 1438:                 &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1439:             unless ($isauthor) {
 1440:                 push(@toggles,'requestauthor');
 1441:             }
 1442:             push(@toggles,('webdav','editors'));
 1443:         }
 1444:         if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1445:             push(@toggles,('aboutme','blog','portfolio','timezone'));
 1446:         }
 1447:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1448:             push(@toggles,('official','unofficial','community','textbook'));
 1449:         }
 1450:         if (@toggles) {
 1451:             my $onload;
 1452:             foreach my $item (@toggles) {
 1453:                 $onload .= "toggleCustom(document.cu,'customtext_$item','custom$item');";
 1454:             }
 1455:             $args->{'add_entries'} = {
 1456:                                        'onload' => $onload,
 1457:                                      };
 1458:         }
 1459:     }
 1460:     my $start_page =
 1461:         &Apache::loncommon::start_page('User Management',$js,$args);
 1462: 
 1463:     my $forminfo =<<"ENDFORMINFO";
 1464: <form action="/adm/createuser" method="post" name="$formname">
 1465: <input type="hidden" name="phase" value="update_user_data" />
 1466: <input type="hidden" name="ccuname" value="$ccuname" />
 1467: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1468: <input type="hidden" name="pres_value"  value="" />
 1469: <input type="hidden" name="pres_type"   value="" />
 1470: <input type="hidden" name="pres_marker" value="" />
 1471: ENDFORMINFO
 1472:     my (%inccourses,$roledom,$defaultcredits);
 1473:     if ($context eq 'course') {
 1474:         $inccourses{$env{'request.course.id'}}=1;
 1475:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1476:         if ($showcredits) {
 1477:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1478:         }
 1479:     } elsif ($context eq 'author') {
 1480:         $roledom = $env{'request.role.domain'};
 1481:     } elsif ($context eq 'domain') {
 1482:         foreach my $key (keys(%env)) {
 1483:             $roledom = $env{'request.role.domain'};
 1484:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1485:                 $inccourses{$1.'_'.$2}=1;
 1486:             }
 1487:         }
 1488:     } else {
 1489:         foreach my $key (keys(%env)) {
 1490: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1491: 	        $inccourses{$1.'_'.$2}=1;
 1492:             }
 1493:         }
 1494:     }
 1495:     my $title = '';
 1496:     my $need_quota_js;
 1497:     if ($newuser) {
 1498:         my ($portfolioform,$domroleform);
 1499:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1500:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1501:             # Current user has quota or user tools modification privileges
 1502:             $portfolioform = '<br /><h3>'.
 1503:                              &mt('User Tools').
 1504:                              '</h3>'."\n".
 1505:                              &Apache::loncommon::start_data_table();
 1506:             if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1507:                 $portfolioform .= &build_tools_display($ccuname,$ccdomain,'tools');
 1508:             }
 1509:             if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1510:                 $portfolioform .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1511:                 $need_quota_js = 1;
 1512:             }
 1513:             $portfolioform .= &Apache::loncommon::end_data_table();
 1514:         }
 1515:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1516:             ($ccdomain eq $env{'request.role.domain'})) {
 1517:             $domroleform = &domainrole_req($ccuname,$ccdomain).
 1518:                            &authoring_defaults($ccuname,$ccdomain);
 1519:             $need_quota_js = 1;
 1520:         }
 1521:         my $readonly;
 1522:         unless ($permission->{'cusr'}) {
 1523:             $readonly = 1;
 1524:         }
 1525:         &initialize_authen_forms($ccdomain,$formname,'','',$readonly);
 1526:         my %lt=&Apache::lonlocal::texthash(
 1527:                 'lg'             => 'Login Data',
 1528:                 'hs'             => "Home Server",
 1529:         );
 1530: 	$r->print(<<ENDTITLE);
 1531: $start_page
 1532: $response
 1533: $forminfo
 1534: <script type="text/javascript" language="Javascript">
 1535: // <![CDATA[
 1536: $loginscript
 1537: // ]]>
 1538: </script>
 1539: <input type='hidden' name='makeuser' value='1' />
 1540: ENDTITLE
 1541:         if ($env{'form.action'} eq 'singlestudent') {
 1542:             if ($crstype eq 'Community') {
 1543:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1544:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1545:             } else {
 1546:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1547:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1548:             }
 1549:         } else {
 1550:                 $title = &mt('Create New User [_1] in domain [_2]',
 1551:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1552:         }
 1553:         $r->print('<h2>'.$title.'</h2>'."\n");
 1554:         $r->print('<div class="LC_left_float">');
 1555:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1556:                                          $inst_results{$ccuname.':'.$ccdomain},$readonly));
 1557:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1558:         my ($home_server_pick,$numlib) = 
 1559:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1560:                                                       'default','hide');
 1561:         if ($numlib > 1) {
 1562:             $r->print("
 1563: <br />
 1564: $lt{'hs'}: $home_server_pick
 1565: <br />");
 1566:         } else {
 1567:             $r->print($home_server_pick);
 1568:         }
 1569:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1570:             $r->print('<br /><h3>'.
 1571:                       &mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1572:                       &Apache::loncommon::start_data_table().
 1573:                       &build_tools_display($ccuname,$ccdomain,
 1574:                                            'requestcourses').
 1575:                       &Apache::loncommon::end_data_table());
 1576:         }
 1577:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1578:                   $lt{'lg'}.'</h3>');
 1579:         my ($fixedauth,$varauth,$authmsg); 
 1580:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1581:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1582:             my ($rules,$ruleorder) = 
 1583:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1584:             if (ref($rules) eq 'HASH') {
 1585:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1586:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1587:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1588:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1589:                     } else { 
 1590:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1591:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1592:                         if ($authtype =~ /^krb(4|5)$/) {
 1593:                             my $ver = $1;
 1594:                             if ($authparm ne '') {
 1595:                                 $fixedauth = <<"KERB"; 
 1596: <input type="hidden" name="login" value="krb" />
 1597: <input type="hidden" name="krbver" value="$ver" />
 1598: <input type="hidden" name="krbarg" value="$authparm" />
 1599: KERB
 1600:                             }
 1601:                         } else {
 1602:                             $fixedauth = 
 1603: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1604:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1605:                                 $fixedauth .=    
 1606: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1607:                             } else {
 1608:                                 if ($authtype eq 'int') {
 1609:                                     $varauth = '<br />'.
 1610: &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>';
 1611:                                 } elsif ($authtype eq 'loc') {
 1612:                                     $varauth = '<br />'.
 1613: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1614:                                 } else {
 1615:                                     $varauth =
 1616: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1617:                                 }
 1618:                             }
 1619:                         }
 1620:                     }
 1621:                 } else {
 1622:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1623:                 }
 1624:             }
 1625:             if ($authmsg) {
 1626:                 $r->print(<<ENDAUTH);
 1627: $fixedauth
 1628: $authmsg
 1629: $varauth
 1630: ENDAUTH
 1631:             }
 1632:         } else {
 1633:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1634:         }
 1635:         $r->print($portfolioform.$domroleform);
 1636:         if ($env{'form.action'} eq 'singlestudent') {
 1637:             $r->print(&date_sections_select($context,$newuser,$formname,
 1638:                                             $permission,$crstype,$ccuname,
 1639:                                             $ccdomain,$showcredits));
 1640:         }
 1641:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1642:     } else { # user already exists
 1643: 	$r->print($start_page.$forminfo);
 1644:         if ($env{'form.action'} eq 'singlestudent') {
 1645:             if ($crstype eq 'Community') {
 1646:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1647:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1648:             } else {
 1649:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1650:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1651:             }
 1652:         } else {
 1653:             if ($permission->{'cusr'}) {
 1654:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1655:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1656:             } else {
 1657:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1658:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1659:             }
 1660:         }
 1661:         $r->print('<h2>'.$title.'</h2>'."\n");
 1662:         $r->print('<div class="LC_left_float">');
 1663:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1664:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1665:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1666:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1667:             $r->print('<br /><h3>'.&mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n".
 1668:                       &Apache::loncommon::start_data_table());
 1669:             if ($env{'request.role.domain'} eq $ccdomain) {
 1670:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1671:             } else {
 1672:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1673:                                                   $env{'request.role.domain'}));
 1674:             }
 1675:             $r->print(&Apache::loncommon::end_data_table());
 1676:         }
 1677:         $r->print('</div>');
 1678:         my @order = ('auth','quota','tools','requestauthor','authordefaults');
 1679:         my %user_text;
 1680:         my ($isadv,$isauthor) = 
 1681:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1682:         if (((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1683:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1684:             ($env{'request.role.domain'} eq $ccdomain)) {
 1685:             if (!$isauthor) {
 1686:                 $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1687:             }
 1688:             $user_text{'authordefaults'} = &authoring_defaults($ccuname,$ccdomain);
 1689:             if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1690:                 $need_quota_js = 1;
 1691:             }
 1692:         }
 1693:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1694:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1695:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1696:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1697:             $user_text{'quota'} = '<br /><h3>'.&mt('User Tools').'</h3>'."\n".
 1698:                                   &Apache::loncommon::start_data_table();
 1699:             if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1700:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1701:                 $user_text{'quota'} .= &build_tools_display($ccuname,$ccdomain,'tools');
 1702:             }
 1703:             # Current user has quota modification privileges
 1704:             if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1705:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1706:                 $user_text{'quota'} .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1707:                 $need_quota_js = 1;
 1708:             }
 1709:             $user_text{'quota'} .= &Apache::loncommon::end_data_table();
 1710:         }
 1711:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1712:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1713:                 my %lt=&Apache::lonlocal::texthash(
 1714:                     'dska'  => "Disk quotas for user's portfolio",
 1715:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1716:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1717:                 );
 1718:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1719: <h3>$lt{'dska'}</h3>
 1720: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1721: ENDNOPORTPRIV
 1722:             }
 1723:         }
 1724:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1725:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1726:                 my %lt=&Apache::lonlocal::texthash(
 1727:                     'utav'  => "User Tools Availability",
 1728:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, Personal Information Page, or Time Zone settings for this user.",
 1729:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1730:                 );
 1731:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1732: <h3>$lt{'utav'}</h3>
 1733: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1734: ENDNOTOOLSPRIV
 1735:             }
 1736:         }
 1737:         my $gotdiv = 0; 
 1738:         foreach my $item (@order) {
 1739:             if ($user_text{$item} ne '') {
 1740:                 unless ($gotdiv) {
 1741:                     $r->print('<div class="LC_left_float">');
 1742:                     $gotdiv = 1;
 1743:                 }
 1744:                 $r->print('<br />'.$user_text{$item});
 1745:             }
 1746:         }
 1747:         if ($env{'form.action'} eq 'singlestudent') {
 1748:             unless ($gotdiv) {
 1749:                 $r->print('<div class="LC_left_float">');
 1750:             }
 1751:             my $credits;
 1752:             if ($showcredits) {
 1753:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1754:                 if ($credits eq '') {
 1755:                     $credits = $defaultcredits;
 1756:                 }
 1757:             }
 1758:             $r->print(&date_sections_select($context,$newuser,$formname,
 1759:                                             $permission,$crstype,$ccuname,
 1760:                                             $ccdomain,$showcredits));
 1761:         }
 1762:         if ($gotdiv) {
 1763:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1764:         }
 1765:         my $statuses;
 1766:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1767:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1768:             $statuses = ['active'];
 1769:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1770:                  ($env{'request.course.sec'} &&
 1771:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1772:             $statuses = ['active'];
 1773:         }
 1774:         if ($env{'form.action'} ne 'singlestudent') {
 1775:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1776:                                     $roledom,$crstype,$showcredits,$statuses);
 1777:         }
 1778:     } ## End of new user/old user logic
 1779:     if ($env{'form.action'} eq 'singlestudent') {
 1780:         my $btntxt;
 1781:         if ($crstype eq 'Community') {
 1782:             $btntxt = &mt('Enroll Member');
 1783:         } else {
 1784:             $btntxt = &mt('Enroll Student');
 1785:         }
 1786:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1787:     } elsif ($permission->{'cusr'}) {
 1788:         $r->print('<div class="LC_left_float">'.
 1789:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1790:         my $addrolesdisplay = 0;
 1791:         if ($context eq 'domain' || $context eq 'author') {
 1792:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1793:         }
 1794:         if ($context eq 'domain') {
 1795:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1796:             if (!$addrolesdisplay) {
 1797:                 $addrolesdisplay = $add_domainroles;
 1798:             }
 1799:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1800:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1801:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1802:         } elsif ($context eq 'author') {
 1803:             if ($addrolesdisplay) {
 1804:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1805:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1806:                 if ($newuser) {
 1807:                     $r->print(' onclick="auth_check()" \>'."\n");
 1808:                 } else {
 1809:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1810:                 }
 1811:             } else {
 1812:                 $r->print('</fieldset></div>'.
 1813:                           '<div class="LC_clear_float_footer"></div>'.
 1814:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1815:                           &mt('Back to previous page').'</a>');
 1816:             }
 1817:         } else {
 1818:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1819:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1820:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1821:         }
 1822:     }
 1823:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1824:     $r->print('<input type="hidden" name="currstate" value="" />');
 1825:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1826:     if ($need_quota_js) {
 1827:         $r->print(&user_quota_js());
 1828:     }
 1829:     return;
 1830: }
 1831: 
 1832: sub singleuser_breadcrumb {
 1833:     my ($crstype,$context,$domain) = @_;
 1834:     my %breadcrumb_text;
 1835:     if ($env{'form.action'} eq 'singlestudent') {
 1836:         if ($crstype eq 'Community') {
 1837:             $breadcrumb_text{'search'} = 'Enroll a member';
 1838:         } else {
 1839:             $breadcrumb_text{'search'} = 'Enroll a student';
 1840:         }
 1841:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1842:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1843:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1844:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1845:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1846:         $breadcrumb_text{'activity'} = 'Activity';
 1847:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1848:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1849:         $breadcrumb_text{'search'} = "View user's roles";
 1850:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1851:         $breadcrumb_text{'modify'} = 'User roles';
 1852:     } else {
 1853:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1854:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1855:         $breadcrumb_text{'modify'} = 'Set user role';
 1856:     }
 1857:     return %breadcrumb_text;
 1858: }
 1859: 
 1860: sub date_sections_select {
 1861:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1862:         $showcredits) = @_;
 1863:     my $credits;
 1864:     if ($showcredits) {
 1865:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1866:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1867:         if ($credits eq '') {
 1868:             $credits = $defaultcredits;
 1869:         }
 1870:     }
 1871:     my $cid = $env{'request.course.id'};
 1872:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1873:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1874:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1875:                                                   undef,$formname,$permission);
 1876:     my $rowtitle = 'Section';
 1877:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1878:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1879:                                               $permission,$context,'',$crstype,
 1880:                                               $showcredits,$credits);
 1881:     my $output = $date_table.$secbox;
 1882:     return $output;
 1883: }
 1884: 
 1885: sub validation_javascript {
 1886:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1887:         $loaditem,$permission) = @_;
 1888:     my $dc_setcourse_code = '';
 1889:     my $nondc_setsection_code = '';
 1890:     if ($context eq 'domain') {
 1891:         if ((ref($permission) eq 'HASH') && ($permission->{'cusr'})) {
 1892:             my $dcdom = $env{'request.role.domain'};
 1893:             $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1894:             $dc_setcourse_code = 
 1895:                 &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1896:         }
 1897:     } else {
 1898:         my $checkauth; 
 1899:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1900:             $checkauth = 1;
 1901:         }
 1902:         if ($context eq 'course') {
 1903:             $nondc_setsection_code =
 1904:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1905:                                                               undef,$checkauth,
 1906:                                                               $crstype);
 1907:         }
 1908:         if ($checkauth) {
 1909:             $nondc_setsection_code .= 
 1910:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1911:         }
 1912:     }
 1913:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1914:                                    $nondc_setsection_code,$groupslist);
 1915:     my ($jsback,$elements) = &crumb_utilities();
 1916:     $js .= "\n".
 1917:            '<script type="text/javascript">'."\n".
 1918:            '// <![CDATA['."\n".
 1919:            $jsback."\n".
 1920:            '// ]]>'."\n".
 1921:            '</script>'."\n";
 1922:     return $js;
 1923: }
 1924: 
 1925: sub display_existing_roles {
 1926:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1927:         $showcredits,$statuses) = @_;
 1928:     my $now=time;
 1929:     my $showall = 1;
 1930:     my ($showexpired,$showactive);
 1931:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1932:         $showall = 0;
 1933:         if (grep(/^expired$/,@{$statuses})) {
 1934:             $showexpired = 1;
 1935:         }
 1936:         if (grep(/^active$/,@{$statuses})) {
 1937:             $showactive = 1;
 1938:         }
 1939:         if ($showexpired && $showactive) {
 1940:             $showall = 1;
 1941:         }
 1942:     }
 1943:     my %lt=&Apache::lonlocal::texthash(
 1944:                     'rer'  => "Existing Roles",
 1945:                     'rev'  => "Revoke",
 1946:                     'del'  => "Delete",
 1947:                     'ren'  => "Re-Enable",
 1948:                     'rol'  => "Role",
 1949:                     'ext'  => "Extent",
 1950:                     'crd'  => "Credits",
 1951:                     'sta'  => "Start",
 1952:                     'end'  => "End",
 1953:                                        );
 1954:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1955:     if ($context eq 'course' || $context eq 'author') {
 1956:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1957:         my %roleshash = 
 1958:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1959:                               ['active','previous','future'],\@roles,$roledom,1);
 1960:         foreach my $key (keys(%roleshash)) {
 1961:             my ($start,$end) = split(':',$roleshash{$key});
 1962:             next if ($start eq '-1' || $end eq '-1');
 1963:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1964:             if ($context eq 'course') {
 1965:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1966:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1967:             } elsif ($context eq 'author') {
 1968:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1969:             }
 1970:             my ($newkey,$newvalue,$newrole);
 1971:             $newkey = '/'.$rdom.'/'.$rnum;
 1972:             if ($sec ne '') {
 1973:                 $newkey .= '/'.$sec;
 1974:             }
 1975:             $newvalue = $role;
 1976:             if ($role =~ /^cr/) {
 1977:                 $newrole = 'cr';
 1978:             } else {
 1979:                 $newrole = $role;
 1980:             }
 1981:             $newkey .= '_'.$newrole;
 1982:             if ($start ne '' && $end ne '') {
 1983:                 $newvalue .= '_'.$end.'_'.$start;
 1984:             } elsif ($end ne '') {
 1985:                 $newvalue .= '_'.$end;
 1986:             }
 1987:             $rolesdump{$newkey} = $newvalue;
 1988:         }
 1989:     } else {
 1990:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1991:     }
 1992:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1993:     my ($tmp) = keys(%rolesdump);
 1994:     return if ($tmp =~ /^(con_lost|error)/i);
 1995:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1996:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1997:                                 return $a1 cmp $b1;
 1998:                             } keys(%rolesdump)) {
 1999:         next if ($area =~ /^rolesdef/);
 2000:         my $envkey=$area;
 2001:         my $role = $rolesdump{$area};
 2002:         my $thisrole=$area;
 2003:         $area =~ s/\_\w\w$//;
 2004:         my ($role_code,$role_end_time,$role_start_time) =
 2005:             split(/_/,$role);
 2006:         my $active=1;
 2007:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 2008:         if ($active) {
 2009:             next unless($showall || $showactive);
 2010:         } else {
 2011:             next unless($showall || $showexpired);
 2012:         }
 2013: # Is this a custom role? Get role owner and title.
 2014:         my ($croleudom,$croleuname,$croletitle)=
 2015:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 2016:         my $allowed=0;
 2017:         my $delallowed=0;
 2018:         my $sortkey=$role_code;
 2019:         my $class='Unknown';
 2020:         my $credits='';
 2021:         my $csec;
 2022:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 2023:             $class='Course';
 2024:             my ($coursedom,$coursedir) = ($1,$2);
 2025:             my $cid = $1.'_'.$2;
 2026:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 2027:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 2028:             my %coursedata=
 2029:                 &Apache::lonnet::coursedescription($cid);
 2030:             if ($coursedir =~ /^$match_community$/) {
 2031:                 $class='Community';
 2032:             }
 2033:             $sortkey.="\0$coursedom";
 2034:             my $carea;
 2035:             if (defined($coursedata{'description'})) {
 2036:                 $carea=$coursedata{'description'}.
 2037:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 2038:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 2039:                 $sortkey.="\0".$coursedata{'description'};
 2040:             } else {
 2041:                 if ($class eq 'Community') {
 2042:                     $carea=&mt('Unavailable community').': '.$area;
 2043:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 2044:                 } else {
 2045:                     $carea=&mt('Unavailable course').': '.$area;
 2046:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 2047:                 }
 2048:             }
 2049:             $sortkey.="\0$coursedir";
 2050:             $inccourses->{$cid}=1;
 2051:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 2052:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 2053:                 $credits =
 2054:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 2055:                                       $coursedom,$coursedir);
 2056:                 if ($credits eq '') {
 2057:                     $credits = $defaultcredits;
 2058:                 }
 2059:             }
 2060:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 2061:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2062:                 $allowed=1;
 2063:             }
 2064:             unless ($allowed) {
 2065:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 2066:                 if ($isowner) {
 2067:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 2068:                         $allowed = 1;
 2069:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 2070:                         $allowed = 1;
 2071:                     }
 2072:                 }
 2073:             } 
 2074:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 2075:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 2076:                 $delallowed=1;
 2077:             }
 2078: # - custom role. Needs more info, too
 2079:             if ($croletitle) {
 2080:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 2081:                     $allowed=1;
 2082:                     $thisrole.='.'.$role_code;
 2083:                 }
 2084:             }
 2085:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 2086:                 $csec = $2;
 2087:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 2088:                 $sortkey.="\0$csec";
 2089:                 if (!$allowed) {
 2090:                     if ($env{'request.course.sec'} eq $csec) {
 2091:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 2092:                             $allowed = 1;
 2093:                         }
 2094:                     }
 2095:                 }
 2096:             }
 2097:             $area=$carea;
 2098:         } else {
 2099:             $sortkey.="\0".$area;
 2100:             # Determine if current user is able to revoke privileges
 2101:             if ($area=~m{^/($match_domain)/}) {
 2102:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 2103:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2104:                    $allowed=1;
 2105:                 }
 2106:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 2107:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 2108:                     ($role_code ne 'dc')) {
 2109:                     $delallowed=1;
 2110:                 }
 2111:             } else {
 2112:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 2113:                     $allowed=1;
 2114:                 }
 2115:             }
 2116:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 2117:                 $class='Authoring Space';
 2118:             } elsif ($role_code eq 'su') {
 2119:                 $class='System';
 2120:             } else {
 2121:                 $class='Domain';
 2122:             }
 2123:         }
 2124:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 2125:             $area=~m{/($match_domain)/($match_username)};
 2126:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 2127:                 $allowed=1;
 2128:             } else {
 2129:                 $allowed=0;
 2130:             }
 2131:         }
 2132:         my $row = '';
 2133:         if ($showall) {
 2134:             $row.= '<td>';
 2135:             if (($active) && ($allowed)) {
 2136:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 2137:             } else {
 2138:                 if ($active) {
 2139:                     $row.='&nbsp;';
 2140:                 } else {
 2141:                     $row.=&mt('expired or revoked');
 2142:                 }
 2143:             }
 2144:             $row.='</td><td>';
 2145:             if ($allowed && !$active) {
 2146:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 2147:             } else {
 2148:                 $row.='&nbsp;';
 2149:             }
 2150:             $row.='</td><td>';
 2151:             if ($delallowed) {
 2152:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 2153:             } else {
 2154:                 $row.='&nbsp;';
 2155:             }
 2156:             $row.= '</td>';
 2157:         }
 2158:         my $plaintext='';
 2159:         if (!$croletitle) {
 2160:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2161:             if (($showcredits) && ($credits ne '')) {
 2162:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2163:                               '<span class="LC_fontsize_small">'.
 2164:                               &mt('Credits: [_1]',$credits).
 2165:                               '</span></span>';
 2166:             }
 2167:         } else {
 2168:             $plaintext=
 2169:                 &mt('Custom role [_1][_2]defined by [_3]',
 2170:                         '"'.$croletitle.'"',
 2171:                         '<br />',
 2172:                         $croleuname.':'.$croleudom);
 2173:         }
 2174:         $row.= '<td>'.$plaintext.'</td>'.
 2175:                '<td>'.$area.'</td>'.
 2176:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2177:                                             : '&nbsp;' ).'</td>'.
 2178:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2179:                                             : '&nbsp;' ).'</td>';
 2180:         $sortrole{$sortkey}=$envkey;
 2181:         $roletext{$envkey}=$row;
 2182:         $roleclass{$envkey}=$class;
 2183:         if ($allowed) {
 2184:             $rolepriv{$envkey}='edit';
 2185:         } else {
 2186:             if ($context eq 'domain') {
 2187:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2188:                     ($envkey=~m{^/$ccdomain/})) {
 2189:                     $rolepriv{$envkey}='view';
 2190:                 }
 2191:             } elsif ($context eq 'course') {
 2192:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2193:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2194:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2195:                     $rolepriv{$envkey}='view';
 2196:                 }
 2197:             }
 2198:         }
 2199:     } # end of foreach        (table building loop)
 2200: 
 2201:     my $rolesdisplay = 0;
 2202:     my %output = ();
 2203:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2204:         $output{$type} = '';
 2205:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2206:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2207:                  $output{$type}.=
 2208:                       &Apache::loncommon::start_data_table_row().
 2209:                       $roletext{$sortrole{$which}}.
 2210:                       &Apache::loncommon::end_data_table_row();
 2211:             }
 2212:         }
 2213:         unless($output{$type} eq '') {
 2214:             $output{$type} = '<tr class="LC_info_row">'.
 2215:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2216:                       $output{$type};
 2217:             $rolesdisplay = 1;
 2218:         }
 2219:     }
 2220:     if ($rolesdisplay == 1) {
 2221:         my $contextrole='';
 2222:         if ($env{'request.course.id'}) {
 2223:             if (&Apache::loncommon::course_type() eq 'Community') {
 2224:                 $contextrole = &mt('Existing Roles in this Community');
 2225:             } else {
 2226:                 $contextrole = &mt('Existing Roles in this Course');
 2227:             }
 2228:         } elsif ($env{'request.role'} =~ /^au\./) {
 2229:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2230:         } else {
 2231:             if ($showall) {
 2232:                 $contextrole = &mt('Existing Roles in this Domain');
 2233:             } elsif ($showactive) {
 2234:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2235:             } elsif ($showexpired) {
 2236:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2237:             }
 2238:         }
 2239:         $r->print('<div class="LC_left_float">'.
 2240: '<fieldset><legend>'.$contextrole.'</legend>'.
 2241: &Apache::loncommon::start_data_table("LC_createuser").
 2242: &Apache::loncommon::start_data_table_header_row());
 2243:         if ($showall) {
 2244:             $r->print(
 2245: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2246:             );
 2247:         } elsif ($showexpired) {
 2248:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2249:         }
 2250:         $r->print(
 2251: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2252: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2253: &Apache::loncommon::end_data_table_header_row());
 2254:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2255:             if ($output{$type}) {
 2256:                 $r->print($output{$type}."\n");
 2257:             }
 2258:         }
 2259:         $r->print(&Apache::loncommon::end_data_table().
 2260:                   '</fieldset></div>');
 2261:     }
 2262:     return;
 2263: }
 2264: 
 2265: sub new_coauthor_roles {
 2266:     my ($r,$ccuname,$ccdomain) = @_;
 2267:     my $addrolesdisplay = 0;
 2268:     #
 2269:     # Co-Author
 2270:     #
 2271:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2272:                                           $env{'request.role.domain'}) &&
 2273:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2274:         # No sense in assigning co-author role to yourself
 2275:         $addrolesdisplay = 1;
 2276:         my $cuname=$env{'user.name'};
 2277:         my $cudom=$env{'request.role.domain'};
 2278:         my %lt=&Apache::lonlocal::texthash(
 2279:                     'cs'   => "Authoring Space",
 2280:                     'act'  => "Activate",
 2281:                     'rol'  => "Role",
 2282:                     'ext'  => "Extent",
 2283:                     'sta'  => "Start",
 2284:                     'end'  => "End",
 2285:                     'cau'  => "Co-Author",
 2286:                     'caa'  => "Assistant Co-Author",
 2287:                     'ssd'  => "Set Start Date",
 2288:                     'sed'  => "Set End Date"
 2289:                                        );
 2290:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2291:                   &Apache::loncommon::start_data_table()."\n".
 2292:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2293:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2294:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2295:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2296:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2297:                   &Apache::loncommon::start_data_table_row().'
 2298:            <td>
 2299:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2300:            </td>
 2301:            <td>'.$lt{'cau'}.'</td>
 2302:            <td>'.$cudom.'_'.$cuname.'</td>
 2303:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2304:              <a href=
 2305: "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>
 2306: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2307: <a href=
 2308: "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".
 2309:               &Apache::loncommon::end_data_table_row()."\n".
 2310:               &Apache::loncommon::start_data_table_row()."\n".
 2311: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2312: <td>'.$lt{'caa'}.'</td>
 2313: <td>'.$cudom.'_'.$cuname.'</td>
 2314: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2315: <a href=
 2316: "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>
 2317: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2318: <a href=
 2319: "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".
 2320:              &Apache::loncommon::end_data_table_row()."\n".
 2321:              &Apache::loncommon::end_data_table());
 2322:     } elsif ($env{'request.role'} =~ /^au\./) {
 2323:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2324:                                                 $env{'request.role.domain'}))) {
 2325:             $r->print('<span class="LC_error">'.
 2326:                       &mt('You do not have privileges to assign co-author roles.').
 2327:                       '</span>');
 2328:         } elsif (($env{'user.name'} eq $ccuname) &&
 2329:              ($env{'user.domain'} eq $ccdomain)) {
 2330:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2331:         }
 2332:     }
 2333:     return $addrolesdisplay;;
 2334: }
 2335: 
 2336: sub new_domain_roles {
 2337:     my ($r,$ccdomain) = @_;
 2338:     my $addrolesdisplay = 0;
 2339:     #
 2340:     # Domain level
 2341:     #
 2342:     my $num_domain_level = 0;
 2343:     my $domaintext =
 2344:     '<h4>'.&mt('Domain Level').'</h4>'.
 2345:     &Apache::loncommon::start_data_table().
 2346:     &Apache::loncommon::start_data_table_header_row().
 2347:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2348:     &mt('Extent').'</th>'.
 2349:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2350:     &Apache::loncommon::end_data_table_header_row();
 2351:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2352:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2353:         foreach my $role (@allroles) {
 2354:             next if ($role eq 'ad');
 2355:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2356:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2357:                my $plrole=&Apache::lonnet::plaintext($role);
 2358:                my %lt=&Apache::lonlocal::texthash(
 2359:                     'ssd'  => "Set Start Date",
 2360:                     'sed'  => "Set End Date"
 2361:                                        );
 2362:                $num_domain_level ++;
 2363:                $domaintext .=
 2364: &Apache::loncommon::start_data_table_row().
 2365: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2366: <td>'.$plrole.'</td>
 2367: <td>'.$thisdomain.'</td>
 2368: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2369: <a href=
 2370: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2371: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2372: <a href=
 2373: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2374: &Apache::loncommon::end_data_table_row();
 2375:             }
 2376:         }
 2377:     }
 2378:     $domaintext.= &Apache::loncommon::end_data_table();
 2379:     if ($num_domain_level > 0) {
 2380:         $r->print($domaintext);
 2381:         $addrolesdisplay = 1;
 2382:     }
 2383:     return $addrolesdisplay;
 2384: }
 2385: 
 2386: sub user_authentication {
 2387:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2388:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2389:     my $outcome;
 2390:     my %lt=&Apache::lonlocal::texthash(
 2391:                    'err'   => "ERROR",
 2392:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2393:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2394:                    'sldb'  => "Please specify login data below",
 2395:                    'ld'    => "Login Data"
 2396:     );
 2397:     # Check for a bad authentication type
 2398:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
 2399:         # bad authentication scheme
 2400:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2401:             &initialize_authen_forms($ccdomain,$formname);
 2402: 
 2403:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2404:             $outcome = <<ENDBADAUTH;
 2405: <script type="text/javascript" language="Javascript">
 2406: // <![CDATA[
 2407: $loginscript
 2408: // ]]>
 2409: </script>
 2410: <span class="LC_error">$lt{'err'}:
 2411: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2412: <h3>$lt{'ld'}</h3>
 2413: $choices
 2414: ENDBADAUTH
 2415:         } else {
 2416:             # This user is not allowed to modify the user's
 2417:             # authentication scheme, so just notify them of the problem
 2418:             $outcome = <<ENDBADAUTH;
 2419: <span class="LC_error"> $lt{'err'}: 
 2420: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2421: </span>
 2422: ENDBADAUTH
 2423:         }
 2424:     } else { # Authentication type is valid
 2425:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2426:         my ($authformcurrent,$can_modify,@authform_others) =
 2427:             &modify_login_block($ccdomain,$currentauth);
 2428:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2429:             # Current user has login modification privileges
 2430:             $outcome =
 2431:                        '<script type="text/javascript" language="Javascript">'."\n".
 2432:                        '// <![CDATA['."\n".
 2433:                        $loginscript."\n".
 2434:                        '// ]]>'."\n".
 2435:                        '</script>'."\n".
 2436:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2437:                        &Apache::loncommon::start_data_table().
 2438:                        &Apache::loncommon::start_data_table_row().
 2439:                        '<td>'.$authformnop;
 2440:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2441:                 $outcome .= '</td>'."\n".
 2442:                             &Apache::loncommon::end_data_table_row().
 2443:                             &Apache::loncommon::start_data_table_row().
 2444:                             '<td>'.$authformcurrent.'</td>'.
 2445:                             &Apache::loncommon::end_data_table_row()."\n";
 2446:             } else {
 2447:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2448:                             &Apache::loncommon::end_data_table_row()."\n";
 2449:             }
 2450:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2451:                 foreach my $item (@authform_others) { 
 2452:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2453:                                 '<td>'.$item.'</td>'.
 2454:                                 &Apache::loncommon::end_data_table_row()."\n";
 2455:                 }
 2456:             }
 2457:             $outcome .= &Apache::loncommon::end_data_table();
 2458:         } else {
 2459:             if (($currentauth =~ /^internal:/) &&
 2460:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2461:                 $outcome = <<"ENDJS";
 2462: <script type="text/javascript">
 2463: // <![CDATA[
 2464: function togglePwd(form) {
 2465:     if (form.newintpwd.length) {
 2466:         if (document.getElementById('LC_ownersetpwd')) {
 2467:             for (var i=0; i<form.newintpwd.length; i++) {
 2468:                 if (form.newintpwd[i].checked) {
 2469:                     if (form.newintpwd[i].value == 1) {
 2470:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2471:                     } else {
 2472:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2473:                     }
 2474:                 }
 2475:             }
 2476:         }
 2477:     }
 2478: }
 2479: // ]]>
 2480: </script>
 2481: ENDJS
 2482: 
 2483:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2484:                             &Apache::loncommon::start_data_table().
 2485:                             &Apache::loncommon::start_data_table_row().
 2486:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2487:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2488:                             &mt('No').'</label>'.('&nbsp;'x2).
 2489:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2490:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2491:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2492:                             '<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></div></td>'.
 2493:                             &Apache::loncommon::end_data_table_row().
 2494:                             &Apache::loncommon::end_data_table();
 2495:             }
 2496:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2497:                 # Current user has rights to view domain preferences for user's domain
 2498:                 my $result;
 2499:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2500:                     my ($krbver,$krbrealm) = ($1,$2);
 2501:                     if ($krbrealm eq '') {
 2502:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2503:                     } else {
 2504:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2505:                                       $krbrealm,$krbver);
 2506:                     }
 2507:                 } elsif ($currentauth =~ /^internal:/) {
 2508:                     $result = &mt('Currently internally authenticated.');
 2509:                 } elsif ($currentauth =~ /^localauth:/) {
 2510:                     $result = &mt('Currently using local (institutional) authentication.');
 2511:                 } elsif ($currentauth =~ /^unix:/) {
 2512:                     $result = &mt('Currently Filesystem Authenticated.');
 2513:                 }
 2514:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2515:                            &Apache::loncommon::start_data_table().
 2516:                            &Apache::loncommon::start_data_table_row().
 2517:                            '<td>'.$result.'</td>'.
 2518:                            &Apache::loncommon::end_data_table_row()."\n".
 2519:                            &Apache::loncommon::end_data_table();
 2520:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2521:                 my %lt=&Apache::lonlocal::texthash(
 2522:                            'ccld'  => "Change Current Login Data",
 2523:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2524:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2525:                 );
 2526:                 $outcome .= <<ENDNOPRIV;
 2527: <h3>$lt{'ccld'}</h3>
 2528: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2529: <input type="hidden" name="login" value="nochange" />
 2530: ENDNOPRIV
 2531:             }
 2532:         }
 2533:     }  ## End of "check for bad authentication type" logic
 2534:     return $outcome;
 2535: }
 2536: 
 2537: sub modify_login_block {
 2538:     my ($dom,$currentauth) = @_;
 2539:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2540:     my ($authnum,%can_assign) =
 2541:         &Apache::loncommon::get_assignable_auth($dom);
 2542:     my ($authformcurrent,@authform_others,$show_override_msg);
 2543:     if ($currentauth=~/^krb(4|5):/) {
 2544:         $authformcurrent=$authformkrb;
 2545:         if ($can_assign{'int'}) {
 2546:             push(@authform_others,$authformint);
 2547:         }
 2548:         if ($can_assign{'loc'}) {
 2549:             push(@authform_others,$authformloc);
 2550:         }
 2551:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2552:             $show_override_msg = 1;
 2553:         }
 2554:     } elsif ($currentauth=~/^internal:/) {
 2555:         $authformcurrent=$authformint;
 2556:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2557:             push(@authform_others,$authformkrb);
 2558:         }
 2559:         if ($can_assign{'loc'}) {
 2560:             push(@authform_others,$authformloc);
 2561:         }
 2562:         if ($can_assign{'int'}) {
 2563:             $show_override_msg = 1;
 2564:         }
 2565:     } elsif ($currentauth=~/^unix:/) {
 2566:         $authformcurrent=$authformfsys;
 2567:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2568:             push(@authform_others,$authformkrb);
 2569:         }
 2570:         if ($can_assign{'int'}) {
 2571:             push(@authform_others,$authformint);
 2572:         }
 2573:         if ($can_assign{'loc'}) {
 2574:             push(@authform_others,$authformloc);
 2575:         }
 2576:         if ($can_assign{'fsys'}) {
 2577:             $show_override_msg = 1;
 2578:         }
 2579:     } elsif ($currentauth=~/^localauth:/) {
 2580:         $authformcurrent=$authformloc;
 2581:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2582:             push(@authform_others,$authformkrb);
 2583:         }
 2584:         if ($can_assign{'int'}) {
 2585:             push(@authform_others,$authformint);
 2586:         }
 2587:         if ($can_assign{'loc'}) {
 2588:             $show_override_msg = 1;
 2589:         }
 2590:     }
 2591:     if ($show_override_msg) {
 2592:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2593:                            '</td></tr>'."\n".
 2594:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2595:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2596:                            '<td align="right"><span class="LC_cusr_emph">'.
 2597:                             &mt('will override current values').
 2598:                             '</span></td></tr></table>';
 2599:     }
 2600:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2601: }
 2602: 
 2603: sub personal_data_display {
 2604:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,$now,
 2605:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2606:     my ($output,%userenv,%canmodify,%canmodify_status);
 2607:     my @userinfo = ('firstname','middlename','lastname','generation',
 2608:                     'permanentemail','id');
 2609:     my $rowcount = 0;
 2610:     my $editable = 0;
 2611:     my %textboxsize = (
 2612:                        firstname      => '15',
 2613:                        middlename     => '15',
 2614:                        lastname       => '15',
 2615:                        generation     => '5',
 2616:                        permanentemail => '25',
 2617:                        id             => '15',
 2618:                       );
 2619: 
 2620:     my %lt=&Apache::lonlocal::texthash(
 2621:                 'pd'             => "Personal Data",
 2622:                 'firstname'      => "First Name",
 2623:                 'middlename'     => "Middle Name",
 2624:                 'lastname'       => "Last Name",
 2625:                 'generation'     => "Generation",
 2626:                 'permanentemail' => "Permanent e-mail address",
 2627:                 'id'             => "Student/Employee ID",
 2628:                 'lg'             => "Login Data",
 2629:                 'inststatus'     => "Affiliation",
 2630:                 'email'          => 'E-mail address',
 2631:                 'valid'          => 'Validation',
 2632:                 'username'       => 'Username',
 2633:     );
 2634: 
 2635:     %canmodify_status =
 2636:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2637:                                                    ['inststatus'],$rolesarray);
 2638:     if (!$newuser) {
 2639:         # Get the users information
 2640:         %userenv = &Apache::lonnet::get('environment',
 2641:                    ['firstname','middlename','lastname','generation',
 2642:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2643:         %canmodify =
 2644:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2645:                                                        \@userinfo,$rolesarray);
 2646:     } elsif ($context eq 'selfcreate') {
 2647:         if ($newuser eq 'email') {
 2648:             if (ref($emailusername) eq 'HASH') {
 2649:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2650:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2651:                     @userinfo = ();
 2652:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2653:                         foreach my $field (@{$infofields}) { 
 2654:                             if ($emailusername->{$usertype}->{$field}) {
 2655:                                 push(@userinfo,$field);
 2656:                                 $canmodify{$field} = 1;
 2657:                                 unless ($textboxsize{$field}) {
 2658:                                     $textboxsize{$field} = 25;
 2659:                                 }
 2660:                                 unless ($lt{$field}) {
 2661:                                     $lt{$field} = $infotitles->{$field};
 2662:                                 }
 2663:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2664:                                     $lt{$field} .= '<b>*</b>';
 2665:                                 }
 2666:                             }
 2667:                         }
 2668:                     }
 2669:                 }
 2670:             }
 2671:         } else {
 2672:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2673:                                                $inst_results,$rolesarray);
 2674:         }
 2675:     }
 2676: 
 2677:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2678:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2679:               &Apache::lonhtmlcommon::start_pick_box();
 2680:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2681:         my $size = 25;
 2682:         if ($condition) {
 2683:             if ($condition =~ /^\@[^\@]+$/) {
 2684:                 $size = 10;
 2685:             } else {
 2686:                 undef($condition);
 2687:             }
 2688:         }
 2689:         if ($excluded) {
 2690:             unless ($excluded =~ /^\@[^\@]+$/) {
 2691:                 undef($condition);
 2692:             }
 2693:         }
 2694:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2695:                                                      'LC_oddrow_value')."\n".
 2696:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2697:         if ($condition) {
 2698:             $output .= $condition;
 2699:         } elsif ($excluded) {
 2700:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2701:                                                                      $excluded).'</span>';
 2702:         }
 2703:         if ($usernameset eq 'first') {
 2704:             $output .= '<br /><span style="font-size: smaller">';
 2705:             if ($condition) {
 2706:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2707:                                       $condition);
 2708:             } else {
 2709:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2710:             }
 2711:             $output .= '</span>';
 2712:         }
 2713:         $rowcount ++;
 2714:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2715:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2716:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2717:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2718:                                                     'LC_pick_box_title',
 2719:                                                     'LC_oddrow_value')."\n".
 2720:                    $upassone."\n".
 2721:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2722:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2723:                                                      'LC_pick_box_title',
 2724:                                                      'LC_oddrow_value')."\n".
 2725:                    $upasstwo.
 2726:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2727:         if ($usernameset eq 'free') {
 2728:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');";
 2729:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2730:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2731:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2732:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2733:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2734:                        &mt('No').'</label></span>'."\n".
 2735:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2736:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2737:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2738:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2739:             $rowcount ++;
 2740:         }
 2741:     }
 2742:     foreach my $item (@userinfo) {
 2743:         my $rowtitle = $lt{$item};
 2744:         my $hiderow = 0;
 2745:         if ($item eq 'generation') {
 2746:             $rowtitle = $genhelp.$rowtitle;
 2747:         }
 2748:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2749:         if ($newuser) {
 2750:             if (ref($inst_results) eq 'HASH') {
 2751:                 if ($inst_results->{$item} ne '') {
 2752:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2753:                 } else {
 2754:                     if ($context eq 'selfcreate') {
 2755:                         if ($canmodify{$item}) {
 2756:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2757:                             $editable ++;
 2758:                         } else {
 2759:                             $hiderow = 1;
 2760:                         }
 2761:                     } else {
 2762:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2763:                     }
 2764:                 }
 2765:             } else {
 2766:                 if ($context eq 'selfcreate') {
 2767:                     if ($canmodify{$item}) {
 2768:                         if ($newuser eq 'email') {
 2769:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2770:                         } else {
 2771:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2772:                         }
 2773:                         $editable ++;
 2774:                     } else {
 2775:                         $hiderow = 1;
 2776:                     }
 2777:                 } else {
 2778:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2779:                 }
 2780:             }
 2781:         } else {
 2782:             if ($canmodify{$item}) {
 2783:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2784:                 if (($item eq 'id') && (!$newuser)) {
 2785:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2786:                 }
 2787:             } else {
 2788:                 $row .= $userenv{$item};
 2789:             }
 2790:         }
 2791:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2792:         if (!$hiderow) {
 2793:             $output .= $row;
 2794:             $rowcount ++;
 2795:         }
 2796:     }
 2797:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2798:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2799:         if (ref($types) eq 'ARRAY') {
 2800:             if (@{$types} > 0) {
 2801:                 my ($hiderow,$shown);
 2802:                 if ($canmodify_status{'inststatus'}) {
 2803:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2804:                 } else {
 2805:                     if ($userenv{'inststatus'} eq '') {
 2806:                         $hiderow = 1;
 2807:                     } else {
 2808:                         my @showitems;
 2809:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2810:                             if (exists($usertypes->{$item})) {
 2811:                                 push(@showitems,$usertypes->{$item});
 2812:                             } else {
 2813:                                 push(@showitems,$item);
 2814:                             }
 2815:                         }
 2816:                         if (@showitems) {
 2817:                             $shown = join(', ',@showitems);
 2818:                         } else {
 2819:                             $hiderow = 1;
 2820:                         }
 2821:                     }
 2822:                 }
 2823:                 if (!$hiderow) {
 2824:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2825:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2826:                     if ($context eq 'selfcreate') {
 2827:                         $rowcount ++;
 2828:                     }
 2829:                     $output .= $row;
 2830:                 }
 2831:             }
 2832:         }
 2833:     }
 2834:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2835:         if ($captchaform) {
 2836:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2837:                                                          'LC_pick_box_title')."\n".
 2838:                        $captchaform."\n".'<br /><br />'.
 2839:                        &Apache::lonhtmlcommon::row_closure(1); 
 2840:             $rowcount ++;
 2841:         }
 2842:         if ($showsubmit) {
 2843:             my $submit_text = &mt('Create account');
 2844:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2845:                        '<br /><input type="submit" name="createaccount" value="'.
 2846:                        $submit_text.'" />';
 2847:             if ($usertype ne '') {
 2848:                 $output .= '<input type="hidden" name="type" value="'.
 2849:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 2850:             }
 2851:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 2852:         }
 2853:     }
 2854:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2855:     if (wantarray) {
 2856:         if ($context eq 'selfcreate') {
 2857:             return($output,$rowcount,$editable);
 2858:         } else {
 2859:             return $output;
 2860:         }
 2861:     } else {
 2862:         return $output;
 2863:     }
 2864: }
 2865: 
 2866: sub pick_inst_statuses {
 2867:     my ($curr,$usertypes,$types) = @_;
 2868:     my ($output,$rem,@currtypes);
 2869:     if ($curr ne '') {
 2870:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2871:     }
 2872:     my $numinrow = 2;
 2873:     if (ref($types) eq 'ARRAY') {
 2874:         $output = '<table>';
 2875:         my $lastcolspan; 
 2876:         for (my $i=0; $i<@{$types}; $i++) {
 2877:             if (defined($usertypes->{$types->[$i]})) {
 2878:                 my $rem = $i%($numinrow);
 2879:                 if ($rem == 0) {
 2880:                     if ($i<@{$types}-1) {
 2881:                         if ($i > 0) { 
 2882:                             $output .= '</tr>';
 2883:                         }
 2884:                         $output .= '<tr>';
 2885:                     }
 2886:                 } elsif ($i==@{$types}-1) {
 2887:                     my $colsleft = $numinrow - $rem;
 2888:                     if ($colsleft > 1) {
 2889:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2890:                     }
 2891:                 }
 2892:                 my $check = ' ';
 2893:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2894:                     $check = ' checked="checked" ';
 2895:                 }
 2896:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2897:                            '<span class="LC_nobreak"><label>'.
 2898:                            '<input type="checkbox" name="inststatus" '.
 2899:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2900:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2901:             }
 2902:         }
 2903:         $output .= '</tr></table>';
 2904:     }
 2905:     return $output;
 2906: }
 2907: 
 2908: sub selfcreate_canmodify {
 2909:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2910:     if (ref($inst_results) eq 'HASH') {
 2911:         my @inststatuses = &get_inststatuses($inst_results);
 2912:         if (@inststatuses == 0) {
 2913:             @inststatuses = ('default');
 2914:         }
 2915:         $rolesarray = \@inststatuses;
 2916:     }
 2917:     my %canmodify =
 2918:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2919:                                                    $rolesarray);
 2920:     return %canmodify;
 2921: }
 2922: 
 2923: sub get_inststatuses {
 2924:     my ($insthashref) = @_;
 2925:     my @inststatuses = ();
 2926:     if (ref($insthashref) eq 'HASH') {
 2927:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2928:             @inststatuses = @{$insthashref->{'inststatus'}};
 2929:         }
 2930:     }
 2931:     return @inststatuses;
 2932: }
 2933: 
 2934: # ================================================================= Phase Three
 2935: sub update_user_data {
 2936:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 2937:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2938:                                           $env{'form.ccdomain'});
 2939:     # Error messages
 2940:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2941:     my $end       = '</span><br /><br />';
 2942:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2943:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2944:                     &mt('Return to previous page').'</a>'.
 2945:                     &Apache::loncommon::end_page();
 2946:     my $now = time;
 2947:     my $title;
 2948:     if (exists($env{'form.makeuser'})) {
 2949: 	$title='Set Privileges for New User';
 2950:     } else {
 2951:         $title='Modify User Privileges';
 2952:     }
 2953:     my $newuser = 0;
 2954:     my ($jsback,$elements) = &crumb_utilities();
 2955:     my $jscript = '<script type="text/javascript">'."\n".
 2956:                   '// <![CDATA['."\n".
 2957:                   $jsback."\n".
 2958:                   '// ]]>'."\n".
 2959:                   '</script>'."\n";
 2960:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2961:     push (@{$brcrum},
 2962:              {href => "javascript:backPage(document.userupdate)",
 2963:               text => $breadcrumb_text{'search'},
 2964:               faq  => 282,
 2965:               bug  => 'Instructor Interface',}
 2966:              );
 2967:     if ($env{'form.prevphase'} eq 'userpicked') {
 2968:         push(@{$brcrum},
 2969:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2970:                 text => $breadcrumb_text{'userpicked'},
 2971:                 faq  => 282,
 2972:                 bug  => 'Instructor Interface',});
 2973:     }
 2974:     my $helpitem = 'Course_Change_Privileges';
 2975:     if ($env{'form.action'} eq 'singlestudent') {
 2976:         $helpitem = 'Course_Add_Student';
 2977:     } elsif ($context eq 'author') {
 2978:         $helpitem = 'Author_Change_Privileges';
 2979:     } elsif ($context eq 'domain') {
 2980:         $helpitem = 'Domain_Change_Privileges';
 2981:     }
 2982:     push(@{$brcrum}, 
 2983:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2984:              text => $breadcrumb_text{'modify'},
 2985:              faq  => 282,
 2986:              bug  => 'Instructor Interface',},
 2987:             {href => "/adm/createuser",
 2988:              text => "Result",
 2989:              faq  => 282,
 2990:              bug  => 'Instructor Interface',
 2991:              help => $helpitem});
 2992:     my $args = {bread_crumbs          => $brcrum,
 2993:                 bread_crumbs_component => 'User Management'};
 2994:     if ($env{'form.popup'}) {
 2995:         $args->{'no_nav_bar'} = 1;
 2996:     }
 2997:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2998:     $r->print(&update_result_form($uhome));
 2999:     # Check Inputs
 3000:     if (! $env{'form.ccuname'} ) {
 3001: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 3002: 	return;
 3003:     }
 3004:     if (  $env{'form.ccuname'} ne 
 3005: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 3006: 	$r->print($error.&mt('Invalid login name.').'  '.
 3007: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 3008: 		  $end.$rtnlink);
 3009: 	return;
 3010:     }
 3011:     if (! $env{'form.ccdomain'}       ) {
 3012: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 3013: 	return;
 3014:     }
 3015:     if (  $env{'form.ccdomain'} ne
 3016: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 3017: 	$r->print($error.&mt('Invalid domain name.').'  '.
 3018: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 3019: 		  $end.$rtnlink);
 3020: 	return;
 3021:     }
 3022:     if ($uhome eq 'no_host') {
 3023:         $newuser = 1;
 3024:     }
 3025:     if (! exists($env{'form.makeuser'})) {
 3026:         # Modifying an existing user, so check the validity of the name
 3027:         if ($uhome eq 'no_host') {
 3028:             $r->print(
 3029:                 $error
 3030:                .'<p class="LC_error">'
 3031:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 3032:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 3033:                .'</p>');
 3034:             return;
 3035:         }
 3036:     }
 3037:     # Determine authentication method and password for the user being modified
 3038:     my $amode='';
 3039:     my $genpwd='';
 3040:     if ($env{'form.login'} eq 'krb') {
 3041: 	$amode='krb';
 3042: 	$amode.=$env{'form.krbver'};
 3043: 	$genpwd=$env{'form.krbarg'};
 3044:     } elsif ($env{'form.login'} eq 'int') {
 3045: 	$amode='internal';
 3046: 	$genpwd=$env{'form.intarg'};
 3047:     } elsif ($env{'form.login'} eq 'fsys') {
 3048: 	$amode='unix';
 3049: 	$genpwd=$env{'form.fsysarg'};
 3050:     } elsif ($env{'form.login'} eq 'loc') {
 3051: 	$amode='localauth';
 3052: 	$genpwd=$env{'form.locarg'};
 3053: 	$genpwd=" " if (!$genpwd);
 3054:     } elsif (($env{'form.login'} eq 'nochange') ||
 3055:              ($env{'form.login'} eq ''        )) { 
 3056:         # There is no need to tell the user we did not change what they
 3057:         # did not ask us to change.
 3058:         # If they are creating a new user but have not specified login
 3059:         # information this will be caught below.
 3060:     } else {
 3061:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 3062:             return;
 3063:     }
 3064: 
 3065:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 3066:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 3067:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 3068:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 3069: 
 3070:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 3071:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3072:     my @usertools = ('aboutme','blog','portfolio','timezone');
 3073:     my @requestcourses = ('official','unofficial','community','textbook');
 3074:     my @requestauthor = ('requestauthor');
 3075:     my @authordefaults = ('webdav','editors');
 3076:     my ($othertitle,$usertypes,$types) = 
 3077:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 3078:     my %canmodify_status =
 3079:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 3080:                                                    ['inststatus']);
 3081:     if ($env{'form.makeuser'}) {
 3082: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 3083:         # Check for the authentication mode and password
 3084:         if (! $amode || ! $genpwd) {
 3085: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 3086: 	    return;
 3087: 	}
 3088:         # Determine desired host
 3089:         my $desiredhost = $env{'form.hserver'};
 3090:         if (lc($desiredhost) eq 'default') {
 3091:             $desiredhost = undef;
 3092:         } else {
 3093:             my %home_servers = 
 3094: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 3095:             if (! exists($home_servers{$desiredhost})) {
 3096:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 3097:                 return;
 3098:             }
 3099:         }
 3100:         # Check ID format
 3101:         my %checkhash;
 3102:         my %checks = ('id' => 1);
 3103:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 3104:             'newuser' => $newuser, 
 3105:             'id' => $env{'form.cid'},
 3106:         );
 3107:         if ($env{'form.cid'} ne '') {
 3108:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 3109:                                           \%rulematch,\%inst_results,\%curr_rules);
 3110:             if (ref($alerts{'id'}) eq 'HASH') {
 3111:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3112:                     my $domdesc =
 3113:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 3114:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 3115:                         my $userchkmsg;
 3116:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 3117:                             $userchkmsg  = 
 3118:                                 &Apache::loncommon::instrule_disallow_msg('id',
 3119:                                                                     $domdesc,1).
 3120:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 3121:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 3122:                         }
 3123:                         $r->print($error.&mt('Invalid ID format').$end.
 3124:                                   $userchkmsg.$rtnlink);
 3125:                         return;
 3126:                     }
 3127:                 }
 3128:             }
 3129:         }
 3130:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 3131: 	# Call modifyuser
 3132: 	my $result = &Apache::lonnet::modifyuser
 3133: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 3134:              $amode,$genpwd,$env{'form.cfirstname'},
 3135:              $env{'form.cmiddlename'},$env{'form.clastname'},
 3136:              $env{'form.cgeneration'},undef,$desiredhost,
 3137:              $env{'form.cpermanentemail'});
 3138: 	$r->print(&mt('Generating user').': '.$result);
 3139:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 3140:                                                $env{'form.ccdomain'});
 3141:         my (%changeHash,%newcustom,%changed,%changedinfo);
 3142:         if ($uhome ne 'no_host') {
 3143:             if ($context eq 'domain') {
 3144:                 foreach my $name ('portfolio','author') {
 3145:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3146:                         if ($env{'form.'.$name.'quota'} eq '') {
 3147:                             $newcustom{$name.'quota'} = 0;
 3148:                         } else {
 3149:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 3150:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 3151:                         }
 3152:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 3153:                             $changed{$name.'quota'} = 1;
 3154:                         }
 3155:                     }
 3156:                 }
 3157:                 foreach my $item (@usertools) {
 3158:                     if ($env{'form.custom'.$item} == 1) {
 3159:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3160:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3161:                                                      \%changeHash,'tools');
 3162:                     }
 3163:                 }
 3164:                 foreach my $item (@requestcourses) {
 3165:                     if ($env{'form.custom'.$item} == 1) {
 3166:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3167:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3168:                             $newcustom{$item} .= '=';
 3169:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3170:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3171:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3172:                             }
 3173:                         }
 3174:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3175:                                                       \%changeHash,'requestcourses');
 3176:                     }
 3177:                 }
 3178:                 if ($env{'form.customrequestauthor'} == 1) {
 3179:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3180:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3181:                                                     $newcustom{'requestauthor'},
 3182:                                                     \%changeHash,'requestauthor');
 3183:                 }
 3184:                 if ($env{'form.customeditors'} == 1) {
 3185:                     my @editors;
 3186:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 3187:                     if (@posseditors) {
 3188:                         foreach my $editor (@posseditors) {
 3189:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 3190:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 3191:                                     push(@editors,$editor);
 3192:                                 }
 3193:                             }
 3194:                         }
 3195:                     }
 3196:                     if (@editors) {
 3197:                         @editors = sort(@editors);
 3198:                         $changed{'editors'} = &tool_admin('editors',join(',',@editors),
 3199:                                                           \%changeHash,'authordefaults');
 3200:                     }
 3201:                 }
 3202:                 if ($env{'form.customwebdav'} == 1) {
 3203:                     $newcustom{'webdav'} = $env{'form.authordefaults_webdav'};
 3204:                     $changed{'webdav'} = &tool_admin('webdav',$newcustom{'webdav'},
 3205:                                                   \%changeHash,'authordefaults');
 3206:                 }
 3207:             }
 3208:             if ($canmodify_status{'inststatus'}) {
 3209:                 if (exists($env{'form.inststatus'})) {
 3210:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3211:                     if (@inststatuses > 0) {
 3212:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3213:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3214:                     }
 3215:                 }
 3216:             }
 3217:             if (keys(%changed)) {
 3218:                 foreach my $item (@userinfo) {
 3219:                     $changeHash{$item}  = $env{'form.c'.$item};
 3220:                 }
 3221:                 my $chgresult =
 3222:                      &Apache::lonnet::put('environment',\%changeHash,
 3223:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3224:             } 
 3225:         }
 3226:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3227:                   &Apache::lonnet::hostname($uhome));
 3228:     } elsif (($env{'form.login'} ne 'nochange') &&
 3229:              ($env{'form.login'} ne ''        )) {
 3230: 	# Modify user privileges
 3231:         if (! $amode || ! $genpwd) {
 3232: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3233: 	    return;
 3234: 	}
 3235: 	# Only allow authentication modification if the person has authority
 3236: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3237: 	    $r->print('Modifying authentication: '.
 3238:                       &Apache::lonnet::modifyuserauth(
 3239: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3240:                        $amode,$genpwd));
 3241:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3242: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3243: 	} else {
 3244: 	    # Okay, this is a non-fatal error.
 3245: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);    
 3246: 	}
 3247:     } elsif (($env{'form.intarg'} ne '') &&
 3248:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3249:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3250:         $r->print('Modifying authentication: '.
 3251:                   &Apache::lonnet::modifyuserauth(
 3252:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3253:                   'internal',$env{'form.intarg'}));
 3254:     }
 3255:     $r->rflush(); # Finish display of header before time consuming actions start
 3256:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3257:     ##
 3258:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3259:     if ($context eq 'course') {
 3260:         ($cnum,$cdom) =
 3261:             &Apache::lonuserutils::get_course_identity();
 3262:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3263:         if ($showcredits) {
 3264:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3265:         }
 3266:     }
 3267:     if (! $env{'form.makeuser'} ) {
 3268:         # Check for need to change
 3269:         my %userenv = &Apache::lonnet::get
 3270:             ('environment',['firstname','middlename','lastname','generation',
 3271:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3272:              'tools.aboutme','tools.blog','tools.webdav',
 3273:              'tools.portfolio','tools.timezone',
 3274:              'authoreditors','requestauthor',
 3275:              'requestcourses.official','requestcourses.unofficial',
 3276:              'requestcourses.community','requestcourses.textbook',
 3277:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3278:              'reqcrsotherdom.community','reqcrsotherdom.textbook'],
 3279:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3280:         my ($tmp) = keys(%userenv);
 3281:         if ($tmp =~ /^(con_lost|error)/i) { 
 3282:             %userenv = ();
 3283:         }
 3284:         my $no_forceid_alert;
 3285:         # Check to see if user information can be changed
 3286:         my %domconfig =
 3287:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3288:                                      $env{'form.ccdomain'});
 3289:         my @statuses = ('active','future');
 3290:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3291:         my ($auname,$audom);
 3292:         if ($context eq 'author') {
 3293:             $auname = $env{'user.name'};
 3294:             $audom = $env{'user.domain'};     
 3295:         }
 3296:         foreach my $item (keys(%roles)) {
 3297:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3298:             if ($context eq 'course') {
 3299:                 if ($cnum ne '' && $cdom ne '') {
 3300:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3301:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3302:                             push(@userroles,$role);
 3303:                         }
 3304:                     }
 3305:                 }
 3306:             } elsif ($context eq 'author') {
 3307:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3308:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3309:                         push(@userroles,$role);
 3310:                     }
 3311:                 }
 3312:             }
 3313:         }
 3314:         if ($env{'form.action'} eq 'singlestudent') {
 3315:             if (!grep(/^st$/,@userroles)) {
 3316:                 push(@userroles,'st');
 3317:             }
 3318:         } else {
 3319:             # Check for course or co-author roles being activated or re-enabled
 3320:             if ($context eq 'author' || $context eq 'course') {
 3321:                 foreach my $key (keys(%env)) {
 3322:                     if ($context eq 'author') {
 3323:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3324:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3325:                                 push(@userroles,$1);
 3326:                             }
 3327:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3328:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3329:                                 push(@userroles,$1);
 3330:                             }
 3331:                         }
 3332:                     } elsif ($context eq 'course') {
 3333:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3334:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3335:                                 push(@userroles,$1);
 3336:                             }
 3337:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3338:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3339:                                 push(@userroles,$1);
 3340:                             }
 3341:                         }
 3342:                     }
 3343:                 }
 3344:             }
 3345:         }
 3346:         #Check to see if we can change personal data for the user 
 3347:         my (@mod_disallowed,@longroles);
 3348:         foreach my $role (@userroles) {
 3349:             if ($role eq 'cr') {
 3350:                 push(@longroles,'Custom');
 3351:             } else {
 3352:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3353:             }
 3354:         }
 3355:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3356:         foreach my $item (@userinfo) {
 3357:             # Strip leading and trailing whitespace
 3358:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3359:             if (!$canmodify{$item}) {
 3360:                 if (defined($env{'form.c'.$item})) {
 3361:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3362:                         push(@mod_disallowed,$item);
 3363:                     }
 3364:                 }
 3365:                 $env{'form.c'.$item} = $userenv{$item};
 3366:             }
 3367:         }
 3368:         # Check to see if we can change the Student/Employee ID
 3369:         my $forceid = $env{'form.forceid'};
 3370:         my $recurseid = $env{'form.recurseid'};
 3371:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3372:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3373:                                             $env{'form.ccuname'});
 3374:         if (($uidhash{$env{'form.ccuname'}}) && 
 3375:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3376:             (!$forceid)) {
 3377:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3378:                 $env{'form.cid'} = $userenv{'id'};
 3379:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3380:                                    .'<br />'
 3381:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3382:                                    .'<br />'."\n";
 3383:             }
 3384:         }
 3385:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3386:             my $checkhash;
 3387:             my $checks = { 'id' => 1 };
 3388:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3389:                    { 'newuser' => $newuser,
 3390:                      'id'  => $env{'form.cid'}, 
 3391:                    };
 3392:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3393:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3394:             if (ref($alerts{'id'}) eq 'HASH') {
 3395:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3396:                    $env{'form.cid'} = $userenv{'id'};
 3397:                 }
 3398:             }
 3399:         }
 3400:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3401:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3402:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3403:             %oldsettingstatus,%newsettingstatus);
 3404:         @disporder = ('inststatus');
 3405:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3406:             push(@disporder,('requestcourses','requestauthor','authordefaults'));
 3407:         } else {
 3408:             push(@disporder,'reqcrsotherdom');
 3409:         }
 3410:         push(@disporder,('quota','tools'));
 3411:         $oldinststatus = $userenv{'inststatus'};
 3412:         foreach my $name ('portfolio','author') {
 3413:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3414:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3415:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3416:         }
 3417:         my %canshow;
 3418:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3419:             $canshow{'quota'} = 1;
 3420:         }
 3421:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3422:             $canshow{'tools'} = 1;
 3423:         }
 3424:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3425:             $canshow{'requestcourses'} = 1;
 3426:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3427:             $canshow{'reqcrsotherdom'} = 1;
 3428:         }
 3429:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3430:             $canshow{'inststatus'} = 1;
 3431:         }
 3432:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3433:             $canshow{'requestauthor'} = 1;
 3434:             $canshow{'authordefaults'} = 1;
 3435:         }
 3436:         my (%changeHash,%changed);
 3437:         if ($oldinststatus eq '') {
 3438:             $oldsettings{'inststatus'} = $othertitle; 
 3439:         } else {
 3440:             if (ref($usertypes) eq 'HASH') {
 3441:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3442:             } else {
 3443:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3444:             }
 3445:         }
 3446:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3447:         if ($canmodify_status{'inststatus'}) {
 3448:             $canshow{'inststatus'} = 1;
 3449:             if (exists($env{'form.inststatus'})) {
 3450:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3451:                 if (@inststatuses > 0) {
 3452:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3453:                     $changeHash{'inststatus'} = $newinststatus;
 3454:                     if ($newinststatus ne $oldinststatus) {
 3455:                         $changed{'inststatus'} = $newinststatus;
 3456:                         foreach my $name ('portfolio','author') {
 3457:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3458:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3459:                         }
 3460:                     }
 3461:                     if (ref($usertypes) eq 'HASH') {
 3462:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3463:                     } else {
 3464:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3465:                     }
 3466:                 }
 3467:             } else {
 3468:                 $newinststatus = '';
 3469:                 $changeHash{'inststatus'} = $newinststatus;
 3470:                 $newsettings{'inststatus'} = $othertitle;
 3471:                 if ($newinststatus ne $oldinststatus) {
 3472:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3473:                     foreach my $name ('portfolio','author') {
 3474:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3475:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3476:                     }
 3477:                 }
 3478:             }
 3479:         } elsif ($context ne 'selfcreate') {
 3480:             $canshow{'inststatus'} = 1;
 3481:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3482:         }
 3483:         foreach my $name ('portfolio','author') {
 3484:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3485:         }
 3486:         if ($context eq 'domain') {
 3487:             foreach my $name ('portfolio','author') {
 3488:                 if ($userenv{$name.'quota'} ne '') {
 3489:                     $oldquota{$name} = $userenv{$name.'quota'};
 3490:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3491:                         if ($env{'form.'.$name.'quota'} eq '') {
 3492:                             $newquota{$name} = 0;
 3493:                         } else {
 3494:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3495:                             $newquota{$name} =~ s/[^\d\.]//g;
 3496:                         }
 3497:                         if ($newquota{$name} != $oldquota{$name}) {
 3498:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3499:                                 $changed{$name.'quota'} = 1;
 3500:                             }
 3501:                         }
 3502:                     } else {
 3503:                         if (&quota_admin('',\%changeHash,$name)) {
 3504:                             $changed{$name.'quota'} = 1;
 3505:                             $newquota{$name} = $newdefquota{$name};
 3506:                             $newisdefault{$name} = 1;
 3507:                         }
 3508:                     }
 3509:                 } else {
 3510:                     $oldisdefault{$name} = 1;
 3511:                     $oldquota{$name} = $olddefquota{$name};
 3512:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3513:                         if ($env{'form.'.$name.'quota'} eq '') {
 3514:                             $newquota{$name} = 0;
 3515:                         } else {
 3516:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3517:                             $newquota{$name} =~ s/[^\d\.]//g;
 3518:                         }
 3519:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3520:                             $changed{$name.'quota'} = 1;
 3521:                         }
 3522:                     } else {
 3523:                         $newquota{$name} = $newdefquota{$name};
 3524:                         $newisdefault{$name} = 1;
 3525:                     }
 3526:                 }
 3527:                 if ($oldisdefault{$name}) {
 3528:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3529:                 }  else {
 3530:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3531:                 }
 3532:                 if ($newisdefault{$name}) {
 3533:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3534:                 } else {
 3535:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3536:                 }
 3537:             }
 3538:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3539:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3540:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3541:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3542:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3543:                 my ($isadv,$isauthor) =
 3544:                     &Apache::lonnet::is_advanced_user($env{'form.ccdomain'},$env{'form.ccuname'});
 3545:                 unless ($isauthor) {
 3546:                     &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3547:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3548:                 }
 3549:                 &tool_changes('authordefaults',\@authordefaults,\%oldsettings,\%oldsettingstext,
 3550:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3551:             } else {
 3552:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3553:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3554:             }
 3555:         }
 3556:         foreach my $item (@userinfo) {
 3557:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3558:                 $namechanged{$item} = 1;
 3559:             }
 3560:         }
 3561:         foreach my $name ('portfolio','author') {
 3562:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3563:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3564:         }
 3565:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3566:             my ($chgresult,$namechgresult);
 3567:             if (keys(%changed) > 0) {
 3568:                 $chgresult = 
 3569:                     &Apache::lonnet::put('environment',\%changeHash,
 3570:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3571:                 if ($chgresult eq 'ok') {
 3572:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3573:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3574:                         my (%newenvhash,$got_domdefs,%domdefaults,$got_userenv,
 3575:                             %userenv);
 3576:                         my @fromenv = keys(%changed);
 3577:                         push(@fromenv,'inststatus');
 3578:                         foreach my $key (keys(%changed)) {
 3579:                             if (($key eq 'official') || ($key eq 'unofficial')
 3580:                                 || ($key eq 'community') || ($key eq 'textbook')) {
 3581:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3582:                                     $changeHash{'requestcourses.'.$key};
 3583:                                 if ($changeHash{'requestcourses.'.$key}) {
 3584:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3585:                                 } else {
 3586:                                     unless ($got_domdefs) {
 3587:                                         %domdefaults =
 3588:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3589:                                         $got_domdefs = 1;
 3590:                                     }
 3591:                                     unless ($got_userenv) {
 3592:                                         %userenv =
 3593:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3594:                                                                              $env{'user.name'},@fromenv);
 3595:                                         $got_userenv = 1;
 3596:                                     }
 3597:                                     $newenvhash{'environment.canrequest.'.$key} =
 3598:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3599:                                             $key,'reload','requestcourses',\%userenv,\%domdefaults);
 3600:                                 }
 3601:                             } elsif ($key eq 'requestauthor') {
 3602:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3603:                                 if ($changeHash{$key}) {
 3604:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3605:                                 } else {
 3606:                                     unless ($got_domdefs) {
 3607:                                         %domdefaults =
 3608:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3609:                                         $got_domdefs = 1;
 3610:                                     }
 3611:                                     unless ($got_userenv) {
 3612:                                         %userenv =
 3613:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3614:                                                                              $env{'user.name'},@fromenv);
 3615:                                         $got_userenv = 1;
 3616:                                     }
 3617:                                     $newenvhash{'environment.canrequest.author'} =
 3618:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3619:                                             $key,'reload','requestauthor',\%userenv,\%domdefaults);
 3620:                                 }
 3621:                             } elsif ($key eq 'editors') {
 3622:                                 $newenvhash{'environment.author'.$key} = $changeHash{'author'.$key};
 3623:                                 if ($env{'form.customeditors'}) {
 3624:                                     $newenvhash{'environment.editors'} = $changeHash{'author'.$key};
 3625:                                 } else {
 3626:                                     unless ($got_domdefs) {
 3627:                                         %domdefaults =
 3628:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3629:                                         $got_domdefs = 1;
 3630:                                     }
 3631:                                     if ($domdefaults{'editors'} ne '') {
 3632:                                         $newenvhash{'environment.editors'} = $domdefaults{'editors'};
 3633:                                     } else {
 3634:                                         $newenvhash{'environment.editors'} = 'edit,xml';
 3635:                                     }
 3636:                                 }
 3637:                             } elsif ($key ne 'quota') {
 3638:                                 $newenvhash{'environment.tools.'.$key} = 
 3639:                                     $changeHash{'tools.'.$key};
 3640:                                 if ($changeHash{'tools.'.$key} ne '') {
 3641:                                     $newenvhash{'environment.availabletools.'.$key} =
 3642:                                         $changeHash{'tools.'.$key};
 3643:                                 } else {
 3644:                                     unless ($got_domdefs) {
 3645:                                         %domdefaults =
 3646:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3647:                                         $got_domdefs = 1;
 3648:                                     }
 3649:                                     unless ($got_userenv) {
 3650:                                         %userenv =
 3651:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3652:                                                                              $env{'user.name'},@fromenv);
 3653:                                         $got_userenv = 1;
 3654:                                     }
 3655:                                     $newenvhash{'environment.availabletools.'.$key} =
 3656:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3657:                                             $key,'reload','tools',\%userenv,\%domdefaults);
 3658:                                 }
 3659:                             }
 3660:                         }
 3661:                         if (keys(%newenvhash)) {
 3662:                             &Apache::lonnet::appenv(\%newenvhash);
 3663:                         }
 3664:                     }
 3665:                     if ($changed{'aboutme'}) {
 3666:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3667:                                                                      $env{'form.ccdomain'});
 3668:                     }
 3669:                 }
 3670:             }
 3671:             if (keys(%namechanged) > 0) {
 3672:                 foreach my $field (@userinfo) {
 3673:                     $changeHash{$field}  = $env{'form.c'.$field};
 3674:                 }
 3675: # Make the change
 3676:                 $namechgresult =
 3677:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3678:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3679:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3680:                         $changeHash{'lastname'},$changeHash{'generation'},
 3681:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3682:                 %userupdate = (
 3683:                                lastname   => $env{'form.clastname'},
 3684:                                middlename => $env{'form.cmiddlename'},
 3685:                                firstname  => $env{'form.cfirstname'},
 3686:                                generation => $env{'form.cgeneration'},
 3687:                                id         => $env{'form.cid'},
 3688:                              );
 3689:             }
 3690:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3691:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3692:             # Tell the user we changed the name
 3693:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3694:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3695:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3696:                                   \%newsettingstext);
 3697:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3698:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3699:                          {$env{'form.ccuname'} => $env{'form.cid'}});
 3700:                     if (($recurseid) &&
 3701:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3702:                         my $idresult = 
 3703:                             &Apache::lonuserutils::propagate_id_change(
 3704:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3705:                                 \%userupdate);
 3706:                         $r->print('<br />'.$idresult.'<br />');
 3707:                     }
 3708:                 }
 3709:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3710:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3711:                     my %newenvhash;
 3712:                     foreach my $key (keys(%changeHash)) {
 3713:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3714:                     }
 3715:                     &Apache::lonnet::appenv(\%newenvhash);
 3716:                 }
 3717:             } else { # error occurred
 3718:                 $r->print(
 3719:                     '<p class="LC_error">'
 3720:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3721:                             '"'.$env{'form.ccuname'}.'"',
 3722:                             '"'.$env{'form.ccdomain'}.'"')
 3723:                    .'</p>');
 3724:             }
 3725:         } else { # End of if ($env ... ) logic
 3726:             # They did not want to change the users name, quota, tool availability,
 3727:             # or ability to request creation of courses, 
 3728:             # but we can still tell them what the name and quota and availabilities are  
 3729:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3730:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3731:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3732:         }
 3733:         if (@mod_disallowed) {
 3734:             my ($rolestr,$contextname);
 3735:             if (@longroles > 0) {
 3736:                 $rolestr = join(', ',@longroles);
 3737:             } else {
 3738:                 $rolestr = &mt('No roles');
 3739:             }
 3740:             if ($context eq 'course') {
 3741:                 $contextname = 'course';
 3742:             } elsif ($context eq 'author') {
 3743:                 $contextname = 'co-author';
 3744:             }
 3745:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3746:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3747:             foreach my $field (@mod_disallowed) {
 3748:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3749:             }
 3750:             $r->print('</ul>');
 3751:             if (@mod_disallowed == 1) {
 3752:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3753:             } else {
 3754:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3755:             }
 3756:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3757:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3758:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3759:                          ,'<a href="'.$helplink.'">','</a>')
 3760:                       .'<br />');
 3761:         }
 3762:         $r->print('<span class="LC_warning">'
 3763:                   .$no_forceid_alert
 3764:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3765:                   .'</span>');
 3766:     }
 3767:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3768:     if ($env{'form.action'} eq 'singlestudent') {
 3769:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3770:                                $crstype,$showcredits,$defaultcredits);
 3771:         my $linktext = ($crstype eq 'Community' ?
 3772:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3773:         $r->print(
 3774:             &Apache::lonhtmlcommon::actionbox([
 3775:                 '<a href="javascript:backPage(document.userupdate)">'
 3776:                .($crstype eq 'Community' ? 
 3777:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3778:                .'</a>']));
 3779:     } else {
 3780:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3781:         if (keys(%namechanged) > 0) {
 3782:             if ($context eq 'course') {
 3783:                 if (@userroles > 0) {
 3784:                     if ((@rolechanges == 0) || 
 3785:                         (!(grep(/^st$/,@rolechanges)))) {
 3786:                         if (grep(/^st$/,@userroles)) {
 3787:                             my $classlistupdated =
 3788:                                 &Apache::lonuserutils::update_classlist($cdom,
 3789:                                               $cnum,$env{'form.ccdomain'},
 3790:                                        $env{'form.ccuname'},\%userupdate);
 3791:                         }
 3792:                     }
 3793:                 }
 3794:             }
 3795:         }
 3796:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3797:                                                      $env{'form.ccdomain'});
 3798:         if ($env{'form.popup'}) {
 3799:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3800:         } else {
 3801:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3802:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3803:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3804:         }
 3805:     }
 3806: }
 3807: 
 3808: sub display_userinfo {
 3809:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3810:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3811:         $newsetting,$newsettingtext) = @_;
 3812:     return unless (ref($order) eq 'ARRAY' &&
 3813:                    ref($canshow) eq 'HASH' && 
 3814:                    ref($requestcourses) eq 'ARRAY' && 
 3815:                    ref($requestauthor) eq 'ARRAY' &&
 3816:                    ref($usertools) eq 'ARRAY' && 
 3817:                    ref($userenv) eq 'HASH' &&
 3818:                    ref($changedhash) eq 'HASH' &&
 3819:                    ref($oldsetting) eq 'HASH' &&
 3820:                    ref($oldsettingtext) eq 'HASH' &&
 3821:                    ref($newsetting) eq 'HASH' &&
 3822:                    ref($newsettingtext) eq 'HASH');
 3823:     my %lt=&Apache::lonlocal::texthash(
 3824:          'ui'             => 'User Information',
 3825:          'uic'            => 'User Information Changed',
 3826:          'firstname'      => 'First Name',
 3827:          'middlename'     => 'Middle Name',
 3828:          'lastname'       => 'Last Name',
 3829:          'generation'     => 'Generation',
 3830:          'id'             => 'Student/Employee ID',
 3831:          'permanentemail' => 'Permanent e-mail address',
 3832:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3833:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3834:          'blog'           => 'Blog Availability',
 3835:          'webdav'         => 'WebDAV Availability',
 3836:          'aboutme'        => 'Personal Information Page Availability',
 3837:          'portfolio'      => 'Portfolio Availability',
 3838:          'timezone'       => 'Can set own Time Zone',
 3839:          'official'       => 'Can Request Official Courses',
 3840:          'unofficial'     => 'Can Request Unofficial Courses',
 3841:          'community'      => 'Can Request Communities',
 3842:          'textbook'       => 'Can Request Textbook Courses',
 3843:          'requestauthor'  => 'Can Request Author Role',
 3844:          'inststatus'     => "Affiliation",
 3845:          'prvs'           => 'Previous Value:',
 3846:          'chto'           => 'Changed To:',
 3847:          'editors'        => "Available Editors in Authoring Space",
 3848:          'edit'           => 'Standard editor (Edit)',
 3849:          'xml'            => 'Text editor (EditXML)',
 3850:          'daxe'           => 'Daxe editor (Daxe)',
 3851:     );
 3852:     if ($changed) {
 3853:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3854:                 &Apache::loncommon::start_data_table().
 3855:                 &Apache::loncommon::start_data_table_header_row());
 3856:         $r->print("<th>&nbsp;</th>\n");
 3857:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3858:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3859:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3860:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3861: 
 3862:         foreach my $item (@userinfo) {
 3863:             my $value = $env{'form.c'.$item};
 3864:             #show changes only:
 3865:             unless ($value eq $userenv->{$item}){
 3866:                 $r->print(&Apache::loncommon::start_data_table_row());
 3867:                 $r->print("<td>$lt{$item}</td>\n");
 3868:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3869:                 $r->print("<td>$value </td>\n");
 3870:                 $r->print(&Apache::loncommon::end_data_table_row());
 3871:             }
 3872:         }
 3873:         foreach my $entry (@{$order}) {
 3874:             if ($canshow->{$entry}) {
 3875:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') ||
 3876:                     ($entry eq 'requestauthor') || ($entry eq 'authordefaults')) {
 3877:                     my @items;
 3878:                     if ($entry eq 'requestauthor') {
 3879:                         @items = ($entry);
 3880:                     } elsif ($entry eq 'authordefaults') {
 3881:                         @items = ('webdav','editors');
 3882:                     } else {
 3883:                         @items = @{$requestcourses};
 3884:                     }
 3885:                     foreach my $item (@items) {
 3886:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3887:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3888:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3889:                             $r->print("<td>$lt{$item}</td>\n");
 3890:                             $r->print("<td>".$oldsetting->{$item});
 3891:                             if ($oldsettingtext->{$item}) {
 3892:                                 if ($oldsetting->{$item}) {
 3893:                                     $r->print(' -- ');
 3894:                                 }
 3895:                                 $r->print($oldsettingtext->{$item});
 3896:                             }
 3897:                             $r->print("</td>\n");
 3898:                             $r->print("<td>".$newsetting->{$item});
 3899:                             if ($newsettingtext->{$item}) {
 3900:                                 if ($newsetting->{$item}) {
 3901:                                     $r->print(' -- ');
 3902:                                 }
 3903:                                 $r->print($newsettingtext->{$item});
 3904:                             }
 3905:                             $r->print("</td>\n");
 3906:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3907:                         }
 3908:                     }
 3909:                 } elsif ($entry eq 'tools') {
 3910:                     foreach my $item (@{$usertools}) {
 3911:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3912:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3913:                             $r->print("<td>$lt{$item}</td>\n");
 3914:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3915:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3916:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3917:                         }
 3918:                     }
 3919:                 } elsif ($entry eq 'quota') {
 3920:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3921:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3922:                         foreach my $name ('portfolio','author') {
 3923:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3924:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3925:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3926:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3927:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3928:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3929:                             }
 3930:                         }
 3931:                     }
 3932:                 } else {
 3933:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3934:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3935:                         $r->print("<td>$lt{$entry}</td>\n");
 3936:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3937:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3938:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3939:                     }
 3940:                 }
 3941:             }
 3942:         }
 3943:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3944:     } else {
 3945:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3946:                   '<p>'.&mt('No changes made to user information').'</p>');
 3947:     }
 3948:     return;
 3949: }
 3950: 
 3951: sub tool_changes {
 3952:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3953:         $changed,$newaccess,$newaccesstext) = @_;
 3954:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3955:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3956:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3957:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3958:         return;
 3959:     }
 3960:     my %reqdisplay = &requestchange_display();
 3961:     if ($context eq 'reqcrsotherdom') {
 3962:         my @options = ('approval','validate','autolimit');
 3963:         my $optregex = join('|',@options);
 3964:         my $cdom = $env{'request.role.domain'};
 3965:         foreach my $tool (@{$usertools}) {
 3966:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3967:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3968:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3969:             my ($newop,$limit);
 3970:             if ($env{'form.'.$context.'_'.$tool}) {
 3971:                 $newop = $env{'form.'.$context.'_'.$tool};
 3972:                 if ($newop eq 'autolimit') {
 3973:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3974:                     $limit =~ s/\D+//g;
 3975:                     $newop .= '='.$limit;
 3976:                 }
 3977:             }
 3978:             if ($userenv->{$context.'.'.$tool} eq '') {
 3979:                 if ($newop) {
 3980:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3981:                                                   $changeHash,$context);
 3982:                     if ($changed->{$tool}) {
 3983:                         if ($newop =~ /^autolimit/) {
 3984:                             if ($limit) {
 3985:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3986:                             } else {
 3987:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3988:                             }
 3989:                         } else {
 3990:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3991:                         }
 3992:                     } else {
 3993:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3994:                     }
 3995:                 }
 3996:             } else {
 3997:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3998:                 my @new;
 3999:                 my $changedoms;
 4000:                 foreach my $req (@curr) {
 4001:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 4002:                         my $oldop = $1;
 4003:                         if ($oldop =~ /^autolimit=(\d*)/) {
 4004:                             my $limit = $1;
 4005:                             if ($limit) {
 4006:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4007:                             } else {
 4008:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4009:                             }
 4010:                         } else {
 4011:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 4012:                         }
 4013:                         if ($oldop ne $newop) {
 4014:                             $changedoms = 1;
 4015:                             foreach my $item (@curr) {
 4016:                                 my ($reqdom,$option) = split(':',$item);
 4017:                                 unless ($reqdom eq $cdom) {
 4018:                                     push(@new,$item);
 4019:                                 }
 4020:                             }
 4021:                             if ($newop) {
 4022:                                 push(@new,$cdom.':'.$newop);
 4023:                             }
 4024:                             @new = sort(@new);
 4025:                         }
 4026:                         last;
 4027:                     }
 4028:                 }
 4029:                 if ((!$changedoms) && ($newop)) {
 4030:                     $changedoms = 1;
 4031:                     @new = sort(@curr,$cdom.':'.$newop);
 4032:                 }
 4033:                 if ($changedoms) {
 4034:                     my $newdomstr;
 4035:                     if (@new) {
 4036:                         $newdomstr = join(',',@new);
 4037:                     }
 4038:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 4039:                                                   $context);
 4040:                     if ($changed->{$tool}) {
 4041:                         if ($env{'form.'.$context.'_'.$tool}) {
 4042:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 4043:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4044:                                 $limit =~ s/\D+//g;
 4045:                                 if ($limit) {
 4046:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4047:                                 } else {
 4048:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4049:                                 }
 4050:                             } else {
 4051:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 4052:                             }
 4053:                         } else {
 4054:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4055:                         }
 4056:                     }
 4057:                 }
 4058:             }
 4059:         }
 4060:         return;
 4061:     }
 4062:     my %tooldesc = &Apache::lonlocal::texthash(
 4063:         'edit' => 'Standard editor (Edit)',
 4064:         'xml'  => 'Text editor (EditXML)',
 4065:         'daxe' => 'Daxe editor (Daxe)',
 4066:     );
 4067:     foreach my $tool (@{$usertools}) {
 4068:         my ($newval,$limit,$envkey);
 4069:         $envkey = $context.'.'.$tool;
 4070:         if ($context eq 'requestcourses') {
 4071:             $newval = $env{'form.crsreq_'.$tool};
 4072:             if ($newval eq 'autolimit') {
 4073:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 4074:                 $limit =~ s/\D+//g;
 4075:                 $newval .= '='.$limit;
 4076:             }
 4077:         } elsif ($context eq 'requestauthor') {
 4078:             $newval = $env{'form.'.$context};
 4079:             $envkey = $context;
 4080:         } elsif ($context eq 'authordefaults') {
 4081:             if ($tool eq 'editors') {
 4082:                 $envkey = 'authoreditors';
 4083:                 if ($env{'form.customeditors'} == 1) {
 4084:                     my @editors;
 4085:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 4086:                     if (@posseditors) {
 4087:                         foreach my $editor (@posseditors) {
 4088:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 4089:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 4090:                                     push(@editors,$editor);
 4091:                                 }
 4092:                             }
 4093:                         }
 4094:                     }
 4095:                     if (@editors) {
 4096:                         $newval = join(',',(sort(@editors)));
 4097:                     }
 4098:                 }
 4099:             } elsif ($tool eq 'webdav') {
 4100:                 $envkey = 'tools.webdav';
 4101:                 $newval = $env{'form.'.$context.'_'.$tool};
 4102:             }
 4103:         } else {
 4104:             $newval = $env{'form.'.$context.'_'.$tool};
 4105:         }
 4106:         if ($userenv->{$envkey} ne '') {
 4107:             $oldaccess->{$tool} = &mt('custom');
 4108:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4109:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 4110:                     my $currlimit = $1;
 4111:                     if ($currlimit eq '') {
 4112:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4113:                     } else {
 4114:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 4115:                     }
 4116:                 } elsif ($userenv->{$envkey}) {
 4117:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4118:                 } else {
 4119:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4120:                 }
 4121:             } elsif ($context eq 'authordefaults') {
 4122:                 if ($tool eq 'editors') {
 4123:                     $oldaccesstext->{$tool} = &mt('can use: [_1]',
 4124:                                                   join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4125:                 } elsif ($tool eq 'webdav') {
 4126:                     if ($userenv->{$envkey}) {
 4127:                         $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4128:                     } else {
 4129:                         $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4130:                     }
 4131:                 }
 4132:             } else {
 4133:                 if ($userenv->{$envkey}) {
 4134:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4135:                 } else {
 4136:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4137:                 }
 4138:             }
 4139:             $changeHash->{$envkey} = $userenv->{$envkey};
 4140:             if ($env{'form.custom'.$tool} == 1) {
 4141:                 if ($newval ne $userenv->{$envkey}) {
 4142:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4143:                                                     $context);
 4144:                     if ($changed->{$tool}) {
 4145:                         $newaccess->{$tool} = &mt('custom');
 4146:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4147:                             if ($newval =~ /^autolimit/) {
 4148:                                 if ($limit) {
 4149:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4150:                                 } else {
 4151:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4152:                                 }
 4153:                             } elsif ($newval) {
 4154:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 4155:                             } else {
 4156:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4157:                             }
 4158:                         } elsif ($context eq 'authordefaults') {
 4159:                             if ($tool eq 'editors') {
 4160:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4161:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$changeHash->{$envkey})));
 4162:                             } elsif ($tool eq 'webdav') {
 4163:                                 if ($newval) {
 4164:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4165:                                 } else {
 4166:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4167:                                 }
 4168:                             }
 4169:                         } else {
 4170:                             if ($newval) {
 4171:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4172:                             } else {
 4173:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4174:                             }
 4175:                         }
 4176:                     } else {
 4177:                         $newaccess->{$tool} = $oldaccess->{$tool};
 4178:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4179:                             if ($userenv->{$envkey} =~ /^autolimit/) {
 4180:                                 if ($limit) {
 4181:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4182:                                 } else {
 4183:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4184:                                 }
 4185:                             } elsif ($userenv->{$envkey}) {
 4186:                                 $newaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4187:                             } else {
 4188:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4189:                             }
 4190:                         } elsif ($context eq 'authordefaults') {
 4191:                             if ($tool eq 'editors') {
 4192:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4193:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4194:                             } elsif ($tool eq 'webdav') {
 4195:                                 if ($userenv->{$envkey}) {
 4196:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4197:                                 } else {
 4198:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4199:                                 }
 4200:                             }  
 4201:                         } else {
 4202:                             if ($userenv->{$context.'.'.$tool}) {
 4203:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4204:                             } else {
 4205:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4206:                             }
 4207:                         }
 4208:                     }
 4209:                 } else {
 4210:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4211:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4212:                 }
 4213:             } else {
 4214:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 4215:                 if ($changed->{$tool}) {
 4216:                     $newaccess->{$tool} = &mt('default');
 4217:                 } else {
 4218:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4219:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4220:                         if ($newval =~ /^autolimit/) {
 4221:                             if ($limit) {
 4222:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4223:                             } else {
 4224:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4225:                             }
 4226:                         } elsif ($newval) {
 4227:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4228:                         } else {
 4229:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4230:                         }
 4231:                     } elsif ($context eq 'authordefaults') {
 4232:                         if ($tool eq 'editors') {
 4233:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4234:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4235:                         } elsif ($tool eq 'webdav') {
 4236:                             if ($userenv->{$envkey}) {
 4237:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4238:                             } else {
 4239:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4240:                             }
 4241:                         }
 4242:                     } else {
 4243:                         if ($userenv->{$context.'.'.$tool}) {
 4244:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4245:                         } else {
 4246:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4247:                         }
 4248:                     }
 4249:                 }
 4250:             }
 4251:         } else {
 4252:             $oldaccess->{$tool} = &mt('default');
 4253:             if ($env{'form.custom'.$tool} == 1) {
 4254:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4255:                                                 $context);
 4256:                 if ($changed->{$tool}) {
 4257:                     $newaccess->{$tool} = &mt('custom');
 4258:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4259:                         if ($newval =~ /^autolimit/) {
 4260:                             if ($limit) {
 4261:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4262:                             } else {
 4263:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4264:                             }
 4265:                         } elsif ($newval) {
 4266:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4267:                         } else {
 4268:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4269:                         }
 4270:                     } elsif ($context eq 'authordefaults') {
 4271:                         if ($tool eq 'editors') {
 4272:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4273:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4274:                         } elsif ($tool eq 'webdav') {
 4275:                             if ($newval) {
 4276:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4277:                             } else {
 4278:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4279:                             }
 4280:                         }
 4281:                     } else {
 4282:                         if ($newval) {
 4283:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4284:                         } else {
 4285:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4286:                         }
 4287:                     }
 4288:                 } else {
 4289:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4290:                 }
 4291:             } else {
 4292:                 $newaccess->{$tool} = $oldaccess->{$tool};
 4293:             }
 4294:         }
 4295:     }
 4296:     return;
 4297: }
 4298: 
 4299: sub update_roles {
 4300:     my ($r,$context,$showcredits) = @_;
 4301:     my $now=time;
 4302:     my @rolechanges;
 4303:     my %disallowed;
 4304:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 4305:     foreach my $key (keys(%env)) {
 4306: 	next if (! $env{$key});
 4307:         next if ($key eq 'form.action');
 4308: 	# Revoke roles
 4309: 	if ($key=~/^form\.rev/) {
 4310: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 4311: # Revoke standard role
 4312: 		my ($scope,$role) = ($1,$2);
 4313: 		my $result =
 4314: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 4315: 						$env{'form.ccuname'},
 4316: 						$scope,$role,'','',$context);
 4317:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4318:                             &mt('Revoking [_1] in [_2]',
 4319:                                 &Apache::lonnet::plaintext($role),
 4320:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4321:                                 $result ne "ok").'<br />');
 4322:                 if ($result ne "ok") {
 4323:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4324:                 }
 4325: 		if ($role eq 'st') {
 4326: 		    my $result = 
 4327:                         &Apache::lonuserutils::classlist_drop($scope,
 4328:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4329: 			    $now);
 4330:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4331: 		}
 4332:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4333:                     push(@rolechanges,$role);
 4334:                 }
 4335: 	    }
 4336: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4337: # Revoke custom role
 4338:                 my $result = &Apache::lonnet::revokecustomrole(
 4339:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4340:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4341:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4342:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4343:                             $result ne 'ok').'<br />');
 4344:                 if ($result ne "ok") {
 4345:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4346:                 }
 4347:                 if (!grep(/^cr$/,@rolechanges)) {
 4348:                     push(@rolechanges,'cr');
 4349:                 }
 4350: 	    }
 4351: 	} elsif ($key=~/^form\.del/) {
 4352: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4353: # Delete standard role
 4354: 		my ($scope,$role) = ($1,$2);
 4355: 		my $result =
 4356: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4357: 						$env{'form.ccuname'},
 4358: 						$scope,$role,$now,0,1,'',
 4359:                                                 $context);
 4360:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4361:                             &mt('Deleting [_1] in [_2]',
 4362:                                 &Apache::lonnet::plaintext($role),
 4363:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4364:                             $result ne 'ok').'<br />');
 4365:                 if ($result ne "ok") {
 4366:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4367:                 }
 4368: 
 4369: 		if ($role eq 'st') {
 4370: 		    my $result = 
 4371:                         &Apache::lonuserutils::classlist_drop($scope,
 4372:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4373: 			    $now);
 4374: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4375: 		}
 4376:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4377:                     push(@rolechanges,$role);
 4378:                 }
 4379:             }
 4380: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4381:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4382: # Delete custom role
 4383:                 my $result =
 4384:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4385:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4386:                         0,1,$context);
 4387:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4388:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4389:                       $result ne "ok").'<br />');
 4390:                 if ($result ne "ok") {
 4391:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4392:                 }
 4393: 
 4394:                 if (!grep(/^cr$/,@rolechanges)) {
 4395:                     push(@rolechanges,'cr');
 4396:                 }
 4397:             }
 4398: 	} elsif ($key=~/^form\.ren/) {
 4399:             my $udom = $env{'form.ccdomain'};
 4400:             my $uname = $env{'form.ccuname'};
 4401: # Re-enable standard role
 4402: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4403:                 my $url = $1;
 4404:                 my $role = $2;
 4405:                 my $logmsg;
 4406:                 my $output;
 4407:                 if ($role eq 'st') {
 4408:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4409:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4410:                         my $credits;
 4411:                         if ($showcredits) {
 4412:                             my $defaultcredits = 
 4413:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4414:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4415:                         }
 4416:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4417:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4418:                             if ($result eq 'refused' && $logmsg) {
 4419:                                 $output = $logmsg;
 4420:                             } else { 
 4421:                                 $output = &mt('Error: [_1]',$result)."\n";
 4422:                             }
 4423:                         } else {
 4424:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4425:                                         &Apache::lonnet::plaintext($role),
 4426:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4427:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4428:                         }
 4429:                     }
 4430:                 } else {
 4431: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4432:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4433:                                $context);
 4434:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4435:                                         &Apache::lonnet::plaintext($role),
 4436:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4437:                     if ($result ne "ok") {
 4438:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4439:                     }
 4440:                 }
 4441:                 $r->print($output);
 4442:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4443:                     push(@rolechanges,$role);
 4444:                 }
 4445: 	    }
 4446: # Re-enable custom role
 4447: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4448:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4449:                 my $result = &Apache::lonnet::assigncustomrole(
 4450:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4451:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4452:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4453:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4454:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4455:                     $result ne "ok").'<br />');
 4456:                 if ($result ne "ok") {
 4457:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4458:                 }
 4459:                 if (!grep(/^cr$/,@rolechanges)) {
 4460:                     push(@rolechanges,'cr');
 4461:                 }
 4462:             }
 4463: 	} elsif ($key=~/^form\.act/) {
 4464:             my $udom = $env{'form.ccdomain'};
 4465:             my $uname = $env{'form.ccuname'};
 4466: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4467:                 # Activate a custom role
 4468: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4469: 		my $url='/'.$one.'/'.$two;
 4470: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4471: 
 4472:                 my $start = ( $env{'form.start_'.$full} ?
 4473:                               $env{'form.start_'.$full} :
 4474:                               $now );
 4475:                 my $end   = ( $env{'form.end_'.$full} ?
 4476:                               $env{'form.end_'.$full} :
 4477:                               0 );
 4478:                                                                                      
 4479:                 # split multiple sections
 4480:                 my %sections = ();
 4481:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4482:                 if ($num_sections == 0) {
 4483:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4484:                 } else {
 4485: 		    my %curr_groups =
 4486: 			&Apache::longroup::coursegroups($one,$two);
 4487:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4488:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4489:                             exists($curr_groups{$sec})) {
 4490:                             $disallowed{$sec} = $url;
 4491:                             next;
 4492:                         }
 4493:                         my $securl = $url.'/'.$sec;
 4494: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4495:                     }
 4496:                 }
 4497:                 if (!grep(/^cr$/,@rolechanges)) {
 4498:                     push(@rolechanges,'cr');
 4499:                 }
 4500: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4501: 		# Activate roles for sections with 3 id numbers
 4502: 		# set start, end times, and the url for the class
 4503: 		my ($one,$two,$three)=($1,$2,$3);
 4504: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4505: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4506: 			      $now );
 4507: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4508: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4509: 			      0 );
 4510: 		my $url='/'.$one.'/'.$two;
 4511:                 my $type = 'three';
 4512:                 # split multiple sections
 4513:                 my %sections = ();
 4514:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4515:                 my $credits;
 4516:                 if ($three eq 'st') {
 4517:                     if ($showcredits) { 
 4518:                         my $defaultcredits = 
 4519:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4520:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4521:                         $credits =~ s/[^\d\.]//g;
 4522:                         if ($credits eq $defaultcredits) {
 4523:                             undef($credits);
 4524:                         }
 4525:                     }
 4526:                 }
 4527:                 if ($num_sections == 0) {
 4528:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4529:                 } else {
 4530:                     my %curr_groups = 
 4531: 			&Apache::longroup::coursegroups($one,$two);
 4532:                     my $emptysec = 0;
 4533:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4534:                         $sec =~ s/\W//g;
 4535:                         if ($sec ne '') {
 4536:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4537:                                 exists($curr_groups{$sec})) {
 4538:                                 $disallowed{$sec} = $url;
 4539:                                 next;
 4540:                             }
 4541:                             my $securl = $url.'/'.$sec;
 4542:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4543:                         } else {
 4544:                             $emptysec = 1;
 4545:                         }
 4546:                     }
 4547:                     if ($emptysec) {
 4548:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4549:                     }
 4550:                 }
 4551:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4552:                     push(@rolechanges,$three);
 4553:                 }
 4554: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4555: 		# Activate roles for sections with two id numbers
 4556: 		# set start, end times, and the url for the class
 4557: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4558: 			      $env{'form.start_'.$1.'_'.$2} : 
 4559: 			      $now );
 4560: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4561: 			      $env{'form.end_'.$1.'_'.$2} :
 4562: 			      0 );
 4563:                 my $one = $1;
 4564:                 my $two = $2;
 4565: 		my $url='/'.$one.'/';
 4566:                 # split multiple sections
 4567:                 my %sections = ();
 4568:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4569:                 if ($num_sections == 0) {
 4570:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4571:                 } else {
 4572:                     my $emptysec = 0;
 4573:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4574:                         if ($sec ne '') {
 4575:                             my $securl = $url.'/'.$sec;
 4576:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4577:                         } else {
 4578:                             $emptysec = 1;
 4579:                         }
 4580:                     }
 4581:                     if ($emptysec) {
 4582:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4583:                     }
 4584:                 }
 4585:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4586:                     push(@rolechanges,$two);
 4587:                 }
 4588: 	    } else {
 4589: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4590:             }
 4591:             foreach my $key (sort(keys(%disallowed))) {
 4592:                 $r->print('<p class="LC_warning">');
 4593:                 if (($key eq 'none') || ($key eq 'all')) {  
 4594:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4595:                 } else {
 4596:                     $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>'));
 4597:                 }
 4598:                 $r->print('</p><p>'
 4599:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4600:                              ,'<a href="javascript:history.go(-1)'
 4601:                              ,'</a>')
 4602:                          .'</p><br />'
 4603:                 );
 4604:             }
 4605: 	}
 4606:     } # End of foreach (keys(%env))
 4607: # Flush the course logs so reverse user roles immediately updated
 4608:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4609:     if (@rolechanges == 0) {
 4610:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4611:     }
 4612:     return @rolechanges;
 4613: }
 4614: 
 4615: sub get_user_credits {
 4616:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4617:     if ($cdom eq '' || $cnum eq '') {
 4618:         return unless ($env{'request.course.id'});
 4619:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4620:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4621:     }
 4622:     my $credits;
 4623:     my %currhash =
 4624:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4625:     if (keys(%currhash) > 0) {
 4626:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4627:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4628:         $credits = $items[$crdidx];
 4629:         $credits =~ s/[^\d\.]//g;
 4630:     }
 4631:     if ($credits eq $defaultcredits) {
 4632:         undef($credits);
 4633:     }
 4634:     return $credits;
 4635: }
 4636: 
 4637: sub enroll_single_student {
 4638:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4639:         $showcredits,$defaultcredits) = @_;
 4640:     $r->print('<h3>');
 4641:     if ($crstype eq 'Community') {
 4642:         $r->print(&mt('Enrolling Member'));
 4643:     } else {
 4644:         $r->print(&mt('Enrolling Student'));
 4645:     }
 4646:     $r->print('</h3>');
 4647: 
 4648:     # Remove non alphanumeric values from section
 4649:     $env{'form.sections'}=~s/\W//g;
 4650: 
 4651:     my $credits;
 4652:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4653:         $credits = $env{'form.credits'};
 4654:         $credits =~ s/[^\d\.]//g;
 4655:         if ($credits ne '') {
 4656:             if ($credits eq $defaultcredits) {
 4657:                 undef($credits);
 4658:             }
 4659:         }
 4660:     }
 4661: 
 4662:     # Clean out any old student roles the user has in this class.
 4663:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4664:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4665:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4666:     my $enroll_result =
 4667:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4668:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4669:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4670:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4671:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4672:             $credits);
 4673:     if ($enroll_result =~ /^ok/) {
 4674:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4675:         if ($env{'form.sections'} ne '') {
 4676:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4677:         }
 4678:         my ($showstart,$showend);
 4679:         if ($startdate <= $now) {
 4680:             $showstart = &mt('Access starts immediately');
 4681:         } else {
 4682:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4683:         }
 4684:         if ($enddate == 0) {
 4685:             $showend = &mt('ends: no ending date');
 4686:         } else {
 4687:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4688:         }
 4689:         $r->print('.<br />'.$showstart.'; '.$showend);
 4690:         if ($startdate <= $now && !$newuser) {
 4691:             $r->print('<p class="LC_info">');
 4692:             if ($crstype eq 'Community') {
 4693:                 $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.'));
 4694:             } else {
 4695:                 $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.'));
 4696:            }
 4697:            $r->print('</p>');
 4698:         }
 4699:     } else {
 4700:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4701:     }
 4702:     return;
 4703: }
 4704: 
 4705: sub get_defaultquota_text {
 4706:     my ($settingstatus) = @_;
 4707:     my $defquotatext; 
 4708:     if ($settingstatus eq '') {
 4709:         $defquotatext = &mt('default');
 4710:     } else {
 4711:         my ($usertypes,$order) =
 4712:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4713:         if ($usertypes->{$settingstatus} eq '') {
 4714:             $defquotatext = &mt('default');
 4715:         } else {
 4716:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4717:         }
 4718:     }
 4719:     return $defquotatext;
 4720: }
 4721: 
 4722: sub update_result_form {
 4723:     my ($uhome) = @_;
 4724:     my $outcome = 
 4725:     '<form name="userupdate" method="post" action="">'."\n";
 4726:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4727:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4728:     }
 4729:     if ($env{'form.origname'} ne '') {
 4730:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4731:     }
 4732:     foreach my $item ('sortby','seluname','seludom') {
 4733:         if (exists($env{'form.'.$item})) {
 4734:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4735:         }
 4736:     }
 4737:     if ($uhome eq 'no_host') {
 4738:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4739:     }
 4740:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4741:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4742:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4743:                 '</form>';
 4744:     return $outcome;
 4745: }
 4746: 
 4747: sub quota_admin {
 4748:     my ($setquota,$changeHash,$name) = @_;
 4749:     my $quotachanged;
 4750:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4751:         # Current user has quota modification privileges
 4752:         if (ref($changeHash) eq 'HASH') {
 4753:             $quotachanged = 1;
 4754:             $changeHash->{$name.'quota'} = $setquota;
 4755:         }
 4756:     }
 4757:     return $quotachanged;
 4758: }
 4759: 
 4760: sub tool_admin {
 4761:     my ($tool,$settool,$changeHash,$context) = @_;
 4762:     my $canchange = 0; 
 4763:     if ($context eq 'requestcourses') {
 4764:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4765:             $canchange = 1;
 4766:         }
 4767:     } elsif ($context eq 'reqcrsotherdom') {
 4768:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4769:             $canchange = 1;
 4770:         }
 4771:     } elsif ($context eq 'requestauthor') {
 4772:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4773:             $canchange = 1;
 4774:         }
 4775:     } elsif ($context eq 'authordefaults') {
 4776:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4777:             $canchange = 1;
 4778:         }
 4779:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4780:         # Current user has quota modification privileges
 4781:         $canchange = 1;
 4782:     }
 4783:     my $toolchanged;
 4784:     if ($canchange) {
 4785:         if (ref($changeHash) eq 'HASH') {
 4786:             $toolchanged = 1;
 4787:             if ($tool eq 'requestauthor') {
 4788:                 $changeHash->{$context} = $settool;
 4789:             } elsif ($tool eq 'editors') {
 4790:                 $changeHash->{'author'.$tool} = $settool;
 4791:             } elsif ($tool eq 'webdav') {
 4792:                 $changeHash->{'tools.'.$tool} = $settool;
 4793:             } else {
 4794:                 $changeHash->{$context.'.'.$tool} = $settool;
 4795:             }
 4796:         }
 4797:     }
 4798:     return $toolchanged;
 4799: }
 4800: 
 4801: sub build_roles {
 4802:     my ($sectionstr,$sections,$role) = @_;
 4803:     my $num_sections = 0;
 4804:     if ($sectionstr=~ /,/) {
 4805:         my @secnums = split/,/,$sectionstr;
 4806:         if ($role eq 'st') {
 4807:             $secnums[0] =~ s/\W//g;
 4808:             $$sections{$secnums[0]} = 1;
 4809:             $num_sections = 1;
 4810:         } else {
 4811:             foreach my $sec (@secnums) {
 4812:                 $sec =~ ~s/\W//g;
 4813:                 if (!($sec eq "")) {
 4814:                     if (exists($$sections{$sec})) {
 4815:                         $$sections{$sec} ++;
 4816:                     } else {
 4817:                         $$sections{$sec} = 1;
 4818:                         $num_sections ++;
 4819:                     }
 4820:                 }
 4821:             }
 4822:         }
 4823:     } else {
 4824:         $sectionstr=~s/\W//g;
 4825:         unless ($sectionstr eq '') {
 4826:             $$sections{$sectionstr} = 1;
 4827:             $num_sections ++;
 4828:         }
 4829:     }
 4830: 
 4831:     return $num_sections;
 4832: }
 4833: 
 4834: # ========================================================== Custom Role Editor
 4835: 
 4836: sub custom_role_editor {
 4837:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4838:     my $action = $env{'form.customroleaction'};
 4839:     my ($rolename,$helpitem);
 4840:     if ($action eq 'new') {
 4841:         $rolename=$env{'form.newrolename'};
 4842:     } else {
 4843:         $rolename=$env{'form.rolename'};
 4844:     }
 4845: 
 4846:     my ($crstype,$context);
 4847:     if ($env{'request.course.id'}) {
 4848:         $crstype = &Apache::loncommon::course_type();
 4849:         $context = 'course';
 4850:         $helpitem = 'Course_Editing_Custom_Roles';
 4851:     } else {
 4852:         $context = 'domain';
 4853:         $crstype = 'course';
 4854:         $helpitem = 'Domain_Editing_Custom_Roles';
 4855:     }
 4856: 
 4857:     $rolename=~s/[^A-Za-z0-9]//gs;
 4858:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4859: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4860:                                    $permission);
 4861:         return;
 4862:     }
 4863: 
 4864:     my $formname = 'form1';
 4865:     my %privs=();
 4866:     my $body_top = '<h2>';
 4867: # ------------------------------------------------------- Does this role exist?
 4868:     my ($rdummy,$roledef)=
 4869: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4870:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4871:         $body_top .= &mt('Existing Role').' "';
 4872: # ------------------------------------------------- Get current role privileges
 4873:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4874:         if ($privs{'system'} =~ /bre\&S/) {
 4875:             if ($context eq 'domain') {
 4876:                 $crstype = 'Course';
 4877:             } elsif ($crstype eq 'Community') {
 4878:                 $privs{'system'} =~ s/bre\&S//;
 4879:             }
 4880:         } elsif ($context eq 'domain') {
 4881:             $crstype = 'Course';
 4882:         }
 4883:     } else {
 4884:         $body_top .= &mt('New Role').' "';
 4885:         $roledef='';
 4886:     }
 4887:     $body_top .= $rolename.'"</h2>';
 4888: 
 4889: # ------------------------------------------------------- What can be assigned?
 4890:     my %full=();
 4891:     my %levels=(
 4892:                  course => {},
 4893:                  domain => {},
 4894:                  system => {},
 4895:                );
 4896:     my %levelscurrent=(
 4897:                         course => {},
 4898:                         domain => {},
 4899:                         system => {},
 4900:                       );
 4901:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4902:     my ($jsback,$elements) = &crumb_utilities();
 4903:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4904:     my $head_script =
 4905:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4906:                                                   \%full,\@templateroles,$jsback);
 4907:     push (@{$brcrum},
 4908:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4909:                text => "Pick custom role",
 4910:                faq  => 282,bug=>'Instructor Interface',},
 4911:               {href => "javascript:backPage(document.$formname,'','')",
 4912:                text => "Edit custom role",
 4913:                faq  => 282,
 4914:                bug  => 'Instructor Interface',
 4915:                help => $helpitem}
 4916:               );
 4917:     my $args = { bread_crumbs          => $brcrum,
 4918:                  bread_crumbs_component => 'User Management'};
 4919:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4920:                                              $head_script,$args).
 4921:               $body_top);
 4922:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4923:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4924:                                                         \@templateroles,$prefix));
 4925: 
 4926:     $r->print(<<ENDCCF);
 4927: <input type="hidden" name="phase" value="set_custom_roles" />
 4928: <input type="hidden" name="rolename" value="$rolename" />
 4929: ENDCCF
 4930:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4931:                                                        \%levelscurrent,$prefix));
 4932:     $r->print(&Apache::loncommon::end_data_table().
 4933:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4934:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4935:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4936:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4937:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4938: }
 4939: 
 4940: # ---------------------------------------------------------- Call to definerole
 4941: sub set_custom_role {
 4942:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4943:     my $rolename=$env{'form.rolename'};
 4944:     $rolename=~s/[^A-Za-z0-9]//gs;
 4945:     if (!$rolename) {
 4946: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4947:         return;
 4948:     }
 4949:     my ($jsback,$elements) = &crumb_utilities();
 4950:     my $jscript = '<script type="text/javascript">'
 4951:                  .'// <![CDATA['."\n"
 4952:                  .$jsback."\n"
 4953:                  .'// ]]>'."\n"
 4954:                  .'</script>'."\n";
 4955:     my $helpitem = 'Course_Editing_Custom_Roles';
 4956:     if ($context eq 'domain') {
 4957:         $helpitem = 'Domain_Editing_Custom_Roles';
 4958:     }
 4959:     push(@{$brcrum},
 4960:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4961:          text => "Pick custom role",
 4962:          faq  => 282,
 4963:          bug  => 'Instructor Interface',},
 4964:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4965:          text => "Edit custom role",
 4966:          faq  => 282,
 4967:          bug  => 'Instructor Interface',},
 4968:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4969:          text => "Result",
 4970:          faq  => 282,
 4971:          bug  => 'Instructor Interface',
 4972:          help => $helpitem,}
 4973:         );
 4974:     my $args = { bread_crumbs           => $brcrum,
 4975:                  bread_crumbs_component => 'User Management'};
 4976:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4977: 
 4978:     my $newrole;
 4979:     my ($rdummy,$roledef)=
 4980: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4981: 
 4982: # ------------------------------------------------------- Does this role exist?
 4983:     $r->print('<h3>');
 4984:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4985: 	$r->print(&mt('Existing Role').' "');
 4986:     } else {
 4987: 	$r->print(&mt('New Role').' "');
 4988: 	$roledef='';
 4989:         $newrole = 1;
 4990:     }
 4991:     $r->print($rolename.'"</h3>');
 4992: # ------------------------------------------------- Assign role and show result
 4993: 
 4994:     my $errmsg;
 4995:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4996:     # Assign role and return result
 4997:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4998:                                              $newprivs{'c'});
 4999:     if ($result ne 'ok') {
 5000:         $errmsg = ': '.$result;
 5001:     }
 5002:     my $message =
 5003:         &Apache::lonhtmlcommon::confirm_success(
 5004:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 5005:     if ($env{'request.course.id'}) {
 5006:         my $url='/'.$env{'request.course.id'};
 5007:         $url=~s/\_/\//g;
 5008:         $result =
 5009:             &Apache::lonnet::assigncustomrole(
 5010:                 $env{'user.domain'},$env{'user.name'},
 5011:                 $url,
 5012:                 $env{'user.domain'},$env{'user.name'},
 5013:                 $rolename,undef,undef,undef,$context);
 5014:         if ($result ne 'ok') {
 5015:             $errmsg = ': '.$result;
 5016:         }
 5017:         $message .=
 5018:             '<br />'
 5019:            .&Apache::lonhtmlcommon::confirm_success(
 5020:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 5021:     }
 5022:     $r->print(
 5023:         &Apache::loncommon::confirmwrapper($message)
 5024:        .'<br />'
 5025:        .&Apache::lonhtmlcommon::actionbox([
 5026:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 5027:            .&mt('Create or edit another custom role')
 5028:            .'</a>'])
 5029:        .'<form name="customresult" method="post" action="">'
 5030:        .&Apache::lonhtmlcommon::echo_form_input([])
 5031:        .'</form>'
 5032:     );
 5033: }
 5034: 
 5035: # ================================================================ Main Handler
 5036: sub handler {
 5037:     my $r = shift;
 5038:     if ($r->header_only) {
 5039:        &Apache::loncommon::content_type($r,'text/html');
 5040:        $r->send_http_header;
 5041:        return OK;
 5042:     }
 5043:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 5044: 
 5045:     if ($env{'request.course.id'}) {
 5046:         $context = 'course';
 5047:         $crstype = &Apache::loncommon::course_type();
 5048:     } elsif ($env{'request.role'} =~ /^au\./) {
 5049:         $context = 'author';
 5050:     } else {
 5051:         $context = 'domain';
 5052:     }
 5053: 
 5054:     my ($permission,$allowed) =
 5055:         &Apache::lonuserutils::get_permission($context,$crstype);
 5056: 
 5057:     if ($allowed) {
 5058:         my @allhelp;
 5059:         if ($context eq 'course') {
 5060:             $cid = $env{'request.course.id'};
 5061:             $cdom = $env{'course.'.$cid.'.domain'};
 5062:             $cnum = $env{'course.'.$cid.'.num'};
 5063: 
 5064:             if ($permission->{'cusr'}) {
 5065:                 push(@allhelp,'Course_Create_Class_List');
 5066:             }
 5067:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5068:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 5069:             }
 5070:             if ($permission->{'custom'}) {
 5071:                 push(@allhelp,'Course_Editing_Custom_Roles');
 5072:             }
 5073:             if ($permission->{'cusr'}) {
 5074:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 5075:             }
 5076:             unless ($permission->{'cusr_section'}) {
 5077:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 5078:                     push(@allhelp,'Course_Automated_Enrollment');
 5079:                 }
 5080:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 5081:                     push(@allhelp,'Course_Approve_Selfenroll');
 5082:                 }
 5083:             }
 5084:             if ($permission->{'grp_manage'}) {
 5085:                 push(@allhelp,'Course_Manage_Group');
 5086:             }
 5087:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5088:                 push(@allhelp,'Course_User_Logs');
 5089:             }
 5090:         } elsif ($context eq 'author') {
 5091:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5092:                            'Author_View_Coauthor_List','Author_User_Logs'));
 5093:         } else {
 5094:             if ($permission->{'cusr'}) {
 5095:                 push(@allhelp,'Domain_Change_Privileges');
 5096:                 if ($permission->{'activity'}) {
 5097:                     push(@allhelp,'Domain_User_Access_Logs');
 5098:                 }
 5099:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 5100:                 if ($permission->{'custom'}) {
 5101:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 5102:                 }
 5103:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 5104:             } elsif ($permission->{'view'}) {
 5105:                 push(@allhelp,'Domain_View_Privileges');
 5106:                 if ($permission->{'activity'}) {
 5107:                     push(@allhelp,'Domain_User_Access_Logs');
 5108:                 }
 5109:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 5110:             }
 5111:         }
 5112:         if (@allhelp) {
 5113:             $allhelpitems = join(',',@allhelp);
 5114:         }
 5115:     }
 5116: 
 5117:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5118:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 5119:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 5120:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5121:     my $args;
 5122:     my $brcrum = [];
 5123:     my $bread_crumbs_component = 'User Management';
 5124:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 5125:         $brcrum = [{href=>"/adm/createuser",
 5126:                     text=>"User Management",
 5127:                     help=>$allhelpitems}
 5128:                   ];
 5129:     }
 5130:     if (!$allowed) {
 5131:         if ($context eq 'course') {
 5132:             $r->internal_redirect('/adm/viewclasslist');
 5133:             return OK;
 5134:         }
 5135:         $env{'user.error.msg'}=
 5136:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 5137:                                  "or view user status.";
 5138:         return HTTP_NOT_ACCEPTABLE;
 5139:     }
 5140: 
 5141:     &Apache::loncommon::content_type($r,'text/html');
 5142:     $r->send_http_header;
 5143: 
 5144:     my $showcredits;
 5145:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 5146:          ($context eq 'domain')) {
 5147:         my %domdefaults = 
 5148:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 5149:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 5150:             $showcredits = 1;
 5151:         }
 5152:     }
 5153: 
 5154:     # Main switch on form.action and form.state, as appropriate
 5155:     if (! exists($env{'form.action'})) {
 5156:         $args = {bread_crumbs => $brcrum,
 5157:                  bread_crumbs_component => $bread_crumbs_component}; 
 5158:         $r->print(&header(undef,$args));
 5159:         $r->print(&print_main_menu($permission,$context,$crstype));
 5160:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 5161:         my $helpitem = 'Course_Create_Class_List';
 5162:         if ($context eq 'author') {
 5163:             $helpitem = 'Author_Create_Coauthor_List';
 5164:         } elsif ($context eq 'domain') {
 5165:             $helpitem = 'Domain_Create_Users';
 5166:         }
 5167:         push(@{$brcrum},
 5168:               { href => '/adm/createuser?action=upload&state=',
 5169:                 text => 'Upload Users List',
 5170:                 help => $helpitem,
 5171:               });
 5172:         $bread_crumbs_component = 'Upload Users List';
 5173:         $args = {bread_crumbs           => $brcrum,
 5174:                  bread_crumbs_component => $bread_crumbs_component};
 5175:         $r->print(&header(undef,$args));
 5176:         $r->print('<form name="studentform" method="post" '.
 5177:                   'enctype="multipart/form-data" '.
 5178:                   ' action="/adm/createuser">'."\n");
 5179:         if (! exists($env{'form.state'})) {
 5180:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5181:         } elsif ($env{'form.state'} eq 'got_file') {
 5182:             my $result =
 5183:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 5184:                                                                  $permission,
 5185:                                                                  $crstype,$showcredits);
 5186:             if ($result eq 'missingdata') {
 5187:                 delete($env{'form.state'});
 5188:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5189:             }
 5190:         } elsif ($env{'form.state'} eq 'enrolling') {
 5191:             if ($env{'form.datatoken'}) {
 5192:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 5193:                                                                     $permission,
 5194:                                                                     $showcredits);
 5195:                 if ($result eq 'missingdata') {
 5196:                     delete($env{'form.state'});
 5197:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5198:                 } elsif ($result eq 'invalidhome') {
 5199:                     $env{'form.state'} = 'got_file';
 5200:                     delete($env{'form.lcserver'});
 5201:                     my $result =
 5202:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 5203:                                                                          $crstype,$showcredits);
 5204:                     if ($result eq 'missingdata') {
 5205:                         delete($env{'form.state'});
 5206:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5207:                     }
 5208:                 }
 5209:             } else {
 5210:                 delete($env{'form.state'});
 5211:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5212:             }
 5213:         } else {
 5214:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5215:         }
 5216:         $r->print('</form>');
 5217:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 5218:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 5219:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 5220:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 5221:         my $phase = $env{'form.phase'};
 5222:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 5223: 	&Apache::loncreateuser::restore_prev_selections();
 5224: 	my $srch;
 5225: 	foreach my $item (@search) {
 5226: 	    $srch->{$item} = $env{'form.'.$item};
 5227: 	}
 5228:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 5229:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 5230:             if ($env{'form.phase'} eq 'createnewuser') {
 5231:                 my $response;
 5232:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 5233:                     my $response =
 5234:                         '<span class="LC_warning">'
 5235:                        .&mt('You must specify a valid username. Only the following are allowed:'
 5236:                            .' letters numbers - . @')
 5237:                        .'</span>';
 5238:                     $env{'form.phase'} = '';
 5239:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 5240:                                                $crstype,$brcrum,$permission);
 5241:                 } else {
 5242:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 5243:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 5244:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 5245:                                                   $srch,$response,$context,
 5246:                                                   $permission,$crstype,$brcrum,
 5247:                                                   $showcredits);
 5248:                 }
 5249:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 5250:                 my ($currstate,$response,$forcenewuser,$results) = 
 5251:                     &user_search_result($context,$srch);
 5252:                 if ($env{'form.currstate'} eq 'modify') {
 5253:                     $currstate = $env{'form.currstate'};
 5254:                 }
 5255:                 if ($currstate eq 'select') {
 5256:                     &print_user_selection_page($r,$response,$srch,$results,
 5257:                                                \@search,$context,undef,$crstype,
 5258:                                                $brcrum);
 5259:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 5260:                     my ($ccuname,$ccdomain,$uhome);
 5261:                     if (($srch->{'srchby'} eq 'uname') && 
 5262:                         ($srch->{'srchtype'} eq 'exact')) {
 5263:                         $ccuname = $srch->{'srchterm'};
 5264:                         $ccdomain= $srch->{'srchdomain'};
 5265:                     } else {
 5266:                         my @matchedunames = keys(%{$results});
 5267:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 5268:                     }
 5269:                     $ccuname =&LONCAPA::clean_username($ccuname);
 5270:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 5271:                     if ($env{'form.action'} eq 'accesslogs') {
 5272:                         my $uhome;
 5273:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 5274:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 5275:                         }
 5276:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 5277:                             $env{'form.phase'} = '';
 5278:                             undef($forcenewuser);
 5279:                             #if ($response) {
 5280:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 5281:                             #        $response .= '<br /><br />';
 5282:                             #    }
 5283:                             #}
 5284:                             &print_username_entry_form($r,$context,$response,$srch,
 5285:                                                        $forcenewuser,$crstype,$brcrum,
 5286:                                                        $permission);
 5287:                         } else {
 5288:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5289:                         }
 5290:                     } else {
 5291:                         if ($env{'form.forcenewuser'}) {
 5292:                             $response = '';
 5293:                         }
 5294:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 5295:                                                       $srch,$response,$context,
 5296:                                                       $permission,$crstype,$brcrum);
 5297:                     }
 5298:                 } elsif ($currstate eq 'query') {
 5299:                     &print_user_query_page($r,'createuser',$brcrum);
 5300:                 } else {
 5301:                     $env{'form.phase'} = '';
 5302:                     &print_username_entry_form($r,$context,$response,$srch,
 5303:                                                $forcenewuser,$crstype,$brcrum,
 5304:                                                $permission);
 5305:                 }
 5306:             } elsif ($env{'form.phase'} eq 'userpicked') {
 5307:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 5308:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 5309:                 if ($env{'form.action'} eq 'accesslogs') {
 5310:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5311:                 } else {
 5312:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 5313:                                                   $context,$permission,$crstype,
 5314:                                                   $brcrum);
 5315:                 }
 5316:             } elsif ($env{'form.action'} eq 'accesslogs') {
 5317:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 5318:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 5319:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5320:             }
 5321:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 5322:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 5323:         } else {
 5324:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 5325:                                        $brcrum,$permission);
 5326:         }
 5327:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 5328:         my $prefix;
 5329:         if ($env{'form.phase'} eq 'set_custom_roles') {
 5330:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 5331:         } else {
 5332:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5333:         }
 5334:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 5335:              ($permission->{'cusr'}) && 
 5336:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5337:         push(@{$brcrum},
 5338:                  {href => '/adm/createuser?action=processauthorreq',
 5339:                   text => 'Authoring Space requests',
 5340:                   help => 'Domain_Role_Approvals'});
 5341:         $bread_crumbs_component = 'Authoring requests';
 5342:         if ($env{'form.state'} eq 'done') {
 5343:             push(@{$brcrum},
 5344:                      {href => '/adm/createuser?action=authorreqqueue',
 5345:                       text => 'Result',
 5346:                       help => 'Domain_Role_Approvals'});
 5347:             $bread_crumbs_component = 'Authoring request result';
 5348:         }
 5349:         $args = { bread_crumbs           => $brcrum,
 5350:                   bread_crumbs_component => $bread_crumbs_component};
 5351:         my $js = &usernamerequest_javascript();
 5352:         $r->print(&header(&add_script($js),$args));
 5353:         if (!exists($env{'form.state'})) {
 5354:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 5355:                                                                             $env{'request.role.domain'}));
 5356:         } elsif ($env{'form.state'} eq 'done') {
 5357:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 5358:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 5359:                                                                          $env{'request.role.domain'}));
 5360:         }
 5361:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 5362:              ($permission->{'cusr'}) &&
 5363:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5364:         push(@{$brcrum},
 5365:                  {href => '/adm/createuser?action=processusernamereq',
 5366:                   text => 'LON-CAPA account requests',
 5367:                   help => 'Domain_Username_Approvals'});
 5368:         $bread_crumbs_component = 'Account requests';
 5369:         if ($env{'form.state'} eq 'done') {
 5370:             push(@{$brcrum},
 5371:                      {href => '/adm/createuser?action=usernamereqqueue',
 5372:                       text => 'Result',
 5373:                       help => 'Domain_Username_Approvals'});
 5374:             $bread_crumbs_component = 'LON-CAPA account request result';
 5375:         }
 5376:         $args = { bread_crumbs           => $brcrum,
 5377:                   bread_crumbs_component => $bread_crumbs_component};
 5378:         my $js = &usernamerequest_javascript();
 5379:         $r->print(&header(&add_script($js),$args));
 5380:         if (!exists($env{'form.state'})) {
 5381:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 5382:                                                                             $env{'request.role.domain'}));
 5383:         } elsif ($env{'form.state'} eq 'done') {
 5384:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 5385:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 5386:                                                                          $env{'request.role.domain'}));
 5387:         }
 5388:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 5389:              ($permission->{'cusr'})) {
 5390:         my $dom = $env{'form.domain'};
 5391:         my $uname = $env{'form.username'};
 5392:         my $warning;
 5393:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 5394:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 5395:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 5396:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 5397:                     if ($uhome eq 'no_host') {
 5398:                         my $queue = $env{'form.queue'};
 5399:                         my $reqkey = &escape($uname).'_'.$queue; 
 5400:                         my $namespace = 'usernamequeue';
 5401:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 5402:                         my %queued =
 5403:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 5404:                         unless ($queued{$reqkey}) {
 5405:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 5406:                         }
 5407:                     } else {
 5408:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 5409:                     }
 5410:                 } else {
 5411:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 5412:                 }
 5413:             } else {
 5414:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 5415:             }
 5416:         } else {
 5417:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 5418:         }
 5419:         my $args = { only_body => 1 };
 5420:         $r->print(&header(undef,$args).
 5421:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 5422:         if ($warning ne '') {
 5423:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 5424:         } else {
 5425:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5426:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 5427:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5428:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 5429:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 5430:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 5431:                         my %info =
 5432:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 5433:                         if (ref($info{$uname}) eq 'HASH') {
 5434:                             my $usertype = $info{$uname}{'inststatus'};
 5435:                             unless ($usertype) {
 5436:                                 $usertype = 'default';
 5437:                             }
 5438:                             my ($showstatus,$showemail,$pickstart);
 5439:                             my $numextras = 0;
 5440:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5441:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 5442:                                 if (ref($usertypes) eq 'HASH') {
 5443:                                     if ($usertypes->{$usertype}) {
 5444:                                         $showstatus = $usertypes->{$usertype};
 5445:                                     } else {
 5446:                                         $showstatus = $othertitle;
 5447:                                     }
 5448:                                     if ($showstatus) {
 5449:                                         $numextras ++;
 5450:                                     }
 5451:                                 }
 5452:                             }
 5453:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 5454:                                 $showemail = $info{$uname}{'email'};
 5455:                                 $numextras ++;
 5456:                             }
 5457:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 5458:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 5459:                                     $pickstart = 1;
 5460:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5461:                                     my ($num,$count);
 5462:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 5463:                                     $count += $numextras;
 5464:                                     foreach my $field (@{$infofields}) {
 5465:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5466:                                         next unless ($infotitles->{$field});
 5467:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5468:                                                   $info{$uname}{$field});
 5469:                                         $num ++;
 5470:                                         unless ($count == $num) {
 5471:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5472:                                         }
 5473:                                     }
 5474:                                 }
 5475:                             }
 5476:                             if ($numextras) {
 5477:                                 unless ($pickstart) {
 5478:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5479:                                     $pickstart = 1;
 5480:                                 }
 5481:                                 if ($showemail) {
 5482:                                     my $closure = '';
 5483:                                     unless ($showstatus) {
 5484:                                         $closure = 1;
 5485:                                     }
 5486:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 5487:                                               $showemail.
 5488:                                               &Apache::lonhtmlcommon::row_closure($closure));
 5489:                                 }
 5490:                                 if ($showstatus) {
 5491:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 5492:                                               $showstatus.
 5493:                                               &Apache::lonhtmlcommon::row_closure(1));
 5494:                                 }
 5495:                             }
 5496:                             if ($pickstart) {
 5497:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5498:                             } else {
 5499:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 5500:                             }
 5501:                         } else {
 5502:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 5503:                         }
 5504:                     }
 5505:                 }
 5506:             }
 5507:         }
 5508:         $r->print(&close_popup_form());
 5509:     } elsif (($env{'form.action'} eq 'listusers') && 
 5510:              ($permission->{'view'} || $permission->{'cusr'})) {
 5511:         my $helpitem = 'Course_View_Class_List';
 5512:         if ($context eq 'author') {
 5513:             $helpitem = 'Author_View_Coauthor_List';
 5514:         } elsif ($context eq 'domain') {
 5515:             $helpitem = 'Domain_View_Users_List';
 5516:         }
 5517:         if ($env{'form.phase'} eq 'bulkchange') {
 5518:             push(@{$brcrum},
 5519:                     {href => '/adm/createuser?action=listusers',
 5520:                      text => "List Users"},
 5521:                     {href => "/adm/createuser",
 5522:                      text => "Result",
 5523:                      help => $helpitem});
 5524:             $bread_crumbs_component = 'Update Users';
 5525:             $args = {bread_crumbs           => $brcrum,
 5526:                      bread_crumbs_component => $bread_crumbs_component};
 5527:             $r->print(&header(undef,$args));
 5528:             my $setting = $env{'form.roletype'};
 5529:             my $choice = $env{'form.bulkaction'};
 5530:             if ($permission->{'cusr'}) {
 5531:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5532:             } else {
 5533:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5534:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5535:             }
 5536:         } else {
 5537:             push(@{$brcrum},
 5538:                     {href => '/adm/createuser?action=listusers',
 5539:                      text => "List Users",
 5540:                      help => $helpitem});
 5541:             $bread_crumbs_component = 'List Users';
 5542:             $args = {bread_crumbs           => $brcrum,
 5543:                      bread_crumbs_component => $bread_crumbs_component};
 5544:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5545:             my $formname = 'studentform';
 5546:             my $hidecall = "hide_searching();";
 5547:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5548:                 ($env{'form.roletype'} eq 'community'))) {
 5549:                 if ($env{'form.roletype'} eq 'course') {
 5550:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5551:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5552:                                                                 $formname);
 5553:                 } elsif ($env{'form.roletype'} eq 'community') {
 5554:                     $cb_jscript = 
 5555:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5556:                     my %elements = (
 5557:                                       coursepick => 'radio',
 5558:                                       coursetotal => 'text',
 5559:                                       courselist => 'text',
 5560:                                    );
 5561:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5562:                 }
 5563:                 $jscript .= &verify_user_display($context)."\n".
 5564:                             &Apache::loncommon::check_uncheck_jscript();
 5565:                 my $js = &add_script($jscript).$cb_jscript;
 5566:                 my $loadcode = 
 5567:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5568:                 if ($loadcode ne '') {
 5569:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5570:                 } else {
 5571:                     $args->{add_entries} = {onload => $hidecall};
 5572:                 }
 5573:                 $r->print(&header($js,$args));
 5574:             } else {
 5575:                 $args->{add_entries} = {onload => $hidecall};
 5576:                 $jscript = &verify_user_display($context).
 5577:                            &Apache::loncommon::check_uncheck_jscript(); 
 5578:                 $r->print(&header(&add_script($jscript),$args));
 5579:             }
 5580:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5581:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5582:                          $showcredits);
 5583:         }
 5584:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5585:         my $brtext;
 5586:         if ($crstype eq 'Community') {
 5587:             $brtext = 'Drop Members';
 5588:         } else {
 5589:             $brtext = 'Drop Students';
 5590:         }
 5591:         push(@{$brcrum},
 5592:                 {href => '/adm/createuser?action=drop',
 5593:                  text => $brtext,
 5594:                  help => 'Course_Drop_Student'});
 5595:         if ($env{'form.state'} eq 'done') {
 5596:             push(@{$brcrum},
 5597:                      {href=>'/adm/createuser?action=drop',
 5598:                       text=>"Result"});
 5599:         }
 5600:         $bread_crumbs_component = $brtext;
 5601:         $args = {bread_crumbs           => $brcrum,
 5602:                  bread_crumbs_component => $bread_crumbs_component}; 
 5603:         $r->print(&header(undef,$args));
 5604:         if (!exists($env{'form.state'})) {
 5605:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5606:         } elsif ($env{'form.state'} eq 'done') {
 5607:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5608:                                                     $env{'form.action'});
 5609:         }
 5610:     } elsif ($env{'form.action'} eq 'dateselect') {
 5611:         if ($permission->{'cusr'}) {
 5612:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5613:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5614:                                                                    $crstype,$showcredits));
 5615:         } else {
 5616:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5617:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5618:         }
 5619:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5620:         my %currsettings;
 5621:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 5622:             %currsettings = (
 5623:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5624:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5625:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5626:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5627:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5628:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5629:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5630:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5631:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5632:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5633:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5634:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5635:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5636:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5637:             );
 5638:         }
 5639:         if ($permission->{selfenrolladmin}) {
 5640:             push(@{$brcrum},
 5641:                     {href => '/adm/createuser?action=selfenroll',
 5642:                      text => "Configure Self-enrollment",
 5643:                      help => 'Course_Self_Enrollment'});
 5644:             if (!exists($env{'form.state'})) {
 5645:                 $args = { bread_crumbs           => $brcrum,
 5646:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5647:                 $r->print(&header(undef,$args));
 5648:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5649:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5650:             } elsif ($env{'form.state'} eq 'done') {
 5651:                 push (@{$brcrum},
 5652:                           {href=>'/adm/createuser?action=selfenroll',
 5653:                            text=>"Result"});
 5654:                 $args = { bread_crumbs           => $brcrum,
 5655:                           bread_crumbs_component => 'Self-enrollment result'};
 5656:                 $r->print(&header(undef,$args));
 5657:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5658:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5659:             }
 5660:         } elsif ($permission->{selfenrollview}) {
 5661:             push(@{$brcrum},
 5662:                     {href => '/adm/createuser?action=selfenroll',
 5663:                      text => "View Self-enrollment configuration",
 5664:                      help => 'Course_Self_Enrollment'});
 5665:             $args = { bread_crumbs           => $brcrum,
 5666:                       bread_crumbs_component => 'Self-enrollment Settings'};
 5667:             $r->print(&header(undef,$args));
 5668:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5669:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 5670:         } else {
 5671:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5672:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5673:         }
 5674:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5675:         if ($permission->{selfenrolladmin}) {
 5676:             push(@{$brcrum},
 5677:                      {href => '/adm/createuser?action=selfenrollqueue',
 5678:                       text => 'Enrollment requests',
 5679:                       help => 'Course_Approve_Selfenroll'});
 5680:             $bread_crumbs_component = 'Enrollment requests';
 5681:             if ($env{'form.state'} eq 'done') {
 5682:                 push(@{$brcrum},
 5683:                          {href => '/adm/createuser?action=selfenrollqueue',
 5684:                           text => 'Result',
 5685:                           help => 'Course_Approve_Selfenroll'});
 5686:                 $bread_crumbs_component = 'Enrollment result';
 5687:             }
 5688:             $args = { bread_crumbs           => $brcrum,
 5689:                       bread_crumbs_component => $bread_crumbs_component};
 5690:             $r->print(&header(undef,$args));
 5691:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5692:             if (!exists($env{'form.state'})) {
 5693:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5694:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5695:                                                                                 $cdom,$cnum));
 5696:             } elsif ($env{'form.state'} eq 'done') {
 5697:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5698:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5699:                               $cdom,$cnum,$coursedesc));
 5700:             }
 5701:         } else {
 5702:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5703:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5704:         }
 5705:     } elsif ($env{'form.action'} eq 'changelogs') {
 5706:         if ($permission->{cusr} || $permission->{view}) {
 5707:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5708:         } else {
 5709:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5710:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5711:         }
 5712:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5713:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 5714:             ($permission->{'cusr'} || $permission->{'view'})) {
 5715:             if ($env{'form.state'} eq 'process') {
 5716:                 if ($permission->{'owner'}) {
 5717:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5718:                 } else {
 5719:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5720:                 }
 5721:             } else {
 5722:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5723:             }
 5724:         } else {
 5725:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5726:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5727:         }
 5728:     } else {
 5729:         $bread_crumbs_component = 'User Management';
 5730:         $args = { bread_crumbs           => $brcrum,
 5731:                   bread_crumbs_component => $bread_crumbs_component};
 5732:         $r->print(&header(undef,$args));
 5733:         $r->print(&print_main_menu($permission,$context,$crstype));
 5734:     }
 5735:     $r->print(&Apache::loncommon::end_page());
 5736:     return OK;
 5737: }
 5738: 
 5739: sub header {
 5740:     my ($jscript,$args) = @_;
 5741:     my $start_page;
 5742:     if (ref($args) eq 'HASH') {
 5743:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5744:     } else {
 5745:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5746:     }
 5747:     return $start_page;
 5748: }
 5749: 
 5750: sub add_script {
 5751:     my ($js) = @_;
 5752:     return '<script type="text/javascript">'."\n"
 5753:           .'// <![CDATA['."\n"
 5754:           .$js."\n"
 5755:           .'// ]]>'."\n"
 5756:           .'</script>'."\n";
 5757: }
 5758: 
 5759: sub usernamerequest_javascript {
 5760:     my $js = <<ENDJS;
 5761: 
 5762: function openusernamereqdisplay(dom,uname,queue) {
 5763:     var url = '/adm/createuser?action=displayuserreq';
 5764:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5765:     var title = 'Account_Request_Browser';
 5766:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5767:     options += ',width=700,height=600';
 5768:     var stdeditbrowser = open(url,title,options,'1');
 5769:     stdeditbrowser.focus();
 5770:     return;
 5771: }
 5772:  
 5773: ENDJS
 5774: }
 5775: 
 5776: sub close_popup_form {
 5777:     my $close= &mt('Close Window');
 5778:     return << "END";
 5779: <p><form name="displayreq" action="" method="post">
 5780: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5781: </form></p>
 5782: END
 5783: }
 5784: 
 5785: sub verify_user_display {
 5786:     my ($context) = @_;
 5787:     my %lt = &Apache::lonlocal::texthash (
 5788:         course    => 'course(s): description, section(s), status',
 5789:         community => 'community(s): description, section(s), status',
 5790:         author    => 'author',
 5791:     );
 5792:     my $photos;
 5793:     if (($context eq 'course') && $env{'request.course.id'}) {
 5794:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5795:     }
 5796:     my $output = <<"END";
 5797: 
 5798: function hide_searching() {
 5799:     if (document.getElementById('searching')) {
 5800:         document.getElementById('searching').style.display = 'none';
 5801:     }
 5802:     return;
 5803: }
 5804: 
 5805: function display_update() {
 5806:     document.studentform.action.value = 'listusers';
 5807:     document.studentform.phase.value = 'display';
 5808:     document.studentform.submit();
 5809: }
 5810: 
 5811: function updateCols(caller) {
 5812:     var context = '$context';
 5813:     var photos = '$photos';
 5814:     if (caller == 'Status') {
 5815:         if ((context == 'domain') && 
 5816:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5817:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5818:             document.getElementById('showcolstatus').checked = false;
 5819:             document.getElementById('showcolstatus').disabled = 'disabled';
 5820:             document.getElementById('showcolstart').checked = false;
 5821:             document.getElementById('showcolend').checked = false;
 5822:         } else {
 5823:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5824:                 document.getElementById('showcolstatus').checked = true;
 5825:                 document.getElementById('showcolstatus').disabled = '';
 5826:                 document.getElementById('showcolstart').checked = true;
 5827:                 document.getElementById('showcolend').checked = true;
 5828:             } else {
 5829:                 document.getElementById('showcolstatus').checked = false;
 5830:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5831:                 document.getElementById('showcolstart').checked = false;
 5832:                 document.getElementById('showcolend').checked = false;
 5833:             }
 5834:         }
 5835:     }
 5836:     if (caller == 'output') {
 5837:         if (photos == 1) {
 5838:             if (document.getElementById('showcolphoto')) {
 5839:                 var photoitem = document.getElementById('showcolphoto');
 5840:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5841:                     photoitem.checked = true;
 5842:                     photoitem.disabled = '';
 5843:                 } else {
 5844:                     photoitem.checked = false;
 5845:                     photoitem.disabled = 'disabled';
 5846:                 }
 5847:             }
 5848:         }
 5849:     }
 5850:     if (caller == 'showrole') {
 5851:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5852:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5853:             document.getElementById('showcolrole').checked = true;
 5854:             document.getElementById('showcolrole').disabled = '';
 5855:         } else {
 5856:             document.getElementById('showcolrole').checked = false;
 5857:             document.getElementById('showcolrole').disabled = 'disabled';
 5858:         }
 5859:         if (context == 'domain') {
 5860:             var quotausageshow = 0;
 5861:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5862:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5863:                 document.getElementById('showcolstatus').checked = false;
 5864:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5865:                 document.getElementById('showcolstart').checked = false;
 5866:                 document.getElementById('showcolend').checked = false;
 5867:             } else {
 5868:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5869:                     document.getElementById('showcolstatus').checked = true;
 5870:                     document.getElementById('showcolstatus').disabled = '';
 5871:                     document.getElementById('showcolstart').checked = true;
 5872:                     document.getElementById('showcolend').checked = true;
 5873:                 }
 5874:             }
 5875:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5876:                 document.getElementById('showcolextent').disabled = 'disabled';
 5877:                 document.getElementById('showcolextent').checked = 'false';
 5878:                 document.getElementById('showextent').style.display='none';
 5879:                 document.getElementById('showcoltextextent').innerHTML = '';
 5880:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5881:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5882:                     if (document.getElementById('showcolauthorusage')) {
 5883:                         document.getElementById('showcolauthorusage').disabled = '';
 5884:                     }
 5885:                     if (document.getElementById('showcolauthorquota')) {
 5886:                         document.getElementById('showcolauthorquota').disabled = '';
 5887:                     }
 5888:                     quotausageshow = 1;
 5889:                 }
 5890:             } else {
 5891:                 document.getElementById('showextent').style.display='block';
 5892:                 document.getElementById('showextent').style.textAlign='left';
 5893:                 document.getElementById('showextent').style.textFace='normal';
 5894:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5895:                     document.getElementById('showcolextent').disabled = '';
 5896:                     document.getElementById('showcolextent').checked = 'true';
 5897:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5898:                 } else {
 5899:                     document.getElementById('showcolextent').disabled = '';
 5900:                     document.getElementById('showcolextent').checked = 'true';
 5901:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5902:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5903:                     } else {
 5904:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5905:                     }
 5906:                 }
 5907:             }
 5908:             if (quotausageshow == 0)  {
 5909:                 if (document.getElementById('showcolauthorusage')) {
 5910:                     document.getElementById('showcolauthorusage').checked = false;
 5911:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5912:                 }
 5913:                 if (document.getElementById('showcolauthorquota')) {
 5914:                     document.getElementById('showcolauthorquota').checked = false;
 5915:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5916:                 }
 5917:             }
 5918:         }
 5919:     }
 5920:     return;
 5921: }
 5922: 
 5923: END
 5924:     return $output;
 5925: 
 5926: }
 5927: 
 5928: ###############################################################
 5929: ###############################################################
 5930: #  Menu Phase One
 5931: sub print_main_menu {
 5932:     my ($permission,$context,$crstype) = @_;
 5933:     my $linkcontext = $context;
 5934:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5935:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5936:         $linkcontext = lc($crstype);
 5937:         $stuterm = 'Members';
 5938:     }
 5939:     my %links = (
 5940:                 domain => {
 5941:                             upload     => 'Upload a File of Users',
 5942:                             singleuser => 'Add/Modify a User',
 5943:                             listusers  => 'Manage Users',
 5944:                             },
 5945:                 author => {
 5946:                             upload     => 'Upload a File of Co-authors',
 5947:                             singleuser => 'Add/Modify a Co-author',
 5948:                             listusers  => 'Manage Co-authors',
 5949:                             },
 5950:                 course => {
 5951:                             upload     => 'Upload a File of Course Users',
 5952:                             singleuser => 'Add/Modify a Course User',
 5953:                             listusers  => 'List and Modify Multiple Course Users',
 5954:                             },
 5955:                 community => {
 5956:                             upload     => 'Upload a File of Community Users',
 5957:                             singleuser => 'Add/Modify a Community User',
 5958:                             listusers  => 'List and Modify Multiple Community Users',
 5959:                            },
 5960:                 );
 5961:      my %linktitles = (
 5962:                 domain => {
 5963:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5964:                             listusers  => 'Show and manage users in this domain.',
 5965:                             },
 5966:                 author => {
 5967:                             singleuser => 'Add a user with a co- or assistant author role.',
 5968:                             listusers  => 'Show and manage co- or assistant authors.',
 5969:                             },
 5970:                 course => {
 5971:                             singleuser => 'Add a user with a certain role to this course.',
 5972:                             listusers  => 'Show and manage users in this course.',
 5973:                             },
 5974:                 community => {
 5975:                             singleuser => 'Add a user with a certain role to this community.',
 5976:                             listusers  => 'Show and manage users in this community.',
 5977:                            },
 5978:                 );
 5979:   if ($linkcontext eq 'domain') {
 5980:       unless ($permission->{'cusr'}) {
 5981:           $links{'domain'}{'singleuser'} = 'View a User';
 5982:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5983:       }
 5984:   } elsif ($linkcontext eq 'course') {
 5985:       unless ($permission->{'cusr'}) {
 5986:           $links{'course'}{'singleuser'} = 'View a Course User';
 5987:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5988:           $links{'course'}{'listusers'} = 'List Course Users';
 5989:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5990:       }
 5991:   } elsif ($linkcontext eq 'community') {
 5992:       unless ($permission->{'cusr'}) {
 5993:           $links{'community'}{'singleuser'} = 'View a Community User';
 5994:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5995:           $links{'community'}{'listusers'} = 'List Community Users';
 5996:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5997:       }
 5998:   }
 5999:   my @menu = ( {categorytitle => 'Single Users', 
 6000:          items =>
 6001:          [
 6002:             {
 6003:              linktext => $links{$linkcontext}{'singleuser'},
 6004:              icon => 'edit-redo.png',
 6005:              #help => 'Course_Change_Privileges',
 6006:              url => '/adm/createuser?action=singleuser',
 6007:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6008:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 6009:             },
 6010:          ]},
 6011: 
 6012:          {categorytitle => 'Multiple Users',
 6013:          items => 
 6014:          [
 6015:             {
 6016:              linktext => $links{$linkcontext}{'upload'},
 6017:              icon => 'uplusr.png',
 6018:              #help => 'Course_Create_Class_List',
 6019:              url => '/adm/createuser?action=upload',
 6020:              permission => $permission->{'cusr'},
 6021:              linktitle => 'Upload a CSV or a text file containing users.',
 6022:             },
 6023:             {
 6024:              linktext => $links{$linkcontext}{'listusers'},
 6025:              icon => 'mngcu.png',
 6026:              #help => 'Course_View_Class_List',
 6027:              url => '/adm/createuser?action=listusers',
 6028:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6029:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 6030:             },
 6031: 
 6032:          ]},
 6033: 
 6034:          {categorytitle => 'Administration',
 6035:          items => [ ]},
 6036:        );
 6037: 
 6038:     if ($context eq 'domain'){
 6039:         push(@{  $menu[0]->{items} }, # Single Users
 6040:             {
 6041:              linktext => 'User Access Log',
 6042:              icon => 'document-properties.png',
 6043:              #help => 'Domain_User_Access_Logs',
 6044:              url => '/adm/createuser?action=accesslogs',
 6045:              permission => $permission->{'activity'},
 6046:              linktitle => 'View user access log.',
 6047:             }
 6048:         );
 6049:         
 6050:         push(@{ $menu[2]->{items} }, #Category: Administration
 6051:             {
 6052:              linktext => 'Custom Roles',
 6053:              icon => 'emblem-photos.png',
 6054:              #help => 'Course_Editing_Custom_Roles',
 6055:              url => '/adm/createuser?action=custom',
 6056:              permission => $permission->{'custom'},
 6057:              linktitle => 'Configure a custom role.',
 6058:             },
 6059:             {
 6060:              linktext => 'Authoring Space Requests',
 6061:              icon => 'selfenrl-queue.png',
 6062:              #help => 'Domain_Role_Approvals',
 6063:              url => '/adm/createuser?action=processauthorreq',
 6064:              permission => $permission->{'cusr'},
 6065:              linktitle => 'Approve or reject author role requests',
 6066:             },
 6067:             {
 6068:              linktext => 'LON-CAPA Account Requests',
 6069:              icon => 'list-add.png',
 6070:              #help => 'Domain_Username_Approvals',
 6071:              url => '/adm/createuser?action=processusernamereq',
 6072:              permission => $permission->{'cusr'},
 6073:              linktitle => 'Approve or reject LON-CAPA account requests',
 6074:             },
 6075:             {
 6076:              linktext => 'Change Log',
 6077:              icon => 'document-properties.png',
 6078:              #help => 'Course_User_Logs',
 6079:              url => '/adm/createuser?action=changelogs',
 6080:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 6081:              linktitle => 'View change log.',
 6082:             },
 6083:         );
 6084:         
 6085:     }elsif ($context eq 'course'){
 6086:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 6087: 
 6088:         my %linktext = (
 6089:                          'Course'    => {
 6090:                                           single => 'Add/Modify a Student', 
 6091:                                           drop   => 'Drop Students',
 6092:                                           groups => 'Course Groups',
 6093:                                         },
 6094:                          'Community' => {
 6095:                                           single => 'Add/Modify a Member', 
 6096:                                           drop   => 'Drop Members',
 6097:                                           groups => 'Community Groups',
 6098:                                         },
 6099:                        );
 6100: 
 6101:         my %linktitle = (
 6102:             'Course' => {
 6103:                   single => 'Add a user with the role of student to this course',
 6104:                   drop   => 'Remove a student from this course.',
 6105:                   groups => 'Manage course groups',
 6106:                         },
 6107:             'Community' => {
 6108:                   single => 'Add a user with the role of member to this community',
 6109:                   drop   => 'Remove a member from this community.',
 6110:                   groups => 'Manage community groups',
 6111:                            },
 6112:         );
 6113: 
 6114:         push(@{ $menu[0]->{items} }, #Category: Single Users
 6115:             {   
 6116:              linktext => $linktext{$crstype}{'single'},
 6117:              #help => 'Course_Add_Student',
 6118:              icon => 'list-add.png',
 6119:              url => '/adm/createuser?action=singlestudent',
 6120:              permission => $permission->{'cusr'},
 6121:              linktitle => $linktitle{$crstype}{'single'},
 6122:             },
 6123:         );
 6124:         
 6125:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 6126:             {
 6127:              linktext => $linktext{$crstype}{'drop'},
 6128:              icon => 'edit-undo.png',
 6129:              #help => 'Course_Drop_Student',
 6130:              url => '/adm/createuser?action=drop',
 6131:              permission => $permission->{'cusr'},
 6132:              linktitle => $linktitle{$crstype}{'drop'},
 6133:             },
 6134:         );
 6135:         push(@{ $menu[2]->{items} }, #Category: Administration
 6136:             {
 6137:              linktext => 'Helpdesk Access',
 6138:              icon => 'helpdesk-access.png',
 6139:              #help => 'Course_Helpdesk_Access',
 6140:              url => '/adm/createuser?action=helpdesk',
 6141:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6142:                             ($permission->{'view'} || $permission->{'cusr'})),
 6143:              linktitle => 'Helpdesk access options',
 6144:             },
 6145:             {
 6146:              linktext => 'Custom Roles',
 6147:              icon => 'emblem-photos.png',
 6148:              #help => 'Course_Editing_Custom_Roles',
 6149:              url => '/adm/createuser?action=custom',
 6150:              permission => $permission->{'custom'},
 6151:              linktitle => 'Configure a custom role.',
 6152:             },
 6153:             {
 6154:              linktext => $linktext{$crstype}{'groups'},
 6155:              icon => 'grps.png',
 6156:              #help => 'Course_Manage_Group',
 6157:              url => '/adm/coursegroups?refpage=cusr',
 6158:              permission => $permission->{'grp_manage'},
 6159:              linktitle => $linktitle{$crstype}{'groups'},
 6160:             },
 6161:             {
 6162:              linktext => 'Change Log',
 6163:              icon => 'document-properties.png',
 6164:              #help => 'Course_User_Logs',
 6165:              url => '/adm/createuser?action=changelogs',
 6166:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6167:              linktitle => 'View change log.',
 6168:             },
 6169:         );
 6170:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 6171:             push(@{ $menu[2]->{items} },
 6172:                     {
 6173:                      linktext => 'Enrollment Requests',
 6174:                      icon => 'selfenrl-queue.png',
 6175:                      #help => 'Course_Approve_Selfenroll',
 6176:                      url => '/adm/createuser?action=selfenrollqueue',
 6177:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6178:                      linktitle =>'Approve or reject enrollment requests.',
 6179:                     },
 6180:             );
 6181:         }
 6182:         
 6183:         if (!exists($permission->{'cusr_section'})){
 6184:             if ($crstype ne 'Community') {
 6185:                 push(@{ $menu[2]->{items} },
 6186:                     {
 6187:                      linktext => 'Automated Enrollment',
 6188:                      icon => 'roles.png',
 6189:                      #help => 'Course_Automated_Enrollment',
 6190:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 6191:                                          && (($permission->{'cusr'}) ||
 6192:                                              ($permission->{'view'}))),
 6193:                      url  => '/adm/populate',
 6194:                      linktitle => 'Automated enrollment manager.',
 6195:                     }
 6196:                 );
 6197:             }
 6198:             push(@{ $menu[2]->{items} }, 
 6199:                 {
 6200:                  linktext => 'User Self-Enrollment',
 6201:                  icon => 'self_enroll.png',
 6202:                  #help => 'Course_Self_Enrollment',
 6203:                  url => '/adm/createuser?action=selfenroll',
 6204:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6205:                  linktitle => 'Configure user self-enrollment.',
 6206:                 },
 6207:             );
 6208:         }
 6209:     } elsif ($context eq 'author') {
 6210:         push(@{ $menu[2]->{items} }, #Category: Administration
 6211:             {
 6212:              linktext => 'Change Log',
 6213:              icon => 'document-properties.png',
 6214:              #help => 'Course_User_Logs',
 6215:              url => '/adm/createuser?action=changelogs',
 6216:              permission => $permission->{'cusr'},
 6217:              linktitle => 'View change log.',
 6218:             },
 6219:         );
 6220:     }
 6221:     return Apache::lonhtmlcommon::generate_menu(@menu);
 6222: #               { text => 'View Log-in History',
 6223: #                 help => 'Course_User_Logins',
 6224: #                 action => 'logins',
 6225: #                 permission => $permission->{'cusr'},
 6226: #               });
 6227: }
 6228: 
 6229: sub restore_prev_selections {
 6230:     my %saveable_parameters = ('srchby'   => 'scalar',
 6231: 			       'srchin'   => 'scalar',
 6232: 			       'srchtype' => 'scalar',
 6233: 			       );
 6234:     &Apache::loncommon::store_settings('user','user_picker',
 6235: 				       \%saveable_parameters);
 6236:     &Apache::loncommon::restore_settings('user','user_picker',
 6237: 					 \%saveable_parameters);
 6238: }
 6239: 
 6240: sub print_selfenroll_menu {
 6241:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 6242:     my $crstype = &Apache::loncommon::course_type();
 6243:     my $formname = 'selfenroll';
 6244:     my $nolink = 1;
 6245:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 6246:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 6247:     my $setsec_js = 
 6248:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 6249:     my %alerts = &Apache::lonlocal::texthash(
 6250:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 6251:         butn => 'but no user types have been checked.',
 6252:         wilf => "Please uncheck 'activate' or check at least one type.",
 6253:     );
 6254:     my $disabled;
 6255:     if ($readonly) {
 6256:        $disabled = ' disabled="disabled"';
 6257:     }
 6258:     &js_escape(\%alerts);
 6259:     my $selfenroll_js = <<"ENDSCRIPT";
 6260: function update_types(caller,num) {
 6261:     var delidx = getIndexByName('selfenroll_delete');
 6262:     var actidx = getIndexByName('selfenroll_activate');
 6263:     if (caller == 'selfenroll_all') {
 6264:         var selall;
 6265:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 6266:             if (document.$formname.selfenroll_all[i].checked) {
 6267:                 selall = document.$formname.selfenroll_all[i].value;
 6268:             }
 6269:         }
 6270:         if (selall == 1) {
 6271:             if (delidx != -1) {
 6272:                 if (document.$formname.selfenroll_delete.length) {
 6273:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 6274:                         document.$formname.selfenroll_delete[j].checked = true;
 6275:                     }
 6276:                 } else {
 6277:                     document.$formname.elements[delidx].checked = true;
 6278:                 }
 6279:             }
 6280:             if (actidx != -1) {
 6281:                 if (document.$formname.selfenroll_activate.length) {
 6282:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 6283:                         document.$formname.selfenroll_activate[j].checked = false;
 6284:                     }
 6285:                 } else {
 6286:                     document.$formname.elements[actidx].checked = false;
 6287:                 }
 6288:             }
 6289:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 6290:         }
 6291:     }
 6292:     if (caller == 'selfenroll_activate') {
 6293:         if (document.$formname.selfenroll_activate.length) {
 6294:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 6295:                 if (document.$formname.selfenroll_activate[j].value == num) {
 6296:                     if (document.$formname.selfenroll_activate[j].checked) {
 6297:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 6298:                             if (document.$formname.selfenroll_all[i].value == '1') {
 6299:                                 document.$formname.selfenroll_all[i].checked = false;
 6300:                             }
 6301:                             if (document.$formname.selfenroll_all[i].value == '0') {
 6302:                                 document.$formname.selfenroll_all[i].checked = true;
 6303:                             }
 6304:                         }
 6305:                     }
 6306:                 }
 6307:             }
 6308:         } else {
 6309:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 6310:                 if (document.$formname.selfenroll_all[i].value == '1') {
 6311:                     document.$formname.selfenroll_all[i].checked = false;
 6312:                 }
 6313:                 if (document.$formname.selfenroll_all[i].value == '0') {
 6314:                     document.$formname.selfenroll_all[i].checked = true;
 6315:                 }
 6316:             }
 6317:         }
 6318:     }
 6319:     if (caller == 'selfenroll_delete') {
 6320:         if (document.$formname.selfenroll_delete.length) {
 6321:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 6322:                 if (document.$formname.selfenroll_delete[j].value == num) {
 6323:                     if (document.$formname.selfenroll_delete[j].checked) {
 6324:                         var delindex = getIndexByName('selfenroll_types_'+num);
 6325:                         if (delindex != -1) { 
 6326:                             if (document.$formname.elements[delindex].length) {
 6327:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 6328:                                     document.$formname.elements[delindex][k].checked = false;
 6329:                                 }
 6330:                             } else {
 6331:                                 document.$formname.elements[delindex].checked = false;
 6332:                             }
 6333:                         }
 6334:                     }
 6335:                 }
 6336:             }
 6337:         } else {
 6338:             if (document.$formname.selfenroll_delete.checked) {
 6339:                 var delindex = getIndexByName('selfenroll_types_'+num);
 6340:                 if (delindex != -1) {
 6341:                     if (document.$formname.elements[delindex].length) {
 6342:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 6343:                             document.$formname.elements[delindex][k].checked = false;
 6344:                         }
 6345:                     } else {
 6346:                         document.$formname.elements[delindex].checked = false;
 6347:                     }
 6348:                 }
 6349:             }
 6350:         }
 6351:     }
 6352:     return;
 6353: }
 6354: 
 6355: function validate_types(form) {
 6356:     var needaction = new Array();
 6357:     var countfail = 0;
 6358:     var actidx = getIndexByName('selfenroll_activate');
 6359:     if (actidx != -1) {
 6360:         if (document.$formname.selfenroll_activate.length) {
 6361:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 6362:                 var num = document.$formname.selfenroll_activate[j].value;
 6363:                 if (document.$formname.selfenroll_activate[j].checked) {
 6364:                     countfail = check_types(num,countfail,needaction)
 6365:                 }
 6366:             }
 6367:         } else {
 6368:             if (document.$formname.selfenroll_activate.checked) {
 6369:                 var num = document.$formname.selfenroll_activate.value;
 6370:                 countfail = check_types(num,countfail,needaction)
 6371:             }
 6372:         }
 6373:     }
 6374:     if (countfail > 0) {
 6375:         var msg = "$alerts{'acto'}\\n";
 6376:         var loopend = needaction.length -1;
 6377:         if (loopend > 0) {
 6378:             for (var m=0; m<loopend; m++) {
 6379:                 msg += needaction[m]+", ";
 6380:             }
 6381:         }
 6382:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 6383:         alert(msg);
 6384:         return; 
 6385:     }
 6386:     setSections(form);
 6387: }
 6388: 
 6389: function check_types(num,countfail,needaction) {
 6390:     var boxname = 'selfenroll_types_'+num;
 6391:     var typeidx = getIndexByName(boxname);
 6392:     var count = 0;
 6393:     if (typeidx != -1) {
 6394:         if (document.$formname.elements[boxname].length) {
 6395:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 6396:                 if (document.$formname.elements[boxname][k].checked) {
 6397:                     count ++;
 6398:                 }
 6399:             }
 6400:         } else {
 6401:             if (document.$formname.elements[typeidx].checked) {
 6402:                 count ++;
 6403:             }
 6404:         }
 6405:         if (count == 0) {
 6406:             var domidx = getIndexByName('selfenroll_dom_'+num);
 6407:             if (domidx != -1) {
 6408:                 var domname = document.$formname.elements[domidx].value;
 6409:                 needaction[countfail] = domname;
 6410:                 countfail ++;
 6411:             }
 6412:         }
 6413:     }
 6414:     return countfail;
 6415: }
 6416: 
 6417: function toggleNotify() {
 6418:     var selfenrollApproval = 0;
 6419:     if (document.$formname.selfenroll_approval.length) {
 6420:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 6421:             if (document.$formname.selfenroll_approval[i].checked) {
 6422:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 6423:                 break;        
 6424:             }
 6425:         }
 6426:     }
 6427:     if (document.getElementById('notified')) {
 6428:         if (selfenrollApproval == 0) {
 6429:             document.getElementById('notified').style.display='none';
 6430:         } else {
 6431:             document.getElementById('notified').style.display='block';
 6432:         }
 6433:     }
 6434:     return;
 6435: }
 6436: 
 6437: function getIndexByName(item) {
 6438:     for (var i=0;i<document.$formname.elements.length;i++) {
 6439:         if (document.$formname.elements[i].name == item) {
 6440:             return i;
 6441:         }
 6442:     }
 6443:     return -1;
 6444: }
 6445: ENDSCRIPT
 6446: 
 6447:     my $output = '<script type="text/javascript">'."\n".
 6448:                  '// <![CDATA['."\n".
 6449:                  $setsec_js."\n".$selfenroll_js."\n".
 6450:                  '// ]]>'."\n".
 6451:                  '</script>'."\n".
 6452:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 6453:     my $visactions = &cat_visibility($cdom);
 6454:     my ($cathash,%cattype);
 6455:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 6456:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 6457:         $cathash = $domconfig{'coursecategories'}{'cats'};
 6458:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 6459:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 6460:         if ($cattype{'auth'} eq '') {
 6461:             $cattype{'auth'} = 'std';
 6462:         }
 6463:         if ($cattype{'unauth'} eq '') {
 6464:             $cattype{'unauth'} = 'std';
 6465:         }
 6466:     } else {
 6467:         $cathash = {};
 6468:         $cattype{'auth'} = 'std';
 6469:         $cattype{'unauth'} = 'std';
 6470:     }
 6471:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 6472:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6473:                   '<br />'.
 6474:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6475:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 6476:                   '</ul>');
 6477:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 6478:         if ($currsettings->{'uniquecode'}) {
 6479:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 6480:         } else {
 6481:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6482:                   '<br />'.
 6483:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6484:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 6485:                   '</ul><br />');
 6486:         }
 6487:     } else {
 6488:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 6489:         if (ref($visactions) eq 'HASH') {
 6490:             if ($visible) {
 6491:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 6492:            } else {
 6493:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 6494:                           .$visactions->{'yous'}.
 6495:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 6496:                 if (ref($vismsgs) eq 'ARRAY') {
 6497:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 6498:                     foreach my $item (@{$vismsgs}) {
 6499:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 6500:                     }
 6501:                     $output .= '</ul>';
 6502:                 }
 6503:                 $output .= '</p>';
 6504:             }
 6505:         }
 6506:     }
 6507:     my $actionhref = '/adm/createuser';
 6508:     if ($context eq 'domain') {
 6509:         $actionhref = '/adm/modifycourse';
 6510:     }
 6511: 
 6512:     my %noedit;
 6513:     unless ($context eq 'domain') {
 6514:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 6515:     }
 6516:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6517:                &Apache::lonhtmlcommon::start_pick_box();
 6518:     if (ref($row) eq 'ARRAY') {
 6519:         foreach my $item (@{$row}) {
 6520:             my $title = $item; 
 6521:             if (ref($lt) eq 'HASH') {
 6522:                 $title = $lt->{$item};
 6523:             }
 6524:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6525:             if ($item eq 'types') {
 6526:                 my $curr_types;
 6527:                 if (ref($currsettings) eq 'HASH') {
 6528:                     $curr_types = $currsettings->{'selfenroll_types'};
 6529:                 }
 6530:                 if ($noedit{$item}) {
 6531:                     if ($curr_types eq '*') {
 6532:                         $output .= &mt('Any user in any domain');   
 6533:                     } else {
 6534:                         my @entries = split(/;/,$curr_types);
 6535:                         if (@entries > 0) {
 6536:                             $output .= '<ul>'; 
 6537:                             foreach my $entry (@entries) {
 6538:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6539:                                 next if ($typestr eq '');
 6540:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6541:                                 my @currinsttypes = split(',',$typestr);
 6542:                                 my ($othertitle,$usertypes,$types) = 
 6543:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6544:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6545:                                     $usertypes->{'any'} = &mt('any user'); 
 6546:                                     if (keys(%{$usertypes}) > 0) {
 6547:                                         $usertypes->{'other'} = &mt('other users');
 6548:                                     }
 6549:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6550:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6551:                                  }
 6552:                             }
 6553:                             $output .= '</ul>';
 6554:                         } else {
 6555:                             $output .= &mt('None');
 6556:                         }
 6557:                     }
 6558:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6559:                     next;
 6560:                 }
 6561:                 my $showdomdesc = 1;
 6562:                 my $includeempty = 1;
 6563:                 my $num = 0;
 6564:                 $output .= &Apache::loncommon::start_data_table().
 6565:                            &Apache::loncommon::start_data_table_row()
 6566:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6567:                            .&mt('Any user in any domain:')
 6568:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6569:                 if ($curr_types eq '*') {
 6570:                     $output .= ' checked="checked" '; 
 6571:                 }
 6572:                 $output .= 'onchange="javascript:update_types('.
 6573:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6574:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6575:                 if ($curr_types ne '*') {
 6576:                     $output .= ' checked="checked" ';
 6577:                 }
 6578:                 $output .= ' onchange="javascript:update_types('.
 6579:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6580:                            &Apache::loncommon::end_data_table_row().
 6581:                            &Apache::loncommon::end_data_table().
 6582:                            &mt('Or').'<br />'.
 6583:                            &Apache::loncommon::start_data_table();
 6584:                 my %currdoms;
 6585:                 if ($curr_types eq '') {
 6586:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6587:                 } elsif ($curr_types ne '*') {
 6588:                     my @entries = split(/;/,$curr_types);
 6589:                     if (@entries > 0) {
 6590:                         foreach my $entry (@entries) {
 6591:                             my ($currdom,$typestr) = split(/:/,$entry);
 6592:                             $currdoms{$currdom} = 1;
 6593:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6594:                             my @currinsttypes = split(',',$typestr);
 6595:                             $output .= &Apache::loncommon::start_data_table_row()
 6596:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6597:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6598:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6599:                                        .'" value="'.$currdom.'" /></span><br />'
 6600:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6601:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6602:                                        .&mt('Delete').'</label></span></td>';
 6603:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6604:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6605:                                        .&Apache::loncommon::end_data_table_row();
 6606:                             $num ++;
 6607:                         }
 6608:                     }
 6609:                 }
 6610:                 my $add_domtitle = &mt('Users in additional domain:');
 6611:                 if ($curr_types eq '*') { 
 6612:                     $add_domtitle = &mt('Users in specific domain:');
 6613:                 } elsif ($curr_types eq '') {
 6614:                     $add_domtitle = &mt('Users in other domain:');
 6615:                 }
 6616:                 $output .= &Apache::loncommon::start_data_table_row()
 6617:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6618:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6619:                                                                 $includeempty,$showdomdesc,'','','',$readonly)
 6620:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6621:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6622:                            .&Apache::loncommon::end_data_table();
 6623:             } elsif ($item eq 'registered') {
 6624:                 my ($regon,$regoff);
 6625:                 my $registered;
 6626:                 if (ref($currsettings) eq 'HASH') {
 6627:                     $registered = $currsettings->{'selfenroll_registered'};
 6628:                 }
 6629:                 if ($noedit{$item}) {
 6630:                     if ($registered) {
 6631:                         $output .= &mt('Must be registered in course');
 6632:                     } else {
 6633:                         $output .= &mt('No requirement');
 6634:                     }
 6635:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6636:                     next;
 6637:                 }
 6638:                 if ($registered) {
 6639:                     $regon = ' checked="checked" ';
 6640:                     $regoff = '';
 6641:                 } else {
 6642:                     $regon = '';
 6643:                     $regoff = ' checked="checked" ';
 6644:                 }
 6645:                 $output .= '<label>'.
 6646:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6647:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6648:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6649:                            &mt('No').'</label>';
 6650:             } elsif ($item eq 'enroll_dates') {
 6651:                 my ($starttime,$endtime);
 6652:                 if (ref($currsettings) eq 'HASH') {
 6653:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6654:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6655:                     if ($starttime eq '') {
 6656:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6657:                     }
 6658:                     if ($endtime eq '') {
 6659:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6660:                     }
 6661:                 }
 6662:                 if ($noedit{$item}) {
 6663:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6664:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6665:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6666:                     next;
 6667:                 }
 6668:                 my $startform =
 6669:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6670:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6671:                 my $endform =
 6672:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6673:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6674:                 $output .= &selfenroll_date_forms($startform,$endform);
 6675:             } elsif ($item eq 'access_dates') {
 6676:                 my ($starttime,$endtime);
 6677:                 if (ref($currsettings) eq 'HASH') {
 6678:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6679:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6680:                     if ($starttime eq '') {
 6681:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6682:                     }
 6683:                     if ($endtime eq '') {
 6684:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6685:                     }
 6686:                 }
 6687:                 if ($noedit{$item}) {
 6688:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6689:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6690:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6691:                     next;
 6692:                 }
 6693:                 my $startform =
 6694:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6695:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6696:                 my $endform =
 6697:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6698:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6699:                 $output .= &selfenroll_date_forms($startform,$endform);
 6700:             } elsif ($item eq 'section') {
 6701:                 my $currsec;
 6702:                 if (ref($currsettings) eq 'HASH') {
 6703:                     $currsec = $currsettings->{'selfenroll_section'};
 6704:                 }
 6705:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6706:                 my $newsecval;
 6707:                 if ($currsec ne 'none' && $currsec ne '') {
 6708:                     if (!defined($sections_count{$currsec})) {
 6709:                         $newsecval = $currsec;
 6710:                     }
 6711:                 }
 6712:                 if ($noedit{$item}) {
 6713:                     if ($currsec ne '') {
 6714:                         $output .= $currsec;
 6715:                     } else {
 6716:                         $output .= &mt('No specific section');
 6717:                     }
 6718:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6719:                     next;
 6720:                 }
 6721:                 my $sections_select = 
 6722:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6723:                 $output .= '<table class="LC_createuser">'."\n".
 6724:                            '<tr class="LC_section_row">'."\n".
 6725:                            '<td align="center">'.&mt('Existing sections')."\n".
 6726:                            '<br />'.$sections_select.'</td><td align="center">'.
 6727:                            &mt('New section').'<br />'."\n".
 6728:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6729:                            '<input type="hidden" name="sections" value="" />'."\n".
 6730:                            '</td></tr></table>'."\n";
 6731:             } elsif ($item eq 'approval') {
 6732:                 my ($currnotified,$currapproval,%appchecked);
 6733:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6734:                 if (ref($currsettings) eq 'HASH') {
 6735:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6736:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6737:                 }
 6738:                 if ($currapproval !~ /^[012]$/) {
 6739:                     $currapproval = 0;
 6740:                 }
 6741:                 if ($noedit{$item}) {
 6742:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6743:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6744:                     next;
 6745:                 }
 6746:                 $appchecked{$currapproval} = ' checked="checked"';
 6747:                 for my $i (0..2) {
 6748:                     $output .= '<label>'.
 6749:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6750:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6751:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6752:                 }
 6753:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6754:                 my (@ccs,%notified);
 6755:                 my $ccrole = 'cc';
 6756:                 if ($crstype eq 'Community') {
 6757:                     $ccrole = 'co';
 6758:                 }
 6759:                 if ($advhash{$ccrole}) {
 6760:                     @ccs = split(/,/,$advhash{$ccrole});
 6761:                 }
 6762:                 if ($currnotified) {
 6763:                     foreach my $current (split(/,/,$currnotified)) {
 6764:                         $notified{$current} = 1;
 6765:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6766:                             push(@ccs,$current);
 6767:                         }
 6768:                     }
 6769:                 }
 6770:                 if (@ccs) {
 6771:                     my $style;
 6772:                     unless ($currapproval) {
 6773:                         $style = ' style="display: none;"'; 
 6774:                     }
 6775:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6776:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6777:                                &Apache::loncommon::start_data_table().
 6778:                                &Apache::loncommon::start_data_table_row();
 6779:                     my $count = 0;
 6780:                     my $numcols = 4;
 6781:                     foreach my $cc (sort(@ccs)) {
 6782:                         my $notifyon;
 6783:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6784:                         if ($notified{$cc}) {
 6785:                             $notifyon = ' checked="checked" ';
 6786:                         }
 6787:                         if ($count && !$count%$numcols) {
 6788:                             $output .= &Apache::loncommon::end_data_table_row().
 6789:                                        &Apache::loncommon::start_data_table_row()
 6790:                         }
 6791:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6792:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6793:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6794:                                    '</label></span></td>';
 6795:                         $count ++;
 6796:                     }
 6797:                     my $rem = $count%$numcols;
 6798:                     if ($rem) {
 6799:                         my $emptycols = $numcols - $rem;
 6800:                         for (my $i=0; $i<$emptycols; $i++) { 
 6801:                             $output .= '<td>&nbsp;</td>';
 6802:                         }
 6803:                     }
 6804:                     $output .= &Apache::loncommon::end_data_table_row().
 6805:                                &Apache::loncommon::end_data_table().
 6806:                                '</div>';
 6807:                 }
 6808:             } elsif ($item eq 'limit') {
 6809:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6810:                 if (ref($currsettings) eq 'HASH') {
 6811:                     $currlim = $currsettings->{'selfenroll_limit'};
 6812:                     $currcap = $currsettings->{'selfenroll_cap'};
 6813:                 }
 6814:                 if ($noedit{$item}) {
 6815:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6816:                         if ($currlim eq 'allstudents') {
 6817:                             $output .= &mt('Limit by total students');
 6818:                         } elsif ($currlim eq 'selfenrolled') {
 6819:                             $output .= &mt('Limit by total self-enrolled students');
 6820:                         }
 6821:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6822:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6823:                     } else {
 6824:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6825:                     }
 6826:                     next;
 6827:                 }
 6828:                 if ($currlim eq 'allstudents') {
 6829:                     $crslimit = ' checked="checked" ';
 6830:                     $selflimit = ' ';
 6831:                     $nolimit = ' ';
 6832:                 } elsif ($currlim eq 'selfenrolled') {
 6833:                     $crslimit = ' ';
 6834:                     $selflimit = ' checked="checked" ';
 6835:                     $nolimit = ' '; 
 6836:                 } else {
 6837:                     $crslimit = ' ';
 6838:                     $selflimit = ' ';
 6839:                     $nolimit = ' checked="checked" ';
 6840:                 }
 6841:                 $output .= '<table><tr><td><label>'.
 6842:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6843:                            &mt('No limit').'</label></td><td><label>'.
 6844:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6845:                            &mt('Limit by total students').'</label></td><td><label>'.
 6846:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6847:                            &mt('Limit by total self-enrolled students').
 6848:                            '</td></tr><tr>'.
 6849:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6850:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6851:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6852:             }
 6853:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6854:         }
 6855:     }
 6856:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6857:     unless ($readonly) {
 6858:         $output .= '<input type="button" name="selfenrollconf" value="'
 6859:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6860:     }
 6861:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6862:               .'<input type="hidden" name="state" value="done" />'."\n"
 6863:               .$additional.'</form>';
 6864:     $r->print($output);
 6865:     return;
 6866: }
 6867: 
 6868: sub get_noedit_fields {
 6869:     my ($cdom,$cnum,$crstype,$row) = @_;
 6870:     my %noedit;
 6871:     if (ref($row) eq 'ARRAY') {
 6872:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6873:                                                            'internal.selfenrollmgrdc',
 6874:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6875:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6876:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6877:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6878:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6879:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6880:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6881: 
 6882:         foreach my $item (@{$row}) {
 6883:             next if ($specific_managebycc{$item});
 6884:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6885:                 $noedit{$item} = 1;
 6886:             }
 6887:         }
 6888:     }
 6889:     return %noedit;
 6890: } 
 6891: 
 6892: sub visible_in_stdcat {
 6893:     my ($cdom,$cnum,$domconf) = @_;
 6894:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6895:     unless (ref($domconf) eq 'HASH') {
 6896:         return ($visible,$cansetvis,\@vismsgs);
 6897:     }
 6898:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6899:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6900:             $settable{'togglecats'} = 1;
 6901:         }
 6902:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6903:             $settable{'categorize'} = 1;
 6904:         }
 6905:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6906:     }
 6907:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6908:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6909:     } elsif ($settable{'togglecats'}) {
 6910:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6911:     } elsif ($settable{'categorize'}) {
 6912:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6913:     } else {
 6914:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6915:     }
 6916:      
 6917:     my %currsettings =
 6918:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6919:                              $cdom,$cnum);
 6920:     $visible = 0;
 6921:     if ($currsettings{'internal.coursecode'} ne '') {
 6922:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6923:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6924:             if (ref($cathash) eq 'HASH') {
 6925:                 if ($cathash->{'instcode::0'} eq '') {
 6926:                     push(@vismsgs,'dc_addinst'); 
 6927:                 } else {
 6928:                     $visible = 1;
 6929:                 }
 6930:             } else {
 6931:                 $visible = 1;
 6932:             }
 6933:         } else {
 6934:             $visible = 1;
 6935:         }
 6936:     } else {
 6937:         if (ref($cathash) eq 'HASH') {
 6938:             if ($cathash->{'instcode::0'} ne '') {
 6939:                 push(@vismsgs,'dc_instcode');
 6940:             }
 6941:         } else {
 6942:             push(@vismsgs,'dc_instcode');
 6943:         }
 6944:     }
 6945:     if ($currsettings{'categories'} ne '') {
 6946:         my $cathash;
 6947:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6948:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6949:             if (ref($cathash) eq 'HASH') {
 6950:                 if (keys(%{$cathash}) == 0) {
 6951:                     push(@vismsgs,'dc_catalog');
 6952:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6953:                     push(@vismsgs,'dc_categories');
 6954:                 } else {
 6955:                     my @currcategories = split('&',$currsettings{'categories'});
 6956:                     my $matched = 0;
 6957:                     foreach my $cat (@currcategories) {
 6958:                         if ($cathash->{$cat} ne '') {
 6959:                             $visible = 1;
 6960:                             $matched = 1;
 6961:                             last;
 6962:                         }
 6963:                     }
 6964:                     if (!$matched) {
 6965:                         if ($settable{'categorize'}) { 
 6966:                             push(@vismsgs,'chgcat');
 6967:                         } else {
 6968:                             push(@vismsgs,'dc_chgcat');
 6969:                         }
 6970:                     }
 6971:                 }
 6972:             }
 6973:         }
 6974:     } else {
 6975:         if (ref($cathash) eq 'HASH') {
 6976:             if ((keys(%{$cathash}) > 1) || 
 6977:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6978:                 if ($settable{'categorize'}) {
 6979:                     push(@vismsgs,'addcat');
 6980:                 } else {
 6981:                     push(@vismsgs,'dc_addcat');
 6982:                 }
 6983:             }
 6984:         }
 6985:     }
 6986:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6987:         $visible = 0;
 6988:         if ($settable{'togglecats'}) {
 6989:             unshift(@vismsgs,'unhide');
 6990:         } else {
 6991:             unshift(@vismsgs,'dc_unhide')
 6992:         }
 6993:     }
 6994:     return ($visible,$cansetvis,\@vismsgs);
 6995: }
 6996: 
 6997: sub cat_visibility {
 6998:     my ($cdom) = @_;
 6999:     my %visactions = &Apache::lonlocal::texthash(
 7000:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 7001:                    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.',
 7002:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 7003:                    none => 'Display of a course catalog is disabled for this domain.',
 7004:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 7005:                    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.',
 7006:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 7007:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 7008:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 7009:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 7010:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 7011:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 7012:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 7013:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 7014:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 7015:                    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',
 7016:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 7017:     );
 7018:     if ($env{'request.role'} eq "dc./$cdom/") {
 7019:         $visactions{'dc_chgconf'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to change the Catalog type for this domain.','&raquo;');
 7020:         $visactions{'dc_setcode'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to assign a six character code to the course.','&raquo;');
 7021:         $visactions{'dc_unhide'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to change the "Exclude from course catalog" setting.','&raquo;');
 7022:         $visactions{'dc_addinst'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to enable catalog display of "Official courses (with institutional codes)".','&raquo;');
 7023:         $visactions{'dc_instcode'} = &mt('Use: "Main menu" [_1] "View or modify a course or community" [_1] "View/Modify course owner, institutional code ... " to assign an institutional code (if this is an official course).','&raquo;');
 7024:         $visactions{'dc_catalog'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to enable or create at least one course category in the domain.','&raquo;');
 7025:         $visactions{'dc_categories'} = &mt('Use: "Main menu" [_1] "Set domain configuration" [_1] "Cataloging of courses/communities" to create a hierarchy of categories and sub categories for courses in the domain.','&raquo;');
 7026:         $visactions{'dc_chgcat'} = &mt('Use: "Main menu" [_1] "View or modify a course or community" [_1] "View/Modify catalog settings for course" to change the category assigned to the course, as the one currently assigned is no longer used in the domain.','&raquo;');
 7027:         $visactions{'dc_addcat'} = &mt('Use: "Main menu" [_1] "View or modify a course or community" [_1] "View/Modify catalog settings for course" to assign a category to the course.','&raquo;');
 7028:     }
 7029:     $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>"');
 7030:     $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>"');
 7031:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 7032:     return \%visactions;
 7033: }
 7034: 
 7035: sub new_selfenroll_dom_row {
 7036:     my ($newdom,$num) = @_;
 7037:     my $domdesc = &Apache::lonnet::domain($newdom);
 7038:     my $output;
 7039:     if ($domdesc ne '') {
 7040:         $output .= &Apache::loncommon::start_data_table_row()
 7041:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 7042:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 7043:                    .'" value="'.$newdom.'" /></span><br />'
 7044:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 7045:                    .'name="selfenroll_activate" value="'.$num.'" '
 7046:                    .'onchange="javascript:update_types('
 7047:                    ."'selfenroll_activate','$num'".');" />'
 7048:                    .&mt('Activate').'</label></span></td>';
 7049:         my @currinsttypes;
 7050:         $output .= '<td>'.&mt('User types:').'<br />'
 7051:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 7052:                    .&Apache::loncommon::end_data_table_row();
 7053:     }
 7054:     return $output;
 7055: }
 7056: 
 7057: sub selfenroll_inst_types {
 7058:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 7059:     my $output;
 7060:     my $numinrow = 4;
 7061:     my $count = 0;
 7062:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 7063:     my $othervalue = 'any';
 7064:     my $disabled;
 7065:     if ($readonly) {
 7066:         $disabled = ' disabled="disabled"';
 7067:     }
 7068:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7069:         if (keys(%{$usertypes}) > 0) {
 7070:             $othervalue = 'other';
 7071:         }
 7072:         $output .= '<table><tr>';
 7073:         foreach my $type (@{$types}) {
 7074:             if (($count > 0) && ($count%$numinrow == 0)) {
 7075:                 $output .= '</tr><tr>';
 7076:             }
 7077:             if (defined($usertypes->{$type})) {
 7078:                 my $esc_type = &escape($type);
 7079:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 7080:                            $esc_type.'" ';
 7081:                 if (ref($currinsttypes) eq 'ARRAY') {
 7082:                     if (@{$currinsttypes} > 0) {
 7083:                         if (grep(/^any$/,@{$currinsttypes})) {
 7084:                             $output .= 'checked="checked"';
 7085:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 7086:                             $output .= 'checked="checked"';
 7087:                         }
 7088:                     } else {
 7089:                         $output .= 'checked="checked"';
 7090:                     }
 7091:                 }
 7092:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 7093:             }
 7094:             $count ++;
 7095:         }
 7096:         if (($count > 0) && ($count%$numinrow == 0)) {
 7097:             $output .= '</tr><tr>';
 7098:         }
 7099:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 7100:         if (ref($currinsttypes) eq 'ARRAY') {
 7101:             if (@{$currinsttypes} > 0) {
 7102:                 if (grep(/^any$/,@{$currinsttypes})) { 
 7103:                     $output .= ' checked="checked"';
 7104:                 } elsif ($othervalue eq 'other') {
 7105:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 7106:                         $output .= ' checked="checked"';
 7107:                     }
 7108:                 }
 7109:             } else {
 7110:                 $output .= ' checked="checked"';
 7111:             }
 7112:         } else {
 7113:             $output .= ' checked="checked"';
 7114:         }
 7115:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 7116:     }
 7117:     return $output;
 7118: }
 7119: 
 7120: sub selfenroll_date_forms {
 7121:     my ($startform,$endform) = @_;
 7122:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 7123:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 7124:                                                     'LC_oddrow_value')."\n".
 7125:                   $startform."\n".
 7126:                   &Apache::lonhtmlcommon::row_closure(1).
 7127:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 7128:                                                    'LC_oddrow_value')."\n".
 7129:                   $endform."\n".
 7130:                   &Apache::lonhtmlcommon::row_closure(1).
 7131:                   &Apache::lonhtmlcommon::end_pick_box();
 7132:     return $output;
 7133: }
 7134: 
 7135: sub print_userchangelogs_display {
 7136:     my ($r,$context,$permission,$brcrum) = @_;
 7137:     my $formname = 'rolelog';
 7138:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 7139:     if ($context eq 'domain') {
 7140:         $domain = $env{'request.role.domain'};
 7141:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 7142:     } else {
 7143:         if ($context eq 'course') { 
 7144:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7145:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 7146:             $crstype = &Apache::loncommon::course_type();
 7147:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 7148:             my %saveable_parameters = ('show' => 'scalar',);
 7149:             &Apache::loncommon::store_course_settings('roles_log',
 7150:                                                       \%saveable_parameters);
 7151:             &Apache::loncommon::restore_course_settings('roles_log',
 7152:                                                         \%saveable_parameters);
 7153:         } elsif ($context eq 'author') {
 7154:             $domain = $env{'user.domain'}; 
 7155:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 7156:                 $username = $env{'user.name'};
 7157:             } else {
 7158:                 undef($domain);
 7159:             }
 7160:         }
 7161:         if ($domain ne '' && $username ne '') { 
 7162:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 7163:         }
 7164:     }
 7165:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 7166: 
 7167:     my $helpitem;
 7168:     if ($context eq 'course') {
 7169:         $helpitem = 'Course_User_Logs';
 7170:     } elsif ($context eq 'domain') {
 7171:         $helpitem = 'Domain_Role_Logs';
 7172:     } elsif ($context eq 'author') {
 7173:         $helpitem = 'Author_User_Logs';
 7174:     }
 7175:     push (@{$brcrum},
 7176:              {href => '/adm/createuser?action=changelogs',
 7177:               text => 'User Management Logs',
 7178:               help => $helpitem});
 7179:     my $bread_crumbs_component = 'User Changes';
 7180:     my $args = { bread_crumbs           => $brcrum,
 7181:                  bread_crumbs_component => $bread_crumbs_component};
 7182: 
 7183:     # Create navigation javascript
 7184:     my $jsnav = &userlogdisplay_js($formname);
 7185: 
 7186:     my $jscript = (<<ENDSCRIPT);
 7187: <script type="text/javascript">
 7188: // <![CDATA[
 7189: $jsnav
 7190: // ]]>
 7191: </script>
 7192: ENDSCRIPT
 7193: 
 7194:     # print page header
 7195:     $r->print(&header($jscript,$args));
 7196: 
 7197:     # set defaults
 7198:     my $now = time();
 7199:     my $defstart = $now - (7*24*3600); #7 days ago 
 7200:     my %defaults = (
 7201:                      page               => '1',
 7202:                      show               => '10',
 7203:                      role               => 'any',
 7204:                      chgcontext         => 'any',
 7205:                      rolelog_start_date => $defstart,
 7206:                      rolelog_end_date   => $now,
 7207:                    );
 7208:     my $more_records = 0;
 7209: 
 7210:     # set current
 7211:     my %curr;
 7212:     foreach my $item ('show','page','role','chgcontext') {
 7213:         $curr{$item} = $env{'form.'.$item};
 7214:     }
 7215:     my ($startdate,$enddate) = 
 7216:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 7217:     $curr{'rolelog_start_date'} = $startdate;
 7218:     $curr{'rolelog_end_date'} = $enddate;
 7219:     foreach my $key (keys(%defaults)) {
 7220:         if ($curr{$key} eq '') {
 7221:             $curr{$key} = $defaults{$key};
 7222:         }
 7223:     }
 7224:     my (%whodunit,%changed,$version);
 7225:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 7226:     my ($minshown,$maxshown);
 7227:     $minshown = 1;
 7228:     my $count = 0;
 7229:     if ($curr{'show'} =~ /\D/) {
 7230:         $curr{'page'} = 1;
 7231:     } else {
 7232:         $maxshown = $curr{'page'} * $curr{'show'};
 7233:         if ($curr{'page'} > 1) {
 7234:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7235:         }
 7236:     }
 7237: 
 7238:     # Form Header
 7239:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7240:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 7241:                                    $version,$crstype));
 7242: 
 7243:     my $showntableheader = 0;
 7244: 
 7245:     # Table Header
 7246:     my $tableheader = 
 7247:         &Apache::loncommon::start_data_table_header_row()
 7248:        .'<th>&nbsp;</th>'
 7249:        .'<th>'.&mt('When').'</th>'
 7250:        .'<th>'.&mt('Who made the change').'</th>'
 7251:        .'<th>'.&mt('Changed User').'</th>'
 7252:        .'<th>'.&mt('Role').'</th>';
 7253: 
 7254:     if ($context eq 'course') {
 7255:         $tableheader .= '<th>'.&mt('Section').'</th>';
 7256:     }
 7257:     $tableheader .=
 7258:         '<th>'.&mt('Context').'</th>'
 7259:        .'<th>'.&mt('Start').'</th>'
 7260:        .'<th>'.&mt('End').'</th>'
 7261:        .&Apache::loncommon::end_data_table_header_row();
 7262: 
 7263:     # Display user change log data
 7264:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 7265:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 7266:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 7267:         if ($curr{'show'} !~ /\D/) {
 7268:             if ($count >= $curr{'page'} * $curr{'show'}) {
 7269:                 $more_records = 1;
 7270:                 last;
 7271:             }
 7272:         }
 7273:         if ($curr{'role'} ne 'any') {
 7274:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 7275:         }
 7276:         if ($curr{'chgcontext'} ne 'any') {
 7277:             if ($curr{'chgcontext'} eq 'selfenroll') {
 7278:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 7279:             } else {
 7280:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 7281:             }
 7282:         }
 7283:         if (($context eq 'course') && ($viewablesec ne '')) {
 7284:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 7285:         }
 7286:         $count ++;
 7287:         next if ($count < $minshown);
 7288:         unless ($showntableheader) {
 7289:             $r->print(&Apache::loncommon::start_data_table()
 7290:                      .$tableheader);
 7291:             $r->rflush();
 7292:             $showntableheader = 1;
 7293:         }
 7294:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 7295:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 7296:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 7297:         }
 7298:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 7299:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 7300:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 7301:         }
 7302:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 7303:         if ($sec eq '') {
 7304:             $sec = &mt('None');
 7305:         }
 7306:         my ($rolestart,$roleend);
 7307:         if ($roleslog{$id}{'delflag'}) {
 7308:             $rolestart = &mt('deleted');
 7309:             $roleend = &mt('deleted');
 7310:         } else {
 7311:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 7312:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 7313:             if ($rolestart eq '' || $rolestart == 0) {
 7314:                 $rolestart = &mt('No start date'); 
 7315:             } else {
 7316:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 7317:             }
 7318:             if ($roleend eq '' || $roleend == 0) { 
 7319:                 $roleend = &mt('No end date');
 7320:             } else {
 7321:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 7322:             }
 7323:         }
 7324:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 7325:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 7326:             $chgcontext = 'selfenroll';
 7327:         }
 7328:         my %lt = &rolechg_contexts($context,$crstype);
 7329:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 7330:             $chgcontext = $lt{$chgcontext};
 7331:         }
 7332:         $r->print(
 7333:             &Apache::loncommon::start_data_table_row()
 7334:            .'<td>'.$count.'</td>'
 7335:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 7336:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 7337:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 7338:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 7339:         if ($context eq 'course') { 
 7340:             $r->print('<td>'.$sec.'</td>');
 7341:         }
 7342:         $r->print(
 7343:             '<td>'.$chgcontext.'</td>'
 7344:            .'<td>'.$rolestart.'</td>'
 7345:            .'<td>'.$roleend.'</td>'
 7346:            .&Apache::loncommon::end_data_table_row()."\n");
 7347:     }
 7348: 
 7349:     if ($showntableheader) { # Table footer, if content displayed above
 7350:         $r->print(&Apache::loncommon::end_data_table().
 7351:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7352:     } else { # No content displayed above
 7353:         $r->print('<p class="LC_info">'
 7354:                  .&mt('There are no records to display.')
 7355:                  .'</p>'
 7356:         );
 7357:     }
 7358: 
 7359:     # Form Footer
 7360:     $r->print( 
 7361:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7362:        .'<input type="hidden" name="action" value="changelogs" />'
 7363:        .'</form>');
 7364:     return;
 7365: }
 7366: 
 7367: sub print_useraccesslogs_display {
 7368:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 7369:     my $formname = 'accesslog';
 7370:     my $form = 'document.accesslog';
 7371: 
 7372: # set breadcrumbs
 7373:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 7374:     my $prevphasestr;
 7375:     if ($env{'form.popup'}) {
 7376:         $brcrum = [];
 7377:     } else {
 7378:         push (@{$brcrum},
 7379:             {href => "javascript:backPage($form)",
 7380:              text => $breadcrumb_text{'search'}});
 7381:         my @prevphases;
 7382:         if ($env{'form.prevphases'}) {
 7383:             @prevphases = split(/,/,$env{'form.prevphases'});
 7384:             $prevphasestr = $env{'form.prevphases'};
 7385:         }
 7386:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 7387:             push(@{$brcrum},
 7388:                   {href => "javascript:backPage($form,'get_user_info','select')",
 7389:                    text => $breadcrumb_text{'userpicked'}});
 7390:             if ($env{'form.phase'} eq 'userpicked') {
 7391:                 $prevphasestr = 'userpicked';
 7392:             }
 7393:         }
 7394:     }
 7395:     push(@{$brcrum},
 7396:              {href => '/adm/createuser?action=accesslogs',
 7397:               text => 'User access logs',
 7398:               help => 'Domain_User_Access_Logs'});
 7399:     my $bread_crumbs_component = 'User Access Logs';
 7400:     my $args = { bread_crumbs           => $brcrum,
 7401:                  bread_crumbs_component => 'User Management'};
 7402:     if ($env{'form.popup'}) {
 7403:         $args->{'no_nav_bar'} = 1;
 7404:         $args->{'bread_crumbs_nomenu'} = 1;
 7405:     }
 7406: 
 7407: # set javascript
 7408:     my ($jsback,$elements) = &crumb_utilities();
 7409:     my $jsnav = &userlogdisplay_js($formname);
 7410: 
 7411:     my $jscript = (<<ENDSCRIPT);
 7412: <script type="text/javascript">
 7413: // <![CDATA[
 7414: 
 7415: $jsback
 7416: $jsnav
 7417: 
 7418: // ]]>
 7419: </script>
 7420: 
 7421: ENDSCRIPT
 7422: 
 7423: # print page header
 7424:     $r->print(&header($jscript,$args));
 7425: 
 7426: # early out unless log data can be displayed.
 7427:     unless ($permission->{'activity'}) {
 7428:         $r->print('<p class="LC_warning">'
 7429:                  .&mt('You do not have rights to display user access logs.')
 7430:                  .'</p>');
 7431:         if ($env{'form.popup'}) {
 7432:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7433:         } else {
 7434:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7435:         }
 7436:         return;
 7437:     }
 7438: 
 7439:     unless ($udom eq $env{'request.role.domain'}) {
 7440:         $r->print('<p class="LC_warning">'
 7441:                  .&mt("User's domain must match role's domain")
 7442:                  .'</p>'
 7443:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7444:         return;
 7445:     }
 7446: 
 7447:     if (($uname eq '') || ($udom eq '')) {
 7448:         $r->print('<p class="LC_warning">'
 7449:                  .&mt('Invalid username or domain')
 7450:                  .'</p>'
 7451:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7452:         return;
 7453:     }
 7454: 
 7455:     if (&Apache::lonnet::privileged($uname,$udom,
 7456:                                     [$env{'request.role.domain'}],['dc','su'])) {
 7457:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 7458:                                             [$env{'request.role.domain'}],['dc','su'])) {
 7459:             $r->print('<p class="LC_warning">'
 7460:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 7461:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 7462:                                                          $uname,$udom))
 7463:                  .'</p>');
 7464:             if ($env{'form.popup'}) {
 7465:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7466:             } else {
 7467:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7468:             }
 7469:             return;
 7470:         }
 7471:     }
 7472: 
 7473: # set defaults
 7474:     my $now = time();
 7475:     my $defstart = $now - (7*24*3600);
 7476:     my %defaults = (
 7477:                      page                 => '1',
 7478:                      show                 => '10',
 7479:                      activity             => 'any',
 7480:                      accesslog_start_date => $defstart,
 7481:                      accesslog_end_date   => $now,
 7482:                    );
 7483:     my $more_records = 0;
 7484: 
 7485: # set current
 7486:     my %curr;
 7487:     foreach my $item ('show','page','activity') {
 7488:         $curr{$item} = $env{'form.'.$item};
 7489:     }
 7490:     my ($startdate,$enddate) =
 7491:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 7492:     $curr{'accesslog_start_date'} = $startdate;
 7493:     $curr{'accesslog_end_date'} = $enddate;
 7494:     foreach my $key (keys(%defaults)) {
 7495:         if ($curr{$key} eq '') {
 7496:             $curr{$key} = $defaults{$key};
 7497:         }
 7498:     }
 7499:     my ($minshown,$maxshown);
 7500:     $minshown = 1;
 7501:     my $count = 0;
 7502:     if ($curr{'show'} =~ /\D/) {
 7503:         $curr{'page'} = 1;
 7504:     } else {
 7505:         $maxshown = $curr{'page'} * $curr{'show'};
 7506:         if ($curr{'page'} > 1) {
 7507:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7508:         }
 7509:     }
 7510: 
 7511: # form header
 7512:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7513:               &activity_display_filter($formname,\%curr));
 7514: 
 7515:     my $showntableheader = 0;
 7516:     my ($nav_script,$nav_links);
 7517: 
 7518: # table header
 7519:     my $heading = '<h3>'.
 7520:         &mt('User access logs for: [_1]',
 7521:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 7522:     my $tableheader = $heading
 7523:        .&Apache::loncommon::start_data_table_header_row()
 7524:        .'<th>&nbsp;</th>'
 7525:        .'<th>'.&mt('When').'</th>'
 7526:        .'<th>'.&mt('HostID').'</th>'
 7527:        .'<th>'.&mt('Event').'</th>'
 7528:        .'<th>'.&mt('Other data').'</th>'
 7529:        .&Apache::loncommon::end_data_table_header_row();
 7530: 
 7531:     my %filters=(
 7532:         start  => $curr{'accesslog_start_date'},
 7533:         end    => $curr{'accesslog_end_date'},
 7534:         action => $curr{'activity'},
 7535:     );
 7536: 
 7537:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 7538:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7539:         my (%courses,%missing);
 7540:         my @results = split(/\&/,$reply);
 7541:         foreach my $item (reverse(@results)) {
 7542:             my ($timestamp,$host,$event) = split(/:/,$item);
 7543:             next unless ($event =~ /^(Log|Role)/);
 7544:             if ($curr{'show'} !~ /\D/) {
 7545:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 7546:                     $more_records = 1;
 7547:                     last;
 7548:                 }
 7549:             }
 7550:             $count ++;
 7551:             next if ($count < $minshown);
 7552:             unless ($showntableheader) {
 7553:                 $r->print($nav_script
 7554:                          .&Apache::loncommon::start_data_table()
 7555:                          .$tableheader);
 7556:                 $r->rflush();
 7557:                 $showntableheader = 1;
 7558:             }
 7559:             my ($shown,$extra);
 7560:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 7561:             if ($event eq 'Role') {
 7562:                 my ($rolecode,$extent) = split(/\./,$data,2);
 7563:                 next if ($extent eq '');
 7564:                 my ($crstype,$desc,$info);
 7565:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 7566:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7567:                     my $cid = $cdom.'_'.$cnum;
 7568:                     if (exists($courses{$cid})) {
 7569:                         $crstype = $courses{$cid}{'type'};
 7570:                         $desc = $courses{$cid}{'description'};
 7571:                     } elsif ($missing{$cid}) {
 7572:                         $crstype = 'Course';
 7573:                         $desc = 'Course/Community';
 7574:                     } else {
 7575:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7576:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7577:                             $courses{$cid} = $crsinfo{$cid};
 7578:                             $crstype = $crsinfo{$cid}{'type'};
 7579:                             $desc = $crsinfo{$cid}{'description'};
 7580:                         } else {
 7581:                             $missing{$cid} = 1;
 7582:                         }
 7583:                     }
 7584:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7585:                     if ($sec ne '') {
 7586:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7587:                     }
 7588:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7589:                     my ($dom,$name) = ($1,$2);
 7590:                     if ($rolecode eq 'au') {
 7591:                         $extra = '';
 7592:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7593:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7594:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7595:                         $extra = &mt('Domain: [_1]',$dom);
 7596:                     }
 7597:                 }
 7598:                 my $rolename;
 7599:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7600:                     my $role = $3;
 7601:                     my $owner = "($2:$1)";
 7602:                     if ($2 eq $1.'-domainconfig') {
 7603:                         $owner = '(ad hoc)';
 7604:                     }
 7605:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7606:                 } else {
 7607:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7608:                 }
 7609:                 $shown = &mt('Role selection: [_1]',$rolename);
 7610:             } else {
 7611:                 $shown = &mt($event);
 7612:                 if ($data =~ /^webdav/) {
 7613:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7614:                     $path =~ s/^webdav//;
 7615:                     if ($clientip ne '') {
 7616:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7617:                     }
 7618:                     if ($path ne '') {
 7619:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7620:                     }
 7621:                 } elsif ($data ne '') {
 7622:                     $extra = &mt('Client IP address: [_1]',$data);
 7623:                 }
 7624:             }
 7625:             $r->print(
 7626:             &Apache::loncommon::start_data_table_row()
 7627:            .'<td>'.$count.'</td>'
 7628:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7629:            .'<td>'.$host.'</td>'
 7630:            .'<td>'.$shown.'</td>'
 7631:            .'<td>'.$extra.'</td>'
 7632:            .&Apache::loncommon::end_data_table_row()."\n");
 7633:         }
 7634:     }
 7635: 
 7636:     if ($showntableheader) { # Table footer, if content displayed above
 7637:         $r->print(&Apache::loncommon::end_data_table().
 7638:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7639:     } else { # No content displayed above
 7640:         $r->print($heading.'<p class="LC_info">'
 7641:                  .&mt('There are no records to display.')
 7642:                  .'</p>');
 7643:     }
 7644: 
 7645:     if ($env{'form.popup'} == 1) {
 7646:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7647:     }
 7648: 
 7649:     # Form Footer
 7650:     $r->print(
 7651:         '<input type="hidden" name="currstate" value="" />'
 7652:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7653:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7654:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7655:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7656:        .'<input type="hidden" name="phase" value="activity" />'
 7657:        .'<input type="hidden" name="action" value="accesslogs" />'
 7658:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7659:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7660:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7661:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7662:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7663:        .'</form>');
 7664:     return;
 7665: }
 7666: 
 7667: sub earlyout_accesslog_form {
 7668:     my ($formname,$prevphasestr,$udom) = @_;
 7669:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7670:    return <<"END";
 7671: <form action="/adm/createuser" method="post" name="$formname">
 7672: <input type="hidden" name="currstate" value="" />
 7673: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7674: <input type="hidden" name="phase" value="activity" />
 7675: <input type="hidden" name="action" value="accesslogs" />
 7676: <input type="hidden" name="srchdomain" value="$udom" />
 7677: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7678: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7679: <input type="hidden" name="srchterm" value="$srchterm" />
 7680: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7681: </form>
 7682: END
 7683: }
 7684: 
 7685: sub activity_display_filter {
 7686:     my ($formname,$curr) = @_;
 7687:     my $nolink = 1;
 7688:     my $output = '<table><tr><td valign="top">'.
 7689:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7690:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7691:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7692:                  '</td><td>&nbsp;&nbsp;</td>';
 7693:     my $startform =
 7694:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7695:                                             $curr->{'accesslog_start_date'},undef,
 7696:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7697:     my $endform =
 7698:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7699:                                             $curr->{'accesslog_end_date'},undef,
 7700:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7701:     my %lt = &Apache::lonlocal::texthash (
 7702:                                           activity => 'Activity',
 7703:                                           Role     => 'Role selection',
 7704:                                           log      => 'Log-in or Logout',
 7705:     );
 7706:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7707:                '<table><tr><td>'.&mt('After:').
 7708:                '</td><td>'.$startform.'</td></tr>'.
 7709:                '<tr><td>'.&mt('Before:').'</td>'.
 7710:                '<td>'.$endform.'</td></tr></table>'.
 7711:                '</td>'.
 7712:                '<td>&nbsp;&nbsp;</td>'.
 7713:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7714:                '<select name="activity"><option value="any"';
 7715:     if ($curr->{'activity'} eq 'any') {
 7716:         $output .= ' selected="selected"';
 7717:     }
 7718:     $output .= '>'.&mt('Any').'</option>'."\n";
 7719:     foreach my $activity ('Role','log') {
 7720:         my $selstr = '';
 7721:         if ($activity eq $curr->{'activity'}) {
 7722:             $selstr = ' selected="selected"';
 7723:         }
 7724:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7725:     }
 7726:     $output .= '</select></td>'.
 7727:                '</tr></table>';
 7728:     # Update Display button
 7729:     $output .= '<p>'
 7730:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7731:               .'</p><hr />';
 7732:     return $output;
 7733: }
 7734: 
 7735: sub userlogdisplay_js {
 7736:     my ($formname) = @_;
 7737:     return <<"ENDSCRIPT";
 7738: 
 7739: function chgPage(caller) {
 7740:     if (caller == 'previous') {
 7741:         document.$formname.page.value --;
 7742:     }
 7743:     if (caller == 'next') {
 7744:         document.$formname.page.value ++;
 7745:     }
 7746:     document.$formname.submit();
 7747:     return;
 7748: }
 7749: ENDSCRIPT
 7750: }
 7751: 
 7752: sub userlogdisplay_navlinks {
 7753:     my ($curr,$more_records) = @_;
 7754:     return unless(ref($curr) eq 'HASH');
 7755:     # Navigation Buttons
 7756:     my $nav_links = '<p>';
 7757:     if (($curr->{'page'} > 1) || ($more_records)) {
 7758:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7759:             $nav_links .= '<input type="button"'
 7760:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7761:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7762:                          .'" /> ';
 7763:         }
 7764:         if ($more_records) {
 7765:             $nav_links .= '<input type="button"'
 7766:                          .' onclick="javascript:chgPage('."'next'".');"'
 7767:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7768:                          .'" />';
 7769:         }
 7770:     }
 7771:     $nav_links .= '</p>';
 7772:     return $nav_links;
 7773: }
 7774: 
 7775: sub role_display_filter {
 7776:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7777:     my $lctype;
 7778:     if ($context eq 'course') {
 7779:         $lctype = lc($crstype);
 7780:     }
 7781:     my $nolink = 1;
 7782:     my $output = '<table><tr><td valign="top">'.
 7783:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7784:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7785:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7786:                  '</td><td>&nbsp;&nbsp;</td>';
 7787:     my $startform =
 7788:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7789:                                             $curr->{'rolelog_start_date'},undef,
 7790:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7791:     my $endform =
 7792:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7793:                                             $curr->{'rolelog_end_date'},undef,
 7794:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7795:     my %lt = &rolechg_contexts($context,$crstype);
 7796:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7797:                '<table><tr><td>'.&mt('After:').
 7798:                '</td><td>'.$startform.'</td></tr>'.
 7799:                '<tr><td>'.&mt('Before:').'</td>'.
 7800:                '<td>'.$endform.'</td></tr></table>'.
 7801:                '</td>'.
 7802:                '<td>&nbsp;&nbsp;</td>'.
 7803:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7804:                '<select name="role"><option value="any"';
 7805:     if ($curr->{'role'} eq 'any') {
 7806:         $output .= ' selected="selected"';
 7807:     }
 7808:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7809:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7810:     foreach my $role (@roles) {
 7811:         my $plrole;
 7812:         if ($role eq 'cr') {
 7813:             $plrole = &mt('Custom Role');
 7814:         } else {
 7815:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7816:         }
 7817:         my $selstr = '';
 7818:         if ($role eq $curr->{'role'}) {
 7819:             $selstr = ' selected="selected"';
 7820:         }
 7821:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7822:     }
 7823:     $output .= '</select></td>'.
 7824:                '<td>&nbsp;&nbsp;</td>'.
 7825:                '<td valign="top"><b>'.
 7826:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7827:     my @posscontexts;
 7828:     if ($context eq 'course') {
 7829:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype');
 7830:     } elsif ($context eq 'domain') {
 7831:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7832:     } else {
 7833:         @posscontexts = ('any','author','domain');
 7834:     }
 7835:     foreach my $chgtype (@posscontexts) {
 7836:         my $selstr = '';
 7837:         if ($curr->{'chgcontext'} eq $chgtype) {
 7838:             $selstr = ' selected="selected"';
 7839:         }
 7840:         if ($context eq 'course') {
 7841:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7842:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7843:             }
 7844:         }
 7845:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7846:     }
 7847:     $output .= '</select></td>'
 7848:               .'</tr></table>';
 7849: 
 7850:     # Update Display button
 7851:     $output .= '<p>'
 7852:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7853:               .'</p>';
 7854: 
 7855:     # Server version info
 7856:     my $needsrev = '2.11.0';
 7857:     if ($context eq 'course') {
 7858:         $needsrev = '2.7.0';
 7859:     }
 7860:     
 7861:     $output .= '<p class="LC_info">'
 7862:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7863:                   ,$needsrev);
 7864:     if ($version) {
 7865:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7866:     }
 7867:     $output .= '</p><hr />';
 7868:     return $output;
 7869: }
 7870: 
 7871: sub rolechg_contexts {
 7872:     my ($context,$crstype) = @_;
 7873:     my %lt;
 7874:     if ($context eq 'course') {
 7875:         %lt = &Apache::lonlocal::texthash (
 7876:                                              any          => 'Any',
 7877:                                              automated    => 'Automated Enrollment',
 7878:                                              chgtype      => 'Enrollment Type/Lock Change',
 7879:                                              updatenow    => 'Roster Update',
 7880:                                              createcourse => 'Course Creation',
 7881:                                              course       => 'User Management in course',
 7882:                                              domain       => 'User Management in domain',
 7883:                                              selfenroll   => 'Self-enrolled',
 7884:                                              requestcourses => 'Course Request',
 7885:                                          );
 7886:         if ($crstype eq 'Community') {
 7887:             $lt{'createcourse'} = &mt('Community Creation');
 7888:             $lt{'course'} = &mt('User Management in community');
 7889:             $lt{'requestcourses'} = &mt('Community Request');
 7890:         }
 7891:     } elsif ($context eq 'domain') {
 7892:         %lt = &Apache::lonlocal::texthash (
 7893:                                              any           => 'Any',
 7894:                                              domain        => 'User Management in domain',
 7895:                                              requestauthor => 'Authoring Request',
 7896:                                              server        => 'Command line script (DC role)',
 7897:                                              domconfig     => 'Self-enrolled',
 7898:                                          );
 7899:     } else {
 7900:         %lt = &Apache::lonlocal::texthash (
 7901:                                              any    => 'Any',
 7902:                                              domain => 'User Management in domain',
 7903:                                              author => 'User Management by author',
 7904:                                          );
 7905:     } 
 7906:     return %lt;
 7907: }
 7908: 
 7909: sub print_helpdeskaccess_display {
 7910:     my ($r,$permission,$brcrum) = @_;
 7911:     my $formname = 'helpdeskaccess';
 7912:     my $helpitem = 'Course_Helpdesk_Access';
 7913:     push (@{$brcrum},
 7914:              {href => '/adm/createuser?action=helpdesk',
 7915:               text => 'Helpdesk Access',
 7916:               help => $helpitem});
 7917:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7918:     my $args = { bread_crumbs           => $brcrum,
 7919:                  bread_crumbs_component => $bread_crumbs_component};
 7920: 
 7921:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7922:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7923:     my $confname = $cdom.'-domainconfig';
 7924:     my $crstype = &Apache::loncommon::course_type();
 7925: 
 7926:     my @accesstypes = ('all','dh','da','none');
 7927:     my ($numstatustypes,@jsarray);
 7928:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7929:     if (ref($types) eq 'ARRAY') {
 7930:         if (@{$types} > 0) {
 7931:             $numstatustypes = scalar(@{$types});
 7932:             push(@accesstypes,'status');
 7933:             @jsarray = ('bystatus');
 7934:         }
 7935:     }
 7936:     my %customroles = &get_domain_customroles($cdom,$confname);
 7937:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7938:     if (keys(%domhelpdesk)) {
 7939:        push(@accesstypes,('inc','exc'));
 7940:        push(@jsarray,('notinc','notexc'));
 7941:     }
 7942:     push(@jsarray,'privs');
 7943:     my $hiddenstr = join("','",@jsarray);
 7944:     my $rolestr = join("','",sort(keys(%customroles)));
 7945: 
 7946:     my $jscript;
 7947:     my (%settings,%overridden);
 7948:     if (keys(%customroles)) {
 7949:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7950:                                 $types,\%customroles,\%settings,\%overridden);
 7951:         my %jsfull=();
 7952:         my %jslevels= (
 7953:                      course => {},
 7954:                      domain => {},
 7955:                      system => {},
 7956:                     );
 7957:         my %jslevelscurrent=(
 7958:                            course => {},
 7959:                            domain => {},
 7960:                            system => {},
 7961:                           );
 7962:         my (%privs,%jsprivs);
 7963:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7964:         foreach my $priv (keys(%jsfull)) {
 7965:             if ($jslevels{'course'}{$priv}) {
 7966:                 $jsprivs{$priv} = 1;
 7967:             }
 7968:         }
 7969:         my (%elements,%stored);
 7970:         foreach my $role (keys(%customroles)) {
 7971:             $elements{$role.'_access'} = 'radio';
 7972:             $elements{$role.'_incrs'} = 'radio';
 7973:             if ($numstatustypes) {
 7974:                 $elements{$role.'_status'} = 'checkbox';
 7975:             }
 7976:             if (keys(%domhelpdesk) > 0) {
 7977:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7978:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7979:             }
 7980:             $elements{$role.'_override'} = 'checkbox';
 7981:             if (ref($settings{$role}) eq 'HASH') {
 7982:                 if ($settings{$role}{'access'} ne '') {
 7983:                     my $curraccess = $settings{$role}{'access'};
 7984:                     $stored{$role.'_access'} = $curraccess;
 7985:                     $stored{$role.'_incrs'} = 1;
 7986:                     if ($curraccess eq 'status') {
 7987:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7988:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7989:                         }
 7990:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7991:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7992:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7993:                         }
 7994:                     }
 7995:                 } else {
 7996:                     $stored{$role.'_incrs'} = 0;
 7997:                 }
 7998:                 $stored{$role.'_override'} = [];
 7999:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 8000:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 8001:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 8002:                             push(@{$stored{$role.'_override'}},$priv);
 8003:                         }
 8004:                     }
 8005:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 8006:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 8007:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 8008:                                 push(@{$stored{$role.'_override'}},$priv);
 8009:                             }
 8010:                         }
 8011:                     }
 8012:                 }
 8013:             } else {
 8014:                 $stored{$role.'_incrs'} = 0;
 8015:             }
 8016:         }
 8017:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 8018:     }
 8019: 
 8020:     my $js = <<"ENDJS";
 8021: <script type="text/javascript">
 8022: // <![CDATA[
 8023: $jscript;
 8024: 
 8025: function switchRoleTab(caller,role) {
 8026:     if (document.getElementById(role+'_maindiv')) {
 8027:         if (caller.id != 'LC_current_minitab') {
 8028:             if (document.getElementById('LC_current_minitab')) {
 8029:                 document.getElementById('LC_current_minitab').id=null;
 8030:             }
 8031:             var roledivs = Array('$rolestr');
 8032:             if (roledivs.length > 0) {
 8033:                 for (var i=0; i<roledivs.length; i++) {
 8034:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 8035:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 8036:                     }
 8037:                 }
 8038:             }
 8039:             caller.id = 'LC_current_minitab';
 8040:             document.getElementById(role+'_maindiv').style.display='block';
 8041:         }
 8042:     }
 8043:     return false;
 8044: }
 8045: 
 8046: function helpdeskAccess(role) {
 8047:     var curraccess = null;
 8048:     if (document.$formname.elements[role+'_access'].length) {
 8049:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 8050:             if (document.$formname.elements[role+'_access'][i].checked) {
 8051:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 8052:             }
 8053:         }
 8054:     }
 8055:     var shown = Array();
 8056:     var hidden = Array();
 8057:     if (curraccess == 'none') {
 8058:         hidden = Array ('$hiddenstr');
 8059:     } else {
 8060:         if (curraccess == 'status') {
 8061:             shown = Array ('bystatus','privs');
 8062:             hidden = Array ('notinc','notexc');
 8063:         } else {
 8064:             if (curraccess == 'exc') {
 8065:                 shown = Array ('notexc','privs');
 8066:                 hidden = Array ('notinc','bystatus');
 8067:             }
 8068:             if (curraccess == 'inc') {
 8069:                 shown = Array ('notinc','privs');
 8070:                 hidden = Array ('notexc','bystatus');
 8071:             }
 8072:             if (curraccess == 'all') {
 8073:                 shown = Array ('privs');
 8074:                 hidden = Array ('notinc','notexc','bystatus');
 8075:             }
 8076:         }
 8077:     }
 8078:     if (hidden.length > 0) {
 8079:         for (var i=0; i<hidden.length; i++) {
 8080:             if (document.getElementById(role+'_'+hidden[i])) {
 8081:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 8082:             }
 8083:         }
 8084:     }
 8085:     if (shown.length > 0) {
 8086:         for (var i=0; i<shown.length; i++) {
 8087:             if (document.getElementById(role+'_'+shown[i])) {
 8088:                 if (shown[i] == 'privs') {
 8089:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 8090:                 } else {
 8091:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 8092:                 }
 8093:             }
 8094:         }
 8095:     }
 8096:     return;
 8097: }
 8098: 
 8099: function toggleAccess(role) {
 8100:     if ((document.getElementById(role+'_setincrs')) &&
 8101:         (document.getElementById(role+'_setindom'))) {
 8102:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 8103:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 8104:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 8105:                     document.getElementById(role+'_setindom').style.display = 'none';
 8106:                     document.getElementById(role+'_setincrs').style.display = 'block';
 8107:                 } else {
 8108:                     document.getElementById(role+'_setincrs').style.display = 'none';
 8109:                     document.getElementById(role+'_setindom').style.display = 'block';
 8110:                 }
 8111:                 break;
 8112:             }
 8113:         }
 8114:     }
 8115:     return;
 8116: }
 8117: 
 8118: // ]]>
 8119: </script>
 8120: ENDJS
 8121: 
 8122:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 8123: 
 8124:     # print page header
 8125:     $r->print(&header($js,$args));
 8126:     # print form header
 8127:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 8128: 
 8129:     if (keys(%customroles)) {
 8130:         my %lt = &Apache::lonlocal::texthash(
 8131:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 8132:                     'rou'    => 'Role usage',
 8133:                     'whi'    => 'Which helpdesk personnel may use this role?',
 8134:                     'udd'    => 'Use domain default',
 8135:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 8136:                     'dh'     => 'All with domain helpdesk role',
 8137:                     'da'     => 'All with domain helpdesk assistant role',
 8138:                     'none'   => 'None',
 8139:                     'status' => 'Determined based on institutional status',
 8140:                     'inc'    => 'Include all, but exclude specific personnel',
 8141:                     'exc'    => 'Exclude all, but include specific personnel',
 8142:                     'hel'    => 'Helpdesk',
 8143:                     'rpr'    => 'Role privileges',
 8144:                  );
 8145:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 8146:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8147:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 8148:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8149:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8150:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8151:             }
 8152:         }
 8153:         my $count = 0;
 8154:         foreach my $role (sort(keys(%customroles))) {
 8155:             my ($order,$desc,$access_in_dom);
 8156:             if (ref($domcurrent{$role}) eq 'HASH') {
 8157:                 $order = $domcurrent{$role}{'order'};
 8158:                 $desc = $domcurrent{$role}{'desc'};
 8159:                 $access_in_dom = $domcurrent{$role}{'access'};
 8160:             }
 8161:             if ($order eq '') {
 8162:                 $order = $count;
 8163:             }
 8164:             $ordered{$order} = $role;
 8165:             if ($desc ne '') {
 8166:                 $description{$role} = $desc;
 8167:             } else {
 8168:                 $description{$role}= $role;
 8169:             }
 8170:             $count++;
 8171:         }
 8172:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8173:         my @roles_by_num = ();
 8174:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8175:             push(@roles_by_num,$ordered{$item});
 8176:         }
 8177:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 8178:         if ($permission->{'owner'}) {
 8179:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 8180:             $r->print('<input type="hidden" name="state" value="process" />'.
 8181:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 8182:         } else {
 8183:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 8184:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 8185:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 8186:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 8187:             }
 8188:             $disabled = ' disabled="disabled"';
 8189:         }
 8190:         $r->print('</p>');
 8191: 
 8192:         $r->print('<div id="LC_minitab_header"><ul>');
 8193:         my $count = 0;
 8194:         my %visibility;
 8195:         foreach my $role (@roles_by_num) {
 8196:             my $id;
 8197:             if ($count == 0) {
 8198:                 $id=' id="LC_current_minitab"';
 8199:                 $visibility{$role} = ' style="display:block"';
 8200:             } else {
 8201:                 $visibility{$role} = ' style="display:none"';
 8202:             }
 8203:             $count ++;
 8204:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 8205:         }
 8206:         $r->print('</ul></div>');
 8207: 
 8208:         foreach my $role (@roles_by_num) {
 8209:             my %usecheck = (
 8210:                              all => ' checked="checked"',
 8211:                            );
 8212:             my %displaydiv = (
 8213:                                 status => 'none',
 8214:                                 inc    => 'none',
 8215:                                 exc    => 'none',
 8216:                                 priv   => 'block',
 8217:                              );
 8218:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 8219:             if (ref($settings{$role}) eq 'HASH') {
 8220:                 if ($settings{$role}{'access'} ne '') {
 8221:                     $indomvis = ' style="display:none"';
 8222:                     $incrsvis = ' style="display:block"';
 8223:                     $incrscheck = ' checked="checked"';
 8224:                     if ($settings{$role}{'access'} ne 'all') {
 8225:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 8226:                         delete($usecheck{'all'});
 8227:                         if ($settings{$role}{'access'} eq 'status') {
 8228:                             my $access = 'status';
 8229:                             $displaydiv{$access} = 'inline';
 8230:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 8231:                                 $selected{$access} = $settings{$role}{$access};
 8232:                             }
 8233:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 8234:                             my $access = $1;
 8235:                             $displaydiv{$access} = 'inline';
 8236:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 8237:                                 $selected{$access} = $settings{$role}{$access};
 8238:                             }
 8239:                         } elsif ($settings{$role}{'access'} eq 'none') {
 8240:                             $displaydiv{'priv'} = 'none';
 8241:                         }
 8242:                     }
 8243:                 } else {
 8244:                     $indomcheck = ' checked="checked"';
 8245:                     $indomvis = ' style="display:block"';
 8246:                     $incrsvis = ' style="display:none"';
 8247:                 }
 8248:             } else {
 8249:                 $indomcheck = ' checked="checked"';
 8250:                 $indomvis = ' style="display:block"';
 8251:                 $incrsvis = ' style="display:none"';
 8252:             }
 8253:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 8254:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 8255:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 8256:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 8257:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 8258:                       '<span>'.('&nbsp;'x2).
 8259:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 8260:                       $lt{'udd'}.'</label><span></p>'.
 8261:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 8262:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 8263:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 8264:             foreach my $access (@accesstypes) {
 8265:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 8266:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 8267:                 if ($access eq 'status') {
 8268:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 8269:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 8270:                                                                         $othertitle,$usertypes,$types,$disabled).
 8271:                               '</div>');
 8272:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 8273:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 8274:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 8275:                                                                  \%domhelpdesk,$disabled).
 8276:                               '</div>');
 8277:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 8278:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 8279:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 8280:                                                                  \%domhelpdesk,$disabled).
 8281:                               '</div>');
 8282:                 }
 8283:                 $r->print('</p>');
 8284:             }
 8285:             $r->print('</div></fieldset>');
 8286:             my %full=();
 8287:             my %levels= (
 8288:                          course => {},
 8289:                          domain => {},
 8290:                          system => {},
 8291:                         );
 8292:             my %levelscurrent=(
 8293:                                course => {},
 8294:                                domain => {},
 8295:                                system => {},
 8296:                               );
 8297:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8298:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 8299:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 8300:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 8301:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 8302:         }
 8303:         if ($permission->{'owner'}) {
 8304:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 8305:         }
 8306:     } else {
 8307:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 8308:     }
 8309:     # Form Footer
 8310:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 8311:              .'</form>');
 8312:     return;
 8313: }
 8314: 
 8315: sub domain_adhoc_access {
 8316:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 8317:     my %domusage;
 8318:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 8319:     foreach my $role (keys(%{$roles})) {
 8320:         if (ref($domcurrent->{$role}) eq 'HASH') {
 8321:             my $access = $domcurrent->{$role}{'access'};
 8322:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 8323:                 $access = 'all';
 8324:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 8325:                                                                                           &Apache::lonnet::plaintext('da'));
 8326:             } elsif ($access eq 'status') {
 8327:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 8328:                     my @shown;
 8329:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 8330:                         unless ($type eq 'default') {
 8331:                             if ($usertypes->{$type}) {
 8332:                                 push(@shown,$usertypes->{$type});
 8333:                             }
 8334:                         }
 8335:                     }
 8336:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 8337:                         push(@shown,$othertitle);
 8338:                     }
 8339:                     if (@shown) {
 8340:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 8341:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 8342:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 8343:                     } else {
 8344:                         $domusage{$role} = &mt('No one in the domain');
 8345:                     }
 8346:                 }
 8347:             } elsif ($access eq 'inc') {
 8348:                 my @dominc = ();
 8349:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 8350:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 8351:                         my ($uname,$udom) = split(/:/,$user);
 8352:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 8353:                     }
 8354:                     my $showninc = join(', ',@dominc);
 8355:                     if ($showninc ne '') {
 8356:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 8357:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 8358:                     } else {
 8359:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8360:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8361:                     }
 8362:                 }
 8363:             } elsif ($access eq 'exc') {
 8364:                 my @domexc = ();
 8365:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 8366:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 8367:                         my ($uname,$udom) = split(/:/,$user);
 8368:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 8369:                     }
 8370:                 }
 8371:                 my $shownexc = join(', ',@domexc);
 8372:                 if ($shownexc ne '') {
 8373:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 8374:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 8375:                 } else {
 8376:                     $domusage{$role} = &mt('No one in the domain');
 8377:                 }
 8378:             } elsif ($access eq 'none') {
 8379:                 $domusage{$role} = &mt('No one in the domain');
 8380:             } elsif ($access eq 'dh') {
 8381:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 8382:             } elsif ($access eq 'da') {
 8383:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 8384:             } elsif ($access eq 'all') {
 8385:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8386:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8387:             }
 8388:         } else {
 8389:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8390:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8391:         }
 8392:     }
 8393:     return %domusage;
 8394: }
 8395: 
 8396: sub get_domain_customroles {
 8397:     my ($cdom,$confname) = @_;
 8398:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 8399:     my %customroles;
 8400:     foreach my $key (keys(%existing)) {
 8401:         if ($key=~/^rolesdef\_(\w+)$/) {
 8402:             my $rolename = $1;
 8403:             my %privs;
 8404:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 8405:             $customroles{$rolename} = \%privs;
 8406:         }
 8407:     }
 8408:     return %customroles;
 8409: }
 8410: 
 8411: sub role_priv_table {
 8412:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 8413:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 8414:                    (ref($levelscurrent) eq 'HASH'));
 8415:     my %lt=&Apache::lonlocal::texthash (
 8416:                     'crl'  => 'Course Level Privilege',
 8417:                     'def'  => 'Domain Defaults',
 8418:                     'ove'  => 'Override in Course',
 8419:                     'ine'  => 'In effect',
 8420:                     'dis'  => 'Disabled',
 8421:                     'ena'  => 'Enabled',
 8422:                    );
 8423:     if ($crstype eq 'Community') {
 8424:         $lt{'ove'} = 'Override in Community',
 8425:     }
 8426:     my @status = ('Disabled','Enabled');
 8427:     my (%on,%off);
 8428:     if (ref($overridden) eq 'HASH') {
 8429:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 8430:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 8431:         }
 8432:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 8433:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 8434:         }
 8435:     }
 8436:     my $output=&Apache::loncommon::start_data_table().
 8437:                &Apache::loncommon::start_data_table_header_row().
 8438:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 8439:                '</th><th>'.$lt{'ine'}.'</th>'.
 8440:                &Apache::loncommon::end_data_table_header_row();
 8441:     foreach my $priv (sort(keys(%{$full}))) {
 8442:         next unless ($levels->{'course'}{$priv});
 8443:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 8444:         my ($default,$ineffect);
 8445:         if ($levelscurrent->{'course'}{$priv}) {
 8446:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8447:             $ineffect = $default;
 8448:         }
 8449:         my ($customstatus,$checked);
 8450:         $output .= &Apache::loncommon::start_data_table_row().
 8451:                    '<td>'.$privtext.'</td>'.
 8452:                    '<td>'.$default.'</td><td>';
 8453:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 8454:             if ($permission->{'owner'}) {
 8455:                 $checked = ' checked="checked"';
 8456:             }
 8457:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 8458:             $ineffect = $customstatus;
 8459:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 8460:             if ($permission->{'owner'}) {
 8461:                 $checked = ' checked="checked"';
 8462:             }
 8463:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8464:             $ineffect = $customstatus;
 8465:         }
 8466:         if ($permission->{'owner'}) {
 8467:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 8468:         } else {
 8469:             $output .= $customstatus;
 8470:         }
 8471:         $output .= '</td><td>'.$ineffect.'</td>'.
 8472:                    &Apache::loncommon::end_data_table_row();
 8473:     }
 8474:     $output .= &Apache::loncommon::end_data_table();
 8475:     return $output;
 8476: }
 8477: 
 8478: sub get_adhocrole_settings {
 8479:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 8480:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 8481:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 8482:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 8483:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 8484:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 8485:             $settings->{$role}{'access'} = $curraccess;
 8486:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 8487:                 my @status = split(/,/,$rest);
 8488:                 my @currstatus;
 8489:                 foreach my $type (@status) {
 8490:                     if ($type eq 'default') {
 8491:                         push(@currstatus,$type);
 8492:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8493:                         push(@currstatus,$type);
 8494:                     }
 8495:                 }
 8496:                 if (@currstatus) {
 8497:                     $settings->{$role}{$curraccess} = \@currstatus;
 8498:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8499:                     my @personnel = split(/,/,$rest);
 8500:                     $settings->{$role}{$curraccess} = \@personnel;
 8501:                 }
 8502:             }
 8503:         }
 8504:     }
 8505:     foreach my $role (keys(%{$customroles})) {
 8506:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 8507:             my %currentprivs;
 8508:             if (ref($customroles->{$role}) eq 'HASH') {
 8509:                 if (exists($customroles->{$role}{'course'})) {
 8510:                     my %full=();
 8511:                     my %levels= (
 8512:                                   course => {},
 8513:                                   domain => {},
 8514:                                   system => {},
 8515:                                 );
 8516:                     my %levelscurrent=(
 8517:                                         course => {},
 8518:                                         domain => {},
 8519:                                         system => {},
 8520:                                       );
 8521:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 8522:                     %currentprivs = %{$levelscurrent{'course'}};
 8523:                 }
 8524:             }
 8525:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 8526:                 next if ($item eq '');
 8527:                 my ($rule,$rest) = split(/=/,$item);
 8528:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 8529:                 foreach my $priv (split(/:/,$rest)) {
 8530:                     if ($priv ne '') {
 8531:                         if ($rule eq 'off') {
 8532:                             push(@{$overridden->{$role}{'off'}},$priv);
 8533:                             if ($currentprivs{$priv}) {
 8534:                                 push(@{$settings->{$role}{'off'}},$priv);
 8535:                             }
 8536:                         } else {
 8537:                             push(@{$overridden->{$role}{'on'}},$priv);
 8538:                             unless ($currentprivs{$priv}) {
 8539:                                 push(@{$settings->{$role}{'on'}},$priv);
 8540:                             }
 8541:                         }
 8542:                     }
 8543:                 }
 8544:             }
 8545:         }
 8546:     }
 8547:     return;
 8548: }
 8549: 
 8550: sub update_helpdeskaccess {
 8551:     my ($r,$permission,$brcrum) = @_;
 8552:     my $helpitem = 'Course_Helpdesk_Access';
 8553:     push (@{$brcrum},
 8554:              {href => '/adm/createuser?action=helpdesk',
 8555:               text => 'Helpdesk Access',
 8556:               help => $helpitem},
 8557:              {href => '/adm/createuser?action=helpdesk',
 8558:               text => 'Result',
 8559:               help => $helpitem}
 8560:          );
 8561:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8562:     my $args = { bread_crumbs           => $brcrum,
 8563:                  bread_crumbs_component => $bread_crumbs_component};
 8564: 
 8565:     # print page header
 8566:     $r->print(&header('',$args));
 8567:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8568:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8569:         return;
 8570:     }
 8571:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8572:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8573:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8574:     my $confname = $cdom.'-domainconfig';
 8575:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8576:     my $crstype = &Apache::loncommon::course_type();
 8577:     my %customroles = &get_domain_customroles($cdom,$confname);
 8578:     my (%settings,%overridden);
 8579:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8580:                             $types,\%customroles,\%settings,\%overridden);
 8581:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8582:     my (%changed,%storehash,@todelete);
 8583: 
 8584:     if (keys(%customroles)) {
 8585:         my (%newsettings,@incrs);
 8586:         foreach my $role (keys(%customroles)) {
 8587:             $newsettings{$role} = {
 8588:                                     access => '',
 8589:                                     status => '',
 8590:                                     exc    => '',
 8591:                                     inc    => '',
 8592:                                     on     => '',
 8593:                                     off    => '',
 8594:                                   };
 8595:             my %current;
 8596:             if (ref($settings{$role}) eq 'HASH') {
 8597:                 %current = %{$settings{$role}};
 8598:             }
 8599:             if (ref($overridden{$role}) eq 'HASH') {
 8600:                 $current{'overridden'} = $overridden{$role};
 8601:             }
 8602:             if ($env{'form.'.$role.'_incrs'}) {
 8603:                 my $access = $env{'form.'.$role.'_access'};
 8604:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8605:                     push(@incrs,$role);
 8606:                     unless ($current{'access'} eq $access) {
 8607:                         $changed{$role}{'access'} = 1;
 8608:                         $storehash{'internal.adhoc.'.$role} = $access;
 8609:                     }
 8610:                     if ($access eq 'status') {
 8611:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8612:                         my @stored;
 8613:                         my @shownstatus;
 8614:                         if (ref($types) eq 'ARRAY') {
 8615:                             foreach my $type (sort(@statuses)) {
 8616:                                 if ($type eq 'default') {
 8617:                                     push(@stored,$type);
 8618:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8619:                                     push(@stored,$type);
 8620:                                     push(@shownstatus,$usertypes->{$type});
 8621:                                 }
 8622:                             }
 8623:                             if (grep(/^default$/,@statuses)) {
 8624:                                 push(@shownstatus,$othertitle);
 8625:                             }
 8626:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8627:                         }
 8628:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8629:                         if (ref($current{'status'}) eq 'ARRAY') {
 8630:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8631:                             if (@diffs) {
 8632:                                 $changed{$role}{'status'} = 1;
 8633:                             }
 8634:                         } elsif (@stored) {
 8635:                             $changed{$role}{'status'} = 1;
 8636:                         }
 8637:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8638:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8639:                         my @newspecstaff;
 8640:                         my @stored;
 8641:                         my @currstaff;
 8642:                         foreach my $person (sort(@personnel)) {
 8643:                             if ($domhelpdesk{$person}) {
 8644:                                 push(@stored,$person);
 8645:                             }
 8646:                         }
 8647:                         if (ref($current{$access}) eq 'ARRAY') {
 8648:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8649:                             if (@diffs) {
 8650:                                 $changed{$role}{$access} = 1;
 8651:                             }
 8652:                         } elsif (@stored) {
 8653:                             $changed{$role}{$access} = 1;
 8654:                         }
 8655:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8656:                         foreach my $person (@stored) {
 8657:                             my ($uname,$udom) = split(/:/,$person);
 8658:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8659:                         }
 8660:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8661:                     }
 8662:                     $newsettings{$role}{'access'} = $access;
 8663:                 }
 8664:             } else {
 8665:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8666:                     $changed{$role}{'access'} = 1;
 8667:                     $newsettings{$role} = {};
 8668:                     push(@todelete,'internal.adhoc.'.$role);
 8669:                 }
 8670:             }
 8671:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8672:                 if (ref($current{'overridden'}) eq 'HASH') {
 8673:                     push(@todelete,'internal.adhocpriv.'.$role);
 8674:                 }
 8675:             } else {
 8676:                 my %full=();
 8677:                 my %levels= (
 8678:                              course => {},
 8679:                              domain => {},
 8680:                              system => {},
 8681:                             );
 8682:                 my %levelscurrent=(
 8683:                                    course => {},
 8684:                                    domain => {},
 8685:                                    system => {},
 8686:                                   );
 8687:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8688:                 my (@updatedon,@updatedoff,@override);
 8689:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8690:                 if (@override) {
 8691:                     foreach my $priv (sort(keys(%full))) {
 8692:                         next unless ($levels{'course'}{$priv});
 8693:                         if (grep(/^\Q$priv\E$/,@override)) {
 8694:                             if ($levelscurrent{'course'}{$priv}) {
 8695:                                 push(@updatedoff,$priv);
 8696:                             } else {
 8697:                                 push(@updatedon,$priv);
 8698:                             }
 8699:                         }
 8700:                     }
 8701:                 }
 8702:                 if (@updatedon) {
 8703:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8704:                 }
 8705:                 if (@updatedoff) {
 8706:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8707:                 }
 8708:                 if (ref($current{'overridden'}) eq 'HASH') {
 8709:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8710:                         if (@updatedon) {
 8711:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8712:                             if (@diffs) {
 8713:                                 $changed{$role}{'on'} = 1;
 8714:                             }
 8715:                         } else {
 8716:                             $changed{$role}{'on'} = 1;
 8717:                         }
 8718:                     } elsif (@updatedon) {
 8719:                         $changed{$role}{'on'} = 1;
 8720:                     }
 8721:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8722:                         if (@updatedoff) {
 8723:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8724:                             if (@diffs) {
 8725:                                 $changed{$role}{'off'} = 1;
 8726:                             }
 8727:                         } else {
 8728:                             $changed{$role}{'off'} = 1;
 8729:                         }
 8730:                     } elsif (@updatedoff) {
 8731:                         $changed{$role}{'off'} = 1;
 8732:                     }
 8733:                 } else {
 8734:                     if (@updatedon) {
 8735:                         $changed{$role}{'on'} = 1;
 8736:                     }
 8737:                     if (@updatedoff) {
 8738:                         $changed{$role}{'off'} = 1;
 8739:                     }
 8740:                 }
 8741:                 if (ref($changed{$role}) eq 'HASH') {
 8742:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8743:                         my $newpriv;
 8744:                         if (@updatedon) {
 8745:                             $newpriv = 'on='.join(':',@updatedon);
 8746:                         }
 8747:                         if (@updatedoff) {
 8748:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8749:                         }
 8750:                         if ($newpriv eq '') {
 8751:                             push(@todelete,'internal.adhocpriv.'.$role);
 8752:                         } else {
 8753:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8754:                         }
 8755:                     }
 8756:                 }
 8757:             }
 8758:         }
 8759:         if (@incrs) {
 8760:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8761:         } elsif (@todelete) {
 8762:             push(@todelete,'internal.adhocaccess');
 8763:         }
 8764:         if (keys(%changed)) {
 8765:             my ($putres,$delres);
 8766:             if (keys(%storehash)) {
 8767:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8768:                 my %newenvhash;
 8769:                 foreach my $key (keys(%storehash)) {
 8770:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8771:                 }
 8772:                 &Apache::lonnet::appenv(\%newenvhash);
 8773:             }
 8774:             if (@todelete) {
 8775:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8776:                 foreach my $key (@todelete) {
 8777:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8778:                 }
 8779:             }
 8780:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8781:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8782:                 my (%domcurrent,%ordered,%description,%domusage);
 8783:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8784:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8785:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8786:                     }
 8787:                 }
 8788:                 my $count = 0;
 8789:                 foreach my $role (sort(keys(%customroles))) {
 8790:                     my ($order,$desc);
 8791:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8792:                         $order = $domcurrent{$role}{'order'};
 8793:                         $desc = $domcurrent{$role}{'desc'};
 8794:                     }
 8795:                     if ($order eq '') {
 8796:                         $order = $count;
 8797:                     }
 8798:                     $ordered{$order} = $role;
 8799:                     if ($desc ne '') {
 8800:                         $description{$role} = $desc;
 8801:                     } else {
 8802:                         $description{$role}= $role;
 8803:                     }
 8804:                     $count++;
 8805:                 }
 8806:                 my @roles_by_num = ();
 8807:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8808:                     push(@roles_by_num,$ordered{$item});
 8809:                 }
 8810:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8811:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8812:                 $r->print('<ul>');
 8813:                 foreach my $role (@roles_by_num) {
 8814:                     next unless (ref($changed{$role}) eq 'HASH');
 8815:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8816:                               '<ul>');
 8817:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8818:                         $r->print('<li>');
 8819:                         if ($env{'form.'.$role.'_incrs'}) {
 8820:                             if ($newsettings{$role}{'access'} eq 'all') {
 8821:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8822:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8823:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8824:                                               &Apache::lonnet::plaintext('dh')));
 8825:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8826:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8827:                                               &Apache::lonnet::plaintext('da')));
 8828:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8829:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8830:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8831:                                 if ($newsettings{$role}{'status'}) {
 8832:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8833:                                     if (split(/,/,$rest) > 1) {
 8834:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8835:                                                       $newsettings{$role}{'status'}));
 8836:                                     } else {
 8837:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8838:                                                       $newsettings{$role}{'status'}));
 8839:                                     }
 8840:                                 } else {
 8841:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8842:                                 }
 8843:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8844:                                 if ($newsettings{$role}{'exc'}) {
 8845:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8846:                                 } else {
 8847:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8848:                                 }
 8849:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8850:                                 if ($newsettings{$role}{'inc'}) {
 8851:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8852:                                 } else {
 8853:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8854:                                 }
 8855:                             }
 8856:                         } else {
 8857:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8858:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8859:                         }
 8860:                         $r->print('</li>');
 8861:                     }
 8862:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8863:                         if ($changed{$role}{'off'}) {
 8864:                             if ($newsettings{$role}{'off'}) {
 8865:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8866:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8867:                             } else {
 8868:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8869:                             }
 8870:                         }
 8871:                         if ($changed{$role}{'on'}) {
 8872:                             if ($newsettings{$role}{'on'}) {
 8873:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8874:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8875:                             } else {
 8876:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8877:                             }
 8878:                         }
 8879:                     }
 8880:                     $r->print('</ul></li>');
 8881:                 }
 8882:                 $r->print('</ul>');
 8883:             }
 8884:         } else {
 8885:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8886:         }
 8887:     }
 8888:     return;
 8889: }
 8890: 
 8891: #-------------------------------------------------- functions for &phase_two
 8892: sub user_search_result {
 8893:     my ($context,$srch) = @_;
 8894:     my %allhomes;
 8895:     my %inst_matches;
 8896:     my %srch_results;
 8897:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8898:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8899:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8900:         $response = &mt('Invalid search.');
 8901:     }
 8902:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8903:         $response = &mt('Invalid search.');
 8904:     }
 8905:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8906:         $response = &mt('Invalid search.');
 8907:     }
 8908:     if ($srch->{'srchterm'} eq '') {
 8909:         $response = &mt('You must enter a search term.');
 8910:     }
 8911:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8912:         $response = &mt('Your search term must contain more than just spaces.');
 8913:     }
 8914:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8915:         if (($srch->{'srchdomain'} eq '') || 
 8916: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8917:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8918:         }
 8919:     }
 8920:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8921:         ($srch->{'srchin'} eq 'alc')) {
 8922:         if ($srch->{'srchby'} eq 'uname') {
 8923:             my $unamecheck = $srch->{'srchterm'};
 8924:             if ($srch->{'srchtype'} eq 'contains') {
 8925:                 if ($unamecheck !~ /^\w/) {
 8926:                     $unamecheck = 'a'.$unamecheck; 
 8927:                 }
 8928:             }
 8929:             if ($unamecheck !~ /^$match_username$/) {
 8930:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8931:             }
 8932:         }
 8933:     }
 8934:     if ($response ne '') {
 8935:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8936:     }
 8937:     if ($srch->{'srchin'} eq 'instd') {
 8938:         my $instd_chk = &instdirectorysrch_check($srch);
 8939:         if ($instd_chk ne 'ok') {
 8940:             my $domd_chk = &domdirectorysrch_check($srch);
 8941:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8942:             if ($domd_chk eq 'ok') {
 8943:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
 8944:             }
 8945:             $response .= '<br />';
 8946:         }
 8947:     } else {
 8948:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8949:             my $domd_chk = &domdirectorysrch_check($srch);
 8950:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8951:                 my $instd_chk = &instdirectorysrch_check($srch);
 8952:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8953:                 if ($instd_chk eq 'ok') {
 8954:                     $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
 8955:                 }
 8956:                 $response .= '<br />';
 8957:             }
 8958:         }
 8959:     }
 8960:     if ($response ne '') {
 8961:         return ($currstate,$response);
 8962:     }
 8963:     if ($srch->{'srchby'} eq 'uname') {
 8964:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8965:             if ($env{'form.forcenew'}) {
 8966:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8967:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8968:                     if ($uhome eq 'no_host') {
 8969:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8970:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8971:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8972:                     } else {
 8973:                         $currstate = 'modify';
 8974:                     }
 8975:                 } else {
 8976:                     $currstate = 'modify';
 8977:                 }
 8978:             } else {
 8979:                 if ($srch->{'srchin'} eq 'dom') {
 8980:                     if ($srch->{'srchtype'} eq 'exact') {
 8981:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8982:                         if ($uhome eq 'no_host') {
 8983:                             ($currstate,$response,$forcenewuser) =
 8984:                                 &build_search_response($context,$srch,%srch_results);
 8985:                         } else {
 8986:                             $currstate = 'modify';
 8987:                             if ($env{'form.action'} eq 'accesslogs') {
 8988:                                 $currstate = 'activity';
 8989:                             }
 8990:                             my $uname = $srch->{'srchterm'};
 8991:                             my $udom = $srch->{'srchdomain'};
 8992:                             $srch_results{$uname.':'.$udom} =
 8993:                                 { &Apache::lonnet::get('environment',
 8994:                                                        ['firstname',
 8995:                                                         'lastname',
 8996:                                                         'permanentemail'],
 8997:                                                          $udom,$uname)
 8998:                                 };
 8999:                         }
 9000:                     } else {
 9001:                         %srch_results = &Apache::lonnet::usersearch($srch);
 9002:                         ($currstate,$response,$forcenewuser) =
 9003:                             &build_search_response($context,$srch,%srch_results);
 9004:                     }
 9005:                 } else {
 9006:                     my $courseusers = &get_courseusers();
 9007:                     if ($srch->{'srchtype'} eq 'exact') {
 9008:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 9009:                             $currstate = 'modify';
 9010:                         } else {
 9011:                             ($currstate,$response,$forcenewuser) =
 9012:                                 &build_search_response($context,$srch,%srch_results);
 9013:                         }
 9014:                     } else {
 9015:                         foreach my $user (keys(%$courseusers)) {
 9016:                             my ($cuname,$cudomain) = split(/:/,$user);
 9017:                             if ($cudomain eq $srch->{'srchdomain'}) {
 9018:                                 my $matched = 0;
 9019:                                 if ($srch->{'srchtype'} eq 'begins') {
 9020:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 9021:                                         $matched = 1;
 9022:                                     }
 9023:                                 } else {
 9024:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 9025:                                         $matched = 1;
 9026:                                     }
 9027:                                 }
 9028:                                 if ($matched) {
 9029:                                     $srch_results{$user} = 
 9030: 					{&Apache::lonnet::get('environment',
 9031: 							     ['firstname',
 9032: 							      'lastname',
 9033: 							      'permanentemail'],
 9034: 							      $cudomain,$cuname)};
 9035:                                 }
 9036:                             }
 9037:                         }
 9038:                         ($currstate,$response,$forcenewuser) =
 9039:                             &build_search_response($context,$srch,%srch_results);
 9040:                     }
 9041:                 }
 9042:             }
 9043:         } elsif ($srch->{'srchin'} eq 'alc') {
 9044:             $currstate = 'query';
 9045:         } elsif ($srch->{'srchin'} eq 'instd') {
 9046:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 9047:             if ($dirsrchres eq 'ok') {
 9048:                 ($currstate,$response,$forcenewuser) = 
 9049:                     &build_search_response($context,$srch,%srch_results);
 9050:             } else {
 9051:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9052:                 $response = '<span class="LC_warning">'.
 9053:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9054:                     '</span><br />'.
 9055:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 9056:                     '<br />'; 
 9057:             }
 9058:         }
 9059:     } else {
 9060:         if ($srch->{'srchin'} eq 'dom') {
 9061:             %srch_results = &Apache::lonnet::usersearch($srch);
 9062:             ($currstate,$response,$forcenewuser) = 
 9063:                 &build_search_response($context,$srch,%srch_results); 
 9064:         } elsif ($srch->{'srchin'} eq 'crs') {
 9065:             my $courseusers = &get_courseusers(); 
 9066:             foreach my $user (keys(%$courseusers)) {
 9067:                 my ($uname,$udom) = split(/:/,$user);
 9068:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 9069:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 9070:                 if ($srch->{'srchby'} eq 'lastname') {
 9071:                     if ((($srch->{'srchtype'} eq 'exact') && 
 9072:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 9073:                         (($srch->{'srchtype'} eq 'begins') &&
 9074:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 9075:                         (($srch->{'srchtype'} eq 'contains') &&
 9076:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 9077:                         $srch_results{$user} = {firstname => $names{'firstname'},
 9078:                                             lastname => $names{'lastname'},
 9079:                                             permanentemail => $emails{'permanentemail'},
 9080:                                            };
 9081:                     }
 9082:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 9083:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 9084:                     $srchlast =~ s/\s+$//;
 9085:                     $srchfirst =~ s/^\s+//;
 9086:                     if ($srch->{'srchtype'} eq 'exact') {
 9087:                         if (($names{'lastname'} eq $srchlast) &&
 9088:                             ($names{'firstname'} eq $srchfirst)) {
 9089:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9090:                                                 lastname => $names{'lastname'},
 9091:                                                 permanentemail => $emails{'permanentemail'},
 9092: 
 9093:                                            };
 9094:                         }
 9095:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 9096:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 9097:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 9098:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9099:                                                 lastname => $names{'lastname'},
 9100:                                                 permanentemail => $emails{'permanentemail'},
 9101:                                                };
 9102:                         }
 9103:                     } else {
 9104:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 9105:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 9106:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9107:                                                 lastname => $names{'lastname'},
 9108:                                                 permanentemail => $emails{'permanentemail'},
 9109:                                                };
 9110:                         }
 9111:                     }
 9112:                 }
 9113:             }
 9114:             ($currstate,$response,$forcenewuser) = 
 9115:                 &build_search_response($context,$srch,%srch_results); 
 9116:         } elsif ($srch->{'srchin'} eq 'alc') {
 9117:             $currstate = 'query';
 9118:         } elsif ($srch->{'srchin'} eq 'instd') {
 9119:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 9120:             if ($dirsrchres eq 'ok') {
 9121:                 ($currstate,$response,$forcenewuser) = 
 9122:                     &build_search_response($context,$srch,%srch_results);
 9123:             } else {
 9124:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9125:                 $response = '<span class="LC_warning">'.
 9126:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9127:                     '</span><br />'.
 9128:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
 9129:                     '<br />';
 9130:             }
 9131:         }
 9132:     }
 9133:     return ($currstate,$response,$forcenewuser,\%srch_results);
 9134: }
 9135: 
 9136: sub domdirectorysrch_check {
 9137:     my ($srch) = @_;
 9138:     my $response;
 9139:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 9140:                                              ['directorysrch'],$srch->{'srchdomain'});
 9141:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 9142:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 9143:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 9144:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 9145:         }
 9146:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 9147:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 9148:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 9149:             }
 9150:         }
 9151:     }
 9152:     return 'ok';
 9153: }
 9154: 
 9155: sub instdirectorysrch_check {
 9156:     my ($srch) = @_;
 9157:     my $can_search = 0;
 9158:     my $response;
 9159:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 9160:                                              ['directorysrch'],$srch->{'srchdomain'});
 9161:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 9162:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 9163:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 9164:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 9165:         }
 9166:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 9167:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 9168:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 9169:             }
 9170:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 9171:             if (!@usertypes) {
 9172:                 push(@usertypes,'default');
 9173:             }
 9174:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 9175:                 foreach my $type (@usertypes) {
 9176:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 9177:                         $can_search = 1;
 9178:                         last;
 9179:                     }
 9180:                 }
 9181:             }
 9182:             if (!$can_search) {
 9183:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 9184:                 my @longtypes; 
 9185:                 foreach my $item (@usertypes) {
 9186:                     if (defined($insttypes->{$item})) { 
 9187:                         push (@longtypes,$insttypes->{$item});
 9188:                     } elsif ($item eq 'default') {
 9189:                         push (@longtypes,&mt('other')); 
 9190:                     }
 9191:                 }
 9192:                 my $insttype_str = join(', ',@longtypes); 
 9193:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 9194:             }
 9195:         } else {
 9196:             $can_search = 1;
 9197:         }
 9198:     } else {
 9199:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 9200:     }
 9201:     my %longtext = &Apache::lonlocal::texthash (
 9202:                        uname     => 'username',
 9203:                        lastfirst => 'last name, first name',
 9204:                        lastname  => 'last name',
 9205:                        contains  => 'contains',
 9206:                        exact     => 'as exact match to',
 9207:                        begins    => 'begins with',
 9208:                    );
 9209:     if ($can_search) {
 9210:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 9211:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 9212:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 9213:             }
 9214:         } else {
 9215:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 9216:         }
 9217:     }
 9218:     if ($can_search) {
 9219:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 9220:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 9221:                 return 'ok';
 9222:             } else {
 9223:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 9224:             }
 9225:         } else {
 9226:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 9227:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 9228:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 9229:                 return 'ok';
 9230:             } else {
 9231:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 9232:             }
 9233:         }
 9234:     }
 9235: }
 9236: 
 9237: sub get_courseusers {
 9238:     my %advhash;
 9239:     my $classlist = &Apache::loncoursedata::get_classlist();
 9240:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 9241:     foreach my $role (sort(keys(%coursepersonnel))) {
 9242:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 9243: 	    if (!exists($classlist->{$user})) {
 9244: 		$classlist->{$user} = [];
 9245: 	    }
 9246:         }
 9247:     }
 9248:     return $classlist;
 9249: }
 9250: 
 9251: sub build_search_response {
 9252:     my ($context,$srch,%srch_results) = @_;
 9253:     my ($currstate,$response,$forcenewuser);
 9254:     my %names = (
 9255:           'uname'     => 'username',
 9256:           'lastname'  => 'last name',
 9257:           'lastfirst' => 'last name, first name',
 9258:           'crs'       => 'this course',
 9259:           'dom'       => 'LON-CAPA domain',
 9260:           'instd'     => 'the institutional directory for domain',
 9261:     );
 9262: 
 9263:     my %single = (
 9264:                    begins   => 'A match',
 9265:                    contains => 'A match',
 9266:                    exact    => 'An exact match',
 9267:                  );
 9268:     my %nomatch = (
 9269:                    begins   => 'No match',
 9270:                    contains => 'No match',
 9271:                    exact    => 'No exact match',
 9272:                   );
 9273:     if (keys(%srch_results) > 1) {
 9274:         $currstate = 'select';
 9275:     } else {
 9276:         if (keys(%srch_results) == 1) {
 9277:             if ($env{'form.action'} eq 'accesslogs') {
 9278:                 $currstate = 'activity';
 9279:             } else {
 9280:                 $currstate = 'modify';
 9281:             }
 9282:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 9283:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 9284:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 9285:             }
 9286:         } else { # Search has nothing found. Prepare message to user.
 9287:             $response = '<span class="LC_warning">';
 9288:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 9289:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 9290:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 9291:                                  &display_domain_info($srch->{'srchdomain'}));
 9292:             } else {
 9293:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 9294:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 9295:             }
 9296:             $response .= '</span>';
 9297: 
 9298:             if ($srch->{'srchin'} ne 'alc') {
 9299:                 $forcenewuser = 1;
 9300:                 my $cansrchinst = 0; 
 9301:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 9302:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 9303:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 9304:                         if ($domconfig{'directorysrch'}{'available'}) {
 9305:                             $cansrchinst = 1;
 9306:                         } 
 9307:                     }
 9308:                 }
 9309:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 9310:                      ($srch->{'srchby'} eq 'lastname')) &&
 9311:                     ($srch->{'srchin'} eq 'dom')) {
 9312:                     if ($cansrchinst) {
 9313:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 9314:                     }
 9315:                 }
 9316:                 if ($srch->{'srchin'} eq 'crs') {
 9317:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 9318:                 }
 9319:             }
 9320:             my $createdom = $env{'request.role.domain'};
 9321:             if ($context eq 'requestcrs') {
 9322:                 if ($env{'form.coursedom'} ne '') {
 9323:                     $createdom = $env{'form.coursedom'};
 9324:                 }
 9325:             }
 9326:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 9327:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 9328:                 my $cancreate =
 9329:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 9330:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 9331:                 if ($cancreate) {
 9332:                     my $showdom = &display_domain_info($createdom); 
 9333:                     $response .= '<br /><br />'
 9334:                                 .'<b>'.&mt('To add a new user:').'</b>'
 9335:                                 .'<br />';
 9336:                     if ($context eq 'requestcrs') {
 9337:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 9338:                     } else {
 9339:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 9340:                     }
 9341:                     $response .='<ul><li>'
 9342:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 9343:                                 .'</li><li>'
 9344:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 9345:                                 .'</li><li>'
 9346:                                 .&mt('Provide the proposed username')
 9347:                                 .'</li><li>'
 9348:                                 .&mt("Click 'Search'")
 9349:                                 .'</li></ul><br />';
 9350:                 } else {
 9351:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 9352:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 9353:                         $response .= '<br /><br />';
 9354:                         if ($context eq 'requestcrs') {
 9355:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 9356:                         } else {
 9357:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 9358:                         }
 9359:                         $response .= '<br />'
 9360:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 9361:                                         ,' <a'.$helplink.'>'
 9362:                                         ,'</a>')
 9363:                                      .'<br />';
 9364:                     }
 9365:                 }
 9366:             }
 9367:         }
 9368:     }
 9369:     return ($currstate,$response,$forcenewuser);
 9370: }
 9371: 
 9372: sub display_domain_info {
 9373:     my ($dom) = @_;
 9374:     my $output = $dom;
 9375:     if ($dom ne '') { 
 9376:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 9377:         if ($domdesc ne '') {
 9378:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 9379:         }
 9380:     }
 9381:     return $output;
 9382: }
 9383: 
 9384: sub crumb_utilities {
 9385:     my %elements = (
 9386:        crtuser => {
 9387:            srchterm => 'text',
 9388:            srchin => 'selectbox',
 9389:            srchby => 'selectbox',
 9390:            srchtype => 'selectbox',
 9391:            srchdomain => 'selectbox',
 9392:        },
 9393:        crtusername => {
 9394:            srchterm => 'text',
 9395:            srchdomain => 'selectbox',
 9396:        },
 9397:        docustom => {
 9398:            rolename => 'selectbox',
 9399:            newrolename => 'textbox',
 9400:        },
 9401:        studentform => {
 9402:            srchterm => 'text',
 9403:            srchin => 'selectbox',
 9404:            srchby => 'selectbox',
 9405:            srchtype => 'selectbox',
 9406:            srchdomain => 'selectbox',
 9407:        },
 9408:     );
 9409: 
 9410:     my $jsback .= qq|
 9411: function backPage(formname,prevphase,prevstate) {
 9412:     if (typeof prevphase == 'undefined') {
 9413:         formname.phase.value = '';
 9414:     }
 9415:     else {  
 9416:         formname.phase.value = prevphase;
 9417:     }
 9418:     if (typeof prevstate == 'undefined') {
 9419:         formname.currstate.value = '';
 9420:     }
 9421:     else {
 9422:         formname.currstate.value = prevstate;
 9423:     }
 9424:     formname.submit();
 9425: }
 9426: |;
 9427:     return ($jsback,\%elements);
 9428: }
 9429: 
 9430: sub course_level_table {
 9431:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 9432:     return unless (ref($inccourses) eq 'HASH');
 9433:     my $table = '';
 9434: # Custom Roles?
 9435: 
 9436:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9437:     my %lt=&Apache::lonlocal::texthash(
 9438:             'exs'  => "Existing sections",
 9439:             'new'  => "Define new section",
 9440:             'ssd'  => "Set Start Date",
 9441:             'sed'  => "Set End Date",
 9442:             'crl'  => "Course Level",
 9443:             'act'  => "Activate",
 9444:             'rol'  => "Role",
 9445:             'ext'  => "Extent",
 9446:             'grs'  => "Section",
 9447:             'crd'  => "Credits",
 9448:             'sta'  => "Start",
 9449:             'end'  => "End"
 9450:     );
 9451: 
 9452:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 9453: 	my $thiscourse=$protectedcourse;
 9454: 	$thiscourse=~s:_:/:g;
 9455: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 9456:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 9457: 	my $area=$coursedata{'description'};
 9458:         my $crstype=$coursedata{'type'};
 9459: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 9460: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 9461:         my %sections_count;
 9462:         if (defined($env{'request.course.id'})) {
 9463:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 9464:                 %sections_count = 
 9465: 		    &Apache::loncommon::get_sections($domain,$cnum);
 9466:             }
 9467:         }
 9468:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 9469: 	foreach my $role (@roles) {
 9470:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 9471: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 9472:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 9473:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9474:                                             $plrole,\%sections_count,\%lt,
 9475:                                             $showcredits,$defaultcredits,$crstype);
 9476:             } elsif ($env{'request.course.sec'} ne '') {
 9477:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 9478:                                              $env{'request.course.sec'})) {
 9479:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9480:                                                 $plrole,\%sections_count,\%lt,
 9481:                                                 $showcredits,$defaultcredits,$crstype);
 9482:                 }
 9483:             }
 9484:         }
 9485:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 9486:             foreach my $cust (sort(keys(%customroles))) {
 9487:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 9488:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 9489:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9490:                                             $cust,\%sections_count,\%lt,
 9491:                                             $showcredits,$defaultcredits,$crstype);
 9492:             }
 9493: 	}
 9494:     }
 9495:     return '' if ($table eq ''); # return nothing if there is nothing 
 9496:                                  # in the table
 9497:     my $result;
 9498:     if (!$env{'request.course.id'}) {
 9499:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 9500:     }
 9501:     $result .= 
 9502: &Apache::loncommon::start_data_table().
 9503: &Apache::loncommon::start_data_table_header_row().
 9504: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9505: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 9506:     if ($showcredits) {
 9507:         $result .= $lt{'crd'}.'</th>';
 9508:     }
 9509:     $result .=
 9510: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 9511: '<th>'.$lt{'end'}.'</th>'.
 9512: &Apache::loncommon::end_data_table_header_row().
 9513: $table.
 9514: &Apache::loncommon::end_data_table();
 9515:     return $result;
 9516: }
 9517: 
 9518: sub course_level_row {
 9519:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 9520:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 9521:     my $creditem;
 9522:     my $row = &Apache::loncommon::start_data_table_row().
 9523:               ' <td><input type="checkbox" name="act_'.
 9524:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 9525:               ' <td>'.$plrole.'</td>'."\n".
 9526:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 9527:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 9528:         $row .= 
 9529:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 9530:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 9531:     } else {
 9532:         $row .= '<td>&nbsp;</td>';
 9533:     }
 9534:     if (($role eq 'cc') || ($role eq 'co')) {
 9535:         $row .= '<td>&nbsp;</td>';
 9536:     } elsif ($env{'request.course.sec'} ne '') {
 9537:         $row .= ' <td><input type="hidden" value="'.
 9538:                 $env{'request.course.sec'}.'" '.
 9539:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 9540:                 $env{'request.course.sec'}.'</td>';
 9541:     } else {
 9542:         if (ref($sections_count) eq 'HASH') {
 9543:             my $currsec = 
 9544:                 &Apache::lonuserutils::course_sections($sections_count,
 9545:                                                        $protectedcourse.'_'.$role);
 9546:             $row .= '<td><table class="LC_createuser">'."\n".
 9547:                     '<tr class="LC_section_row">'."\n".
 9548:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 9549:                        $currsec.'</td>'."\n".
 9550:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 9551:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 9552:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 9553:                      '" value="" />'.
 9554:                      '<input type="hidden" '.
 9555:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 9556:                      '</tr></table></td>'."\n";
 9557:         } else {
 9558:             $row .= '<td><input type="text" size="10" '.
 9559:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 9560:         }
 9561:     }
 9562:     $row .= <<ENDTIMEENTRY;
 9563: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 9564: <a href=
 9565: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 9566: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 9567: <a href=
 9568: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9569: ENDTIMEENTRY
 9570:     $row .= &Apache::loncommon::end_data_table_row();
 9571:     return $row;
 9572: }
 9573: 
 9574: sub course_level_dc {
 9575:     my ($dcdom,$showcredits) = @_;
 9576:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9577:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9578:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9579:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9580:                       '<input type="hidden" name="dccourse" value="" />';
 9581:     my $courseform=&Apache::loncommon::selectcourse_link
 9582:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9583:     my $credit_elem;
 9584:     if ($showcredits) {
 9585:         $credit_elem = 'credits';
 9586:     }
 9587:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9588:     my %lt=&Apache::lonlocal::texthash(
 9589:                     'rol'  => "Role",
 9590:                     'grs'  => "Section",
 9591:                     'exs'  => "Existing sections",
 9592:                     'new'  => "Define new section", 
 9593:                     'sta'  => "Start",
 9594:                     'end'  => "End",
 9595:                     'ssd'  => "Set Start Date",
 9596:                     'sed'  => "Set End Date",
 9597:                     'scc'  => "Course/Community",
 9598:                     'crd'  => "Credits",
 9599:                   );
 9600:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9601:                  &Apache::loncommon::start_data_table().
 9602:                  &Apache::loncommon::start_data_table_header_row().
 9603:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9604:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9605:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9606:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9607:                  &Apache::loncommon::end_data_table_header_row();
 9608:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9609:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9610:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9611:                      '<td valign="top"><br /><select name="role">'."\n";
 9612:     foreach my $role (@roles) {
 9613:         my $plrole=&Apache::lonnet::plaintext($role);
 9614:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9615:     }
 9616:     if ( keys(%customroles) > 0) {
 9617:         foreach my $cust (sort(keys(%customroles))) {
 9618:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9619:                     '_'.$env{'user.name'}.'_'.$cust;
 9620:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9621:         }
 9622:     }
 9623:     $otheritems .= '</select></td><td>'.
 9624:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9625:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9626:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9627:                      '<td>&nbsp;&nbsp;</td>'.
 9628:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9629:                      '<input type="text" name="newsec" value="" />'.
 9630:                      '<input type="hidden" name="section" value="" />'.
 9631:                      '<input type="hidden" name="groups" value="" />'.
 9632:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9633:                      '</tr></table></td>'."\n";
 9634:     if ($showcredits) {
 9635:         $otheritems .= '<td><br />'."\n".
 9636:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9637:     }
 9638:     $otheritems .= <<ENDTIMEENTRY;
 9639: <td><br /><input type="hidden" name="start" value='' />
 9640: <a href=
 9641: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9642: <td><br /><input type="hidden" name="end" value='' />
 9643: <a href=
 9644: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9645: ENDTIMEENTRY
 9646:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9647:                    &Apache::loncommon::end_data_table()."\n";
 9648:     return $cb_jscript.$hiddenitems.$header.$otheritems;
 9649: }
 9650: 
 9651: sub update_selfenroll_config {
 9652:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9653:     return unless (ref($currsettings) eq 'HASH');
 9654:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9655:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9656:     my (%changes,%warning);
 9657:     my $curr_types;
 9658:     my %noedit;
 9659:     unless ($context eq 'domain') {
 9660:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9661:     }
 9662:     if (ref($row) eq 'ARRAY') {
 9663:         foreach my $item (@{$row}) {
 9664:             next if ($noedit{$item});
 9665:             if ($item eq 'enroll_dates') {
 9666:                 my (%currenrolldate,%newenrolldate);
 9667:                 foreach my $type ('start','end') {
 9668:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9669:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9670:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9671:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9672:                     }
 9673:                 }
 9674:             } elsif ($item eq 'access_dates') {
 9675:                 my (%currdate,%newdate);
 9676:                 foreach my $type ('start','end') {
 9677:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9678:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9679:                     if ($newdate{$type} ne $currdate{$type}) {
 9680:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9681:                     }
 9682:                 }
 9683:             } elsif ($item eq 'types') {
 9684:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9685:                 if ($env{'form.selfenroll_all'}) {
 9686:                     if ($curr_types ne '*') {
 9687:                         $changes{'internal.selfenroll_types'} = '*';
 9688:                     } else {
 9689:                         next;
 9690:                     }
 9691:                 } else {
 9692:                     my %currdoms;
 9693:                     my @entries = split(/;/,$curr_types);
 9694:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9695:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9696:                     my $newnum = 0;
 9697:                     my @latesttypes;
 9698:                     foreach my $num (@activations) {
 9699:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9700:                         if (@types > 0) {
 9701:                             @types = sort(@types);
 9702:                             my $typestr = join(',',@types);
 9703:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9704:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9705:                             $currdoms{$typedom} = 1;
 9706:                             $newnum ++;
 9707:                         }
 9708:                     }
 9709:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9710:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9711:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9712:                             if (@types > 0) {
 9713:                                 @types = sort(@types);
 9714:                                 my $typestr = join(',',@types);
 9715:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9716:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9717:                                 $currdoms{$typedom} = 1;
 9718:                                 $newnum ++;
 9719:                             }
 9720:                         }
 9721:                     }
 9722:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9723:                         my $typedom = $env{'form.selfenroll_newdom'};
 9724:                         if ((!defined($currdoms{$typedom})) && 
 9725:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9726:                             my $typestr;
 9727:                             my ($othertitle,$usertypes,$types) = 
 9728:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9729:                             my $othervalue = 'any';
 9730:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9731:                                 if (@{$types} > 0) {
 9732:                                     my @esc_types = map { &escape($_); } @{$types};
 9733:                                     $othervalue = 'other';
 9734:                                     $typestr = join(',',(@esc_types,$othervalue));
 9735:                                 }
 9736:                                 $typestr = $othervalue;
 9737:                             } else {
 9738:                                 $typestr = $othervalue;
 9739:                             } 
 9740:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9741:                             $newnum ++ ;
 9742:                         }
 9743:                     }
 9744:                     my $selfenroll_types = join(';',@latesttypes);
 9745:                     if ($selfenroll_types ne $curr_types) {
 9746:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9747:                     }
 9748:                 }
 9749:             } elsif ($item eq 'limit') {
 9750:                 my $newlimit = $env{'form.selfenroll_limit'};
 9751:                 my $newcap = $env{'form.selfenroll_cap'};
 9752:                 $newcap =~s/\s+//g;
 9753:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9754:                 $currlimit = 'none' if ($currlimit eq '');
 9755:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9756:                 if ($newlimit ne $currlimit) {
 9757:                     if ($newlimit ne 'none') {
 9758:                         if ($newcap =~ /^\d+$/) {
 9759:                             if ($newcap ne $currcap) {
 9760:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9761:                             }
 9762:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9763:                         } else {
 9764:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9765:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9766:                         }
 9767:                     } elsif ($currcap ne '') {
 9768:                         $changes{'internal.selfenroll_cap'} = '';
 9769:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9770:                     }
 9771:                 } elsif ($currlimit ne 'none') {
 9772:                     if ($newcap =~ /^\d+$/) {
 9773:                         if ($newcap ne $currcap) {
 9774:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9775:                         }
 9776:                     } else {
 9777:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9778:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9779:                     }
 9780:                 }
 9781:             } elsif ($item eq 'approval') {
 9782:                 my (@currnotified,@newnotified);
 9783:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9784:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9785:                 if ($currnotifylist ne '') {
 9786:                     @currnotified = split(/,/,$currnotifylist);
 9787:                     @currnotified = sort(@currnotified);
 9788:                 }
 9789:                 my $newapproval = $env{'form.selfenroll_approval'};
 9790:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9791:                 @newnotified = sort(@newnotified);
 9792:                 if ($newapproval ne $currapproval) {
 9793:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9794:                     if (!$newapproval) {
 9795:                         if ($currnotifylist ne '') {
 9796:                             $changes{'internal.selfenroll_notifylist'} = '';
 9797:                         }
 9798:                     } else {
 9799:                         my @differences =  
 9800:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9801:                         if (@differences > 0) {
 9802:                             if (@newnotified > 0) {
 9803:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9804:                             } else {
 9805:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9806:                             }
 9807:                         }
 9808:                     }
 9809:                 } else {
 9810:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9811:                     if (@differences > 0) {
 9812:                         if (@newnotified > 0) {
 9813:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9814:                         } else {
 9815:                             $changes{'internal.selfenroll_notifylist'} = '';
 9816:                         }
 9817:                     }
 9818:                 }
 9819:             } else {
 9820:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9821:                 my $newval = $env{'form.selfenroll_'.$item};
 9822:                 if ($item eq 'section') {
 9823:                     $newval = $env{'form.sections'};
 9824:                     if (defined($curr_groups{$newval})) {
 9825:                         $newval = $curr_val;
 9826:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9827:                                           &mt('Group names and section names must be distinct');
 9828:                     } elsif ($newval eq 'all') {
 9829:                         $newval = $curr_val;
 9830:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9831:                     }
 9832:                     if ($newval eq '') {
 9833:                         $newval = 'none';
 9834:                     }
 9835:                 }
 9836:                 if ($newval ne $curr_val) {
 9837:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9838:                 }
 9839:             }
 9840:         }
 9841:         if (keys(%warning) > 0) {
 9842:             foreach my $item (@{$row}) {
 9843:                 if (exists($warning{$item})) {
 9844:                     $r->print($warning{$item}.'<br />');
 9845:                 }
 9846:             } 
 9847:         }
 9848:         if (keys(%changes) > 0) {
 9849:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9850:             if ($putresult eq 'ok') {
 9851:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9852:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9853:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9854:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9855:                                                                 $cnum,undef,undef,'Course');
 9856:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9857:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9858:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9859:                             if (exists($changes{'internal.'.$item})) {
 9860:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9861:                             }
 9862:                         }
 9863:                         my $crsputresult =
 9864:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9865:                                                          $chome,'notime');
 9866:                     }
 9867:                 }
 9868:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9869:                 foreach my $item (@{$row}) {
 9870:                     my $title = $item;
 9871:                     if (ref($lt) eq 'HASH') {
 9872:                         $title = $lt->{$item};
 9873:                     }
 9874:                     if ($item eq 'enroll_dates') {
 9875:                         foreach my $type ('start','end') {
 9876:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9877:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9878:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9879:                                           $title,$type,$newdate).'</li>');
 9880:                             }
 9881:                         }
 9882:                     } elsif ($item eq 'access_dates') {
 9883:                         foreach my $type ('start','end') {
 9884:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9885:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9886:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9887:                                           $title,$type,$newdate).'</li>');
 9888:                             }
 9889:                         }
 9890:                     } elsif ($item eq 'limit') {
 9891:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9892:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9893:                             my ($newval,$newcap);
 9894:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9895:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9896:                             } else {
 9897:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9898:                             }
 9899:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9900:                                 $newval = &mt('No limit');
 9901:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9902:                                      'allstudents') {
 9903:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9904:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9905:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9906:                             } else {
 9907:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9908:                                 if ($currlimit eq 'allstudents') {
 9909:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9910:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9911:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9912:                                 }
 9913:                             }
 9914:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9915:                         }
 9916:                     } elsif ($item eq 'approval') {
 9917:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9918:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9919:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9920:                             my ($newval,$newnotify);
 9921:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9922:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9923:                             } else {   
 9924:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9925:                             }
 9926:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9927:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9928:                                     $changes{'internal.selfenroll_approval'} = '0';
 9929:                                 }
 9930:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9931:                             } else {
 9932:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9933:                                 if ($currapproval !~ /^[012]$/) {
 9934:                                     $currapproval = 0;
 9935:                                 }
 9936:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9937:                             }
 9938:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9939:                             if ($newnotify) {
 9940:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9941:                             } else {
 9942:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9943:                             }
 9944:                             $r->print('</li>'."\n");
 9945:                         }
 9946:                     } else {
 9947:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9948:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9949:                             if ($item eq 'types') {
 9950:                                 if ($newval eq '') {
 9951:                                     $newval = &mt('None');
 9952:                                 } elsif ($newval eq '*') {
 9953:                                     $newval = &mt('Any user in any domain');
 9954:                                 }
 9955:                             } elsif ($item eq 'registered') {
 9956:                                 if ($newval eq '1') {
 9957:                                     $newval = &mt('Yes');
 9958:                                 } elsif ($newval eq '0') {
 9959:                                     $newval = &mt('No');
 9960:                                 }
 9961:                             }
 9962:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9963:                         }
 9964:                     }
 9965:                 }
 9966:                 $r->print('</ul>');
 9967:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9968:                     my %newenvhash;
 9969:                     foreach my $key (keys(%changes)) {
 9970:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9971:                     }
 9972:                     &Apache::lonnet::appenv(\%newenvhash);
 9973:                 }
 9974:             } else {
 9975:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9976:                           &mt('The error was: [_1].',$putresult));
 9977:             }
 9978:         } else {
 9979:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9980:         }
 9981:     } else {
 9982:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9983:     }
 9984:     my $visactions = &cat_visibility($cdom);
 9985:     my ($cathash,%cattype);
 9986:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9987:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9988:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9989:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9990:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9991:     } else {
 9992:         $cathash = {};
 9993:         $cattype{'auth'} = 'std';
 9994:         $cattype{'unauth'} = 'std';
 9995:     }
 9996:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9997:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9998:                   '<br />'.
 9999:                   '<br />'.$visactions->{'take'}.'<ul>'.
10000:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
10001:                   '</ul>');
10002:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
10003:         if ($currsettings->{'uniquecode'}) {
10004:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
10005:         } else {
10006:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10007:                   '<br />'.
10008:                   '<br />'.$visactions->{'take'}.'<ul>'.
10009:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
10010:                   '</ul><br />');
10011:         }
10012:     } else {
10013:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
10014:         if (ref($visactions) eq 'HASH') {
10015:             if (!$visible) {
10016:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10017:                           '<br />');
10018:                 if (ref($vismsgs) eq 'ARRAY') {
10019:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
10020:                     foreach my $item (@{$vismsgs}) {
10021:                         $r->print('<li>'.$visactions->{$item}.'</li>');
10022:                     }
10023:                     $r->print('</ul>');
10024:                 }
10025:                 $r->print($cansetvis);
10026:             }
10027:         }
10028:     } 
10029:     return;
10030: }
10031: 
10032: #---------------------------------------------- end functions for &phase_two
10033: 
10034: #--------------------------------- functions for &phase_two and &phase_three
10035: 
10036: #--------------------------end of functions for &phase_two and &phase_three
10037: 
10038: 1;
10039: __END__
10040: 
10041: 

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