File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.480: download - view: text, annotated - select for diffs
Tue May 21 02:57:15 2024 UTC (5 weeks, 6 days ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Bug 6990. Ability to download tarball of Authoring Space's files/directories.
  - Support use of domain default and also override for individual author(s).
  - Check if there is sufficient disk space to create archive file
  - Each author may only have one archive request in process at a time
  - Remove archive file after download
  - Log archive creation and deletion actions in nohist_archivelog.db in
    author's data directory.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.480 2024/05/21 02:57:15 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 Apache::lonviewcoauthors;
   74: use LONCAPA qw(:DEFAULT :match);
   75: use HTML::Entities;
   76: 
   77: my $loginscript; # piece of javascript used in two separate instances
   78: my $authformnop;
   79: my $authformkrb;
   80: my $authformint;
   81: my $authformfsys;
   82: my $authformloc;
   83: my $authformlti;
   84: 
   85: sub initialize_authen_forms {
   86:     my ($dom,$formname,$curr_authtype,$mode,$readonly) = @_;
   87:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   88:     my %param = ( formname => $formname,
   89:                   kerb_def_dom => $krbdefdom,
   90:                   kerb_def_auth => $krbdef,
   91:                   domain => $dom,
   92:                 );
   93:     my %abv_auth = &auth_abbrev();
   94:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix|lti):(.*)$/) {
   95:         my $long_auth = $1;
   96:         my $curr_autharg = $2;
   97:         my %abv_auth = &auth_abbrev();
   98:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   99:         if ($long_auth =~ /^krb(4|5)$/) {
  100:             $param{'curr_kerb_ver'} = $1;
  101:             $param{'curr_autharg'} = $curr_autharg;
  102:         }
  103:         if ($mode eq 'modifyuser') {
  104:             $param{'mode'} = $mode;
  105:         }
  106:     }
  107:     if ($readonly) {
  108:         $param{'readonly'} = 1;
  109:     }
  110:     $loginscript  = &Apache::loncommon::authform_header(%param);
  111:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  112:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  113:     $authformint  = &Apache::loncommon::authform_internal(%param);
  114:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  115:     $authformloc  = &Apache::loncommon::authform_local(%param);
  116:     $authformlti  = &Apache::loncommon::authform_lti(%param);
  117: }
  118: 
  119: sub auth_abbrev {
  120:     my %abv_auth = (
  121:                      krb5      => 'krb',
  122:                      krb4      => 'krb',
  123:                      internal  => 'int',
  124:                      localauth => 'loc',
  125:                      unix      => 'fsys',
  126:                      lti       => 'lti',
  127:                    );
  128:     return %abv_auth;
  129: }
  130: 
  131: # ====================================================
  132: 
  133: sub user_quotas {
  134:     my ($ccuname,$ccdomain,$name) = @_;
  135:     my %lt = &Apache::lonlocal::texthash(
  136:                    'cust'      => "Custom quota",
  137:                    'chqu'      => "Change quota",
  138:     );
  139:     my ($output,$longinsttype);
  140:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  141:     my %titles = &Apache::lonlocal::texthash (
  142:                     portfolio => "Disk space allocated to user's portfolio files",
  143:                     author    => "Disk space allocated to user's Authoring Space",
  144:                  );
  145:     my ($currquota,$quotatype,$inststatus,$defquota) =
  146:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  147:     if ($longinsttype eq '') {
  148:         if ($inststatus ne '') {
  149:             if ($usertypes->{$inststatus} ne '') {
  150:                 $longinsttype = $usertypes->{$inststatus};
  151:             }
  152:         }
  153:     }
  154:     my ($showquota,$custom_on,$custom_off,$defaultinfo,$colspan);
  155:     $custom_on = ' ';
  156:     $custom_off = ' checked="checked" ';
  157:     $colspan = ' colspan="2"';
  158:     if ($quotatype eq 'custom') {
  159:         $custom_on = $custom_off;
  160:         $custom_off = ' ';
  161:         $showquota = $currquota;
  162:         if ($longinsttype eq '') {
  163:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
  164:                               .' MB.',$defquota);
  165:         } else {
  166:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
  167:                                " MB,[_2]as determined by the user's institutional".
  168:                                " affiliation ([_3]).",$defquota,'<br />',$longinsttype);
  169:         }
  170:     } else {
  171:         if ($longinsttype eq '') {
  172:             $defaultinfo = &mt('For this user, the default quota is [_1]'
  173:                               .' MB.',$defquota);
  174:         } else {
  175:             $defaultinfo = &mt("For this user, the default quota of [_1]".
  176:                                " MB,[_2]is determined by the user's institutional".
  177:                                " affiliation ([_3]).",$defquota,'<br />'.$longinsttype);
  178:         }
  179:     }
  180: 
  181:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  182:         $output .= '<tr class="LC_info_row">'."\n".
  183:                    '    <td'.$colspan.'>'.$titles{$name}.'</td>'."\n".
  184:                    '  </tr>'."\n".
  185:                    &Apache::loncommon::start_data_table_row()."\n".
  186:                    '  <td'.$colspan.'><span class="LC_nobreak">'.
  187:                    &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  188:                    $defaultinfo.'</td>'."\n".
  189:                    &Apache::loncommon::end_data_table_row()."\n".
  190:                    &Apache::loncommon::start_data_table_row()."\n".
  191:                    '<td'.$colspan.'><span class="LC_nobreak">'.$lt{'chqu'}.
  192:                    ': <label>'.
  193:                    '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  194:                    'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  195:                    ' /><span class="LC_nobreak">'.
  196:                    &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  197:                    '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  198:                    'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  199:                    ' />'.$lt{'cust'}.':</label>&nbsp;'.
  200:                    '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  201:                    'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  202:                    ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  203:                    &Apache::loncommon::end_data_table_row()."\n";
  204:     }
  205:     return $output;
  206: }
  207: 
  208: sub user_quota_js {
  209:     return  <<"END_SCRIPT";
  210: <script type="text/javascript">
  211: // <![CDATA[
  212: function quota_changes(caller,context) {
  213:     var customoff = document.getElementById('custom_'+context+'quota_off');
  214:     var customon = document.getElementById('custom_'+context+'quota_on');
  215:     var number = document.getElementById(context+'quota');
  216:     if (caller == "custom") {
  217:         if (customoff) {
  218:             if (customoff.checked) {
  219:                 number.value = "";
  220:             }
  221:         }
  222:     }
  223:     if (caller == "quota") {
  224:         if (customon) {
  225:             customon.checked = true;
  226:         }
  227:     }
  228:     return;
  229: }
  230: // ]]>
  231: </script>
  232: END_SCRIPT
  233: 
  234: }
  235: 
  236: sub set_custom_js {
  237:     return  <<"END_SCRIPT";
  238: 
  239: <script type="text/javascript">
  240: // <![CDATA[
  241: function toggleCustom(form,item,name) {
  242:     if (document.getElementById(item)) {
  243:         var divid = document.getElementById(item);
  244:         var radioname = form.elements[name];
  245:         if (radioname) {
  246:             if (radioname.length > 0) {
  247:                 var setvis;
  248:                 var RegExp = /^customtext_(aboutme|blog|portfolio|portaccess|timezone|webdav|archive)\$/;
  249:                 for (var i=0; i<radioname.length; i++) {
  250:                     if (radioname[i].checked == true) {
  251:                         if (radioname[i].value == 1) {
  252:                             if (RegExp.test(item)) {
  253:                                 divid.style.display = 'inline';
  254:                             } else {
  255:                                 divid.style.display = 'block';
  256:                             }
  257:                             setvis = 1;
  258:                         }
  259:                         break;
  260:                     }
  261:                 }
  262:                 if (!setvis) {
  263:                     divid.style.display = 'none';
  264:                 }
  265:             }
  266:         }
  267:     }
  268:     return;
  269: }
  270: // ]]>
  271: </script>
  272: 
  273: END_SCRIPT
  274: 
  275: }
  276: 
  277: sub build_tools_display {
  278:     my ($ccuname,$ccdomain,$context) = @_;
  279:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  280:         $colspan,$isadv,%domconfig,@defaulteditors,@customeditors,@custommanagers,
  281:         @possmanagers);
  282:     my %lt = &Apache::lonlocal::texthash (
  283:                    'blog'       => "Personal User Blog",
  284:                    'aboutme'    => "Personal Information Page",
  285:                    'webdav'     => "WebDAV access to Authoring Spaces (https)",
  286:                    'editors'    => "Available Editors",
  287:                    'managers'   => "Co-authors who can add/revoke roles",
  288:                    'archive'    => "Managers can download tar.gz file of Authoring Space",
  289:                    'portfolio'  => "Personal User Portfolio",
  290:                    'portaccess' => "Portfolio Shareable",
  291:                    'timezone'   => "Can set Time Zone",
  292:                    'avai'       => "Available",
  293:                    'cusa'       => "availability",
  294:                    'chse'       => "Change setting",
  295:                    'usde'       => "Use default",
  296:                    'uscu'       => "Use custom",
  297:                    'official'   => 'Can request creation of official courses',
  298:                    'unofficial' => 'Can request creation of unofficial courses',
  299:                    'community'  => 'Can request creation of communities',
  300:                    'textbook'   => 'Can request creation of textbook courses',
  301:                    'placement'  => 'Can request creation of placement tests',
  302:                    'lti'        => 'Can request creation of LTI courses',
  303:                    'requestauthor'  => 'Can request author space',
  304:                    'edit'       => 'Standard editor (Edit)',
  305:                    'xml'        => 'Text editor (EditXML)',
  306:                    'daxe'       => 'Daxe editor (Daxe)',
  307:     );
  308:     $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  309:     if ($context eq 'requestcourses') {
  310:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  311:                       'requestcourses.official','requestcourses.unofficial',
  312:                       'requestcourses.community','requestcourses.textbook',
  313:                       'requestcourses.placement','requestcourses.lti');
  314:         @usertools = ('official','unofficial','community','textbook','placement','lti');
  315:         @options =('norequest','approval','autolimit','validate');
  316:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  317:         %reqtitles = &courserequest_titles();
  318:         %reqdisplay = &courserequest_display();
  319:         %domconfig =
  320:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  321:     } elsif ($context eq 'requestauthor') {
  322:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'requestauthor');
  323:         @usertools = ('requestauthor');
  324:         @options =('norequest','approval','automatic');
  325:         %reqtitles = &requestauthor_titles();
  326:         %reqdisplay = &requestauthor_display();
  327:         %domconfig =
  328:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  329:     } elsif ($context eq 'authordefaults') {
  330:         %domconfig =
  331:             &Apache::lonnet::get_dom('configuration',['quotas','authordefaults'],$ccdomain);
  332:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'tools.webdav',
  333:                                                     'authoreditors','authormanagers',
  334:                                                     'authorarchive','domcoord.author');
  335:         @usertools = ('webdav','editors','managers','archive');
  336:         $colspan = ' colspan="2"';
  337:     } else {
  338:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  339:                           'tools.aboutme','tools.portfolio','tools.blog',
  340:                           'tools.timezone','tools.portaccess');
  341:         @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
  342:         $colspan = ' colspan="2"';
  343:     }
  344:     foreach my $item (@usertools) {
  345:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  346:             $currdisp,$custdisp,$custradio,$onclick,$customsty,$editorsty);
  347:         $cust_off = 'checked="checked" ';
  348:         $tool_on = 'checked="checked" ';
  349:         unless (($context eq 'authordefaults') || ($item eq 'webdav')) {
  350:             $curr_access =
  351:                 &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  352:                                                   $context,\%userenv,'',
  353:                                                   {'is_adv' => $isadv});
  354:         }
  355:         if ($context eq 'requestauthor') {
  356:             if ($userenv{$context} ne '') {
  357:                 $cust_on = ' checked="checked" ';
  358:                 $cust_off = '';
  359:             }
  360:         } elsif ($context eq 'authordefaults') {
  361:             if (($item eq 'editors') || ($item eq 'archive')) {
  362:                 if ($userenv{'author'.$item} ne '') {
  363:                     $cust_on = ' checked="checked" ';
  364:                     $cust_off = '';
  365:                     if ($item eq 'archive') {
  366:                         $curr_access = $userenv{'author'.$item};
  367:                     }
  368:                 } elsif ($item eq 'archive') {
  369:                     $curr_access = 0;
  370:                     if (ref($domconfig{'authordefaults'}) eq 'HASH') {
  371:                         $curr_access = $domconfig{'authordefaults'}{'archive'};
  372:                     }
  373:                 }
  374:             } elsif ($item eq 'webdav') {
  375:                 if ($userenv{'tools.'.$item} ne '') {
  376:                     $cust_on = ' checked="checked" ';
  377:                     $cust_off = '';
  378:                 }
  379:             }
  380:         } elsif ($userenv{$context.'.'.$item} ne '') {
  381:             $cust_on = ' checked="checked" ';
  382:             $cust_off = '';
  383:         }
  384:         if ($context eq 'requestcourses') {
  385:             if ($userenv{$context.'.'.$item} eq '') {
  386:                 $custom_access = &mt('Currently from default setting.');
  387:                 $customsty = ' style="display:none;"';
  388:             } else {
  389:                 $custom_access = &mt('Currently from custom setting.');
  390:                 $customsty = ' style="display:block;"';
  391:             }
  392:         } elsif ($context eq 'requestauthor') {
  393:             if ($userenv{$context} eq '') {
  394:                 $custom_access = &mt('Currently from default setting.');
  395:                 $customsty = ' style="display:none;"';
  396:             } else {
  397:                 $custom_access = &mt('Currently from custom setting.');
  398:                 $customsty = ' style="display:block;"';
  399:             }
  400:         } elsif ($item eq 'editors') {
  401:             if ($userenv{'author'.$item} eq '') {
  402:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
  403:                     @defaulteditors = @{$domconfig{'authordefaults'}{'editors'}};
  404:                 } else {
  405:                     @defaulteditors = ('edit','xml');
  406:                 }
  407:                 $custom_access = &mt('Can use: [_1]',
  408:                                                join(', ', map { $lt{$_} } @defaulteditors));
  409:                 $editorsty = ' style="display:none;"';
  410:             } else {
  411:                 $custom_access = &mt('Currently from custom setting.');
  412:                 foreach my $editor (split(/,/,$userenv{'author'.$item})) {
  413:                     if ($editor =~ /^(edit|daxe|xml)$/) {
  414:                         push(@customeditors,$editor);
  415:                     }
  416:                 }
  417:                 if (@customeditors) {
  418:                     if (@customeditors > 1) {
  419:                         $custom_access .= '<br /><span>';
  420:                     } else {
  421:                         $custom_access .= ' <span class="LC_nobreak">';
  422:                     }
  423:                     $custom_access .= &mt('Can use: [_1]',
  424:                                           join(', ', map { $lt{$_} } @customeditors)).
  425:                                       '</span>';
  426:                 } else {
  427:                     $custom_access .= ' '.&mt('No available editors');
  428:                 }
  429:                 $editorsty = ' style="display:block;"';
  430:             }
  431:         } elsif ($item eq 'managers') {
  432:             my %ca_roles = &Apache::lonnet::get_my_roles($ccuname,$ccdomain,undef,
  433:                                                          ['active','future'],['ca']);
  434:             if (keys(%ca_roles)) {
  435:                 foreach my $entry (sort(keys(%ca_roles))) {
  436:                     if ($entry =~ /^($match_username\:$match_domain):ca$/) {
  437:                         my $user = $1;
  438:                         unless ($user eq "$ccuname:$ccdomain") {
  439:                             push(@possmanagers,$user);
  440:                         }
  441:                     }
  442:                 }
  443:             }
  444:             if ($userenv{'author'.$item} eq '') {
  445:                 $custom_access = &mt('Currently author manages co-author roles');
  446:             } else {
  447:                 if (keys(%ca_roles)) {
  448:                     foreach my $user (split(/,/,$userenv{'author'.$item})) {
  449:                         if ($user =~ /^($match_username):($match_domain)$/) {
  450:                             if (exists($ca_roles{$user.':ca'})) {
  451:                                 unless ($user eq "$ccuname:$ccdomain") {
  452:                                     push(@custommanagers,$user);
  453:                                 }
  454:                             }
  455:                         }
  456:                     }
  457:                 }
  458:                 if (@custommanagers) {
  459:                     $custom_access = &mt('Co-authors who manage co-author roles: [_1]',
  460:                                          join(', ',@custommanagers));
  461:                 } else {
  462:                     $custom_access = &mt('Currently author manages co-author roles');
  463:                 }
  464:             }
  465:         } else {
  466:             my $current = $userenv{$context.'.'.$item};
  467:             if ($item eq 'webdav') {
  468:                 $current = $userenv{'tools.webdav'};
  469:             } elsif ($item eq 'archive') {
  470:                 $current = $userenv{'author'.$item};
  471:             }
  472:             if ($current eq '') {
  473:                 $custom_access =
  474:                     &mt('Availability determined currently from default setting.');
  475:                 if (!$curr_access) {
  476:                     $tool_off = 'checked="checked" ';
  477:                     $tool_on = '';
  478:                 }
  479:                 $customsty = ' style="display:none;"';
  480:             } else {
  481:                 $custom_access =
  482:                     &mt('Availability determined currently from custom setting.');
  483:                 if ($current == 0) {
  484:                     $tool_off = 'checked="checked" ';
  485:                     $tool_on = '';
  486:                 }
  487:                 $customsty = ' style="display:inline;"';
  488:             }
  489:         }
  490:         $output .= '  <tr class="LC_info_row">'."\n".
  491:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  492:                    '  </tr>'."\n".
  493:                    &Apache::loncommon::start_data_table_row()."\n";
  494:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  495:             my ($curroption,$currlimit);
  496:             my $envkey = $context.'.'.$item;
  497:             if ($context eq 'requestauthor') {
  498:                 $envkey = $context;
  499:             }
  500:             if ($userenv{$envkey} ne '') {
  501:                 $curroption = $userenv{$envkey};
  502:             } else {
  503:                 my (@inststatuses);
  504:                 if ($context eq 'requestcourses') {
  505:                     $curroption =
  506:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  507:                                                                       $isadv,$ccdomain,$item,
  508:                                                                       \@inststatuses,\%domconfig);
  509:                 } else {
  510:                      $curroption = 
  511:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  512:                                                                        $isadv,$ccdomain,undef,
  513:                                                                        \@inststatuses,\%domconfig);
  514:                 }
  515:             }
  516:             if (!$curroption) {
  517:                 $curroption = 'norequest';
  518:             }
  519:             my $name = 'crsreq_'.$item;
  520:             if ($context eq 'requestauthor') {
  521:                 $name = $item;
  522:             }
  523:             $onclick = ' onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');"';
  524:             if ($curroption =~ /^autolimit=(\d*)$/) {
  525:                 $currlimit = $1;
  526:                 if ($currlimit eq '') {
  527:                     $currdisp = &mt('Yes, automatic creation');
  528:                 } else {
  529:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  530:                 }
  531:             } else {
  532:                 $currdisp = $reqdisplay{$curroption};
  533:             }
  534:             $custdisp = '<fieldset id="customtext_'.$item.'"'.$customsty.'>';
  535:             foreach my $option (@options) {
  536:                 my $val = $option;
  537:                 if ($option eq 'norequest') {
  538:                     $val = 0;
  539:                 }
  540:                 if ($option eq 'validate') {
  541:                     my $canvalidate = 0;
  542:                     if (ref($validations{$item}) eq 'HASH') {
  543:                         if ($validations{$item}{'_custom_'}) {
  544:                             $canvalidate = 1;
  545:                         }
  546:                     }
  547:                     next if (!$canvalidate);
  548:                 }
  549:                 my $checked = '';
  550:                 if ($option eq $curroption) {
  551:                     $checked = ' checked="checked"';
  552:                 } elsif ($option eq 'autolimit') {
  553:                     if ($curroption =~ /^autolimit/) {
  554:                         $checked = ' checked="checked"';
  555:                     }
  556:                 }
  557:                 if ($option eq 'autolimit') {
  558:                     $custdisp .= '<br />';
  559:                 }
  560:                 $custdisp .= '<span class="LC_nobreak"><label>'.
  561:                              '<input type="radio" name="'.$name.'" '.
  562:                              'value="'.$val.'"'.$checked.' />'.
  563:                              $reqtitles{$option}.'</label>&nbsp;';
  564:                 if ($option eq 'autolimit') {
  565:                     $custdisp .= '<input type="text" name="'.$name.
  566:                                  '_limit" size="1" '.
  567:                                  'value="'.$currlimit.'" />&nbsp;'.
  568:                                  $reqtitles{'unlimited'}.'</span>';
  569:                 } else {
  570:                     $custdisp .= '</span>';
  571:                 }
  572:                 $custdisp .= ' ';
  573:             }
  574:             $custdisp .= '</fieldset>';
  575:             $custradio = '<br />'.$custdisp;
  576:         } elsif ($item eq 'editors') {
  577:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  578:                        &Apache::loncommon::end_data_table_row()."\n";
  579:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  580:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  581:                           '<td'.$colspan.'><span class="LC_nobreak">'.
  582:                           $lt{'chse'}.': <label>'.
  583:                           '<input type="radio" name="custom'.$item.'" value="0" '.
  584:                           $cust_off.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  585:                           $lt{'usde'}.'</label>'.('&nbsp;' x3).
  586:                           '<label><input type="radio" name="custom'.$item.'" value="1" '.
  587:                           $cust_on.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  588:                           $lt{'uscu'}.'</label></span><br />'.
  589:                           '<fieldset id="customtext_'.$item.'"'.$editorsty.'>';
  590:                 foreach my $editor ('edit','xml','daxe') {
  591:                     my $checked;
  592:                     if ($userenv{'author'.$item} eq '') {
  593:                         if (grep(/^\Q$editor\E$/,@defaulteditors)) {
  594:                             $checked = ' checked="checked"';
  595:                         }
  596:                     } elsif (grep(/^\Q$editor\E$/,@customeditors)) {
  597:                         $checked = ' checked="checked"';
  598:                     }
  599:                     $output .= '<span style="LC_nobreak"><label>'.
  600:                                '<input type="checkbox" name="custom_editor" '.
  601:                                'value="'.$editor.'"'.$checked.' />'.
  602:                                $lt{$editor}.'</label></span> ';
  603:                 }
  604:                 $output .= '</fieldset></td>'.
  605:                            &Apache::loncommon::end_data_table_row()."\n";
  606:             }
  607:         } elsif ($item eq 'managers') {
  608:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  609:                        &Apache::loncommon::end_data_table_row()."\n";
  610:             unless ((&Apache::lonnet::allowed('udp',$ccdomain)) ||
  611:                     (($userenv{'domcoord.author'} eq 'blocked') &&
  612:                      (($env{'user.name'} ne $ccuname) || ($env{'user.domain'} ne $ccdomain)))) {
  613:                 $output .=
  614:                     &Apache::loncommon::start_data_table_row()."\n".
  615:                     '<td'.$colspan.'>';
  616:                 if (@possmanagers) {
  617:                     $output .= &mt('Select manager(s)').': ';
  618:                     foreach my $user (@possmanagers) {
  619:                         my $checked;
  620:                         if (grep(/^\Q$user\E$/,@custommanagers)) {
  621:                             $checked = ' checked="checked"';
  622:                         }
  623:                         $output .= '<span style="LC_nobreak"><label>'.
  624:                                    '<input type="checkbox" name="custommanagers" '.
  625:                                    'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
  626:                                    $user.'</label></span> ';
  627:                     }
  628:                 } else {
  629:                     $output .= &mt('No co-author roles assignable as manager');
  630:                 }
  631:                 $output .= '</td>'.
  632:                            &Apache::loncommon::end_data_table_row()."\n";
  633:             }
  634:         } else {
  635:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  636:             my $name = $context.'_'.$item;
  637:             $onclick = 'onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');" ';
  638:             $custdisp = '<span class="LC_nobreak"><label>'.
  639:                         '<input type="radio" name="'.$name.'"'.
  640:                         ' value="1" '.$tool_on.$onclick.'/>'.&mt('On').'</label>&nbsp;<label>'.
  641:                         '<input type="radio" name="'.$name.'" value="0" '.
  642:                         $tool_off.$onclick.'/>'.&mt('Off').'</label></span>';
  643:             $custradio = '<span id="customtext_'.$item.'"'.$customsty.' class="LC_nobreak">'.
  644:                          '--'.$lt{'cusa'}.':&nbsp;'.$custdisp.'</span>';
  645:         }
  646:         unless (($item eq 'editors') || ($item eq 'managers')) {
  647:             $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  648:                        $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  649:                        &Apache::loncommon::end_data_table_row()."\n";
  650:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  651:                 $output .=
  652:                    &Apache::loncommon::start_data_table_row()."\n".
  653:                    '<td><span class="LC_nobreak">'.
  654:                    $lt{'chse'}.': <label>'.
  655:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  656:                    $cust_off.$onclick.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  657:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  658:                    $cust_on.$onclick.'/>'.$lt{'uscu'}.'</label></span>';
  659:                 if ($colspan) {
  660:                     $output .= '</td><td>';
  661:                 }
  662:                 $output .= $custradio.'</td>'.
  663:                            &Apache::loncommon::end_data_table_row()."\n";
  664:             }
  665:         }
  666:     }
  667:     return $output;
  668: }
  669: 
  670: sub coursereq_externaluser {
  671:     my ($ccuname,$ccdomain,$cdom) = @_;
  672:     my (@usertools,@options,%validations,%userenv,$output);
  673:     my %lt = &Apache::lonlocal::texthash (
  674:                    'official'   => 'Can request creation of official courses',
  675:                    'unofficial' => 'Can request creation of unofficial courses',
  676:                    'community'  => 'Can request creation of communities',
  677:                    'textbook'   => 'Can request creation of textbook courses',
  678:                    'placement'  => 'Can request creation of placement tests',
  679:     );
  680: 
  681:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  682:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  683:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  684:                       'reqcrsotherdom.placement');
  685:     @usertools = ('official','unofficial','community','textbook','placement');
  686:     @options = ('approval','validate','autolimit');
  687:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  688:     my $optregex = join('|',@options);
  689:     my %reqtitles = &courserequest_titles();
  690:     foreach my $item (@usertools) {
  691:         my ($curroption,$currlimit,$tooloff);
  692:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  693:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  694:             foreach my $req (@curr) {
  695:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  696:                     $curroption = $1;
  697:                     $currlimit = $2;
  698:                     last;
  699:                 }
  700:             }
  701:             if (!$curroption) {
  702:                 $curroption = 'norequest';
  703:                 $tooloff = ' checked="checked"';
  704:             }
  705:         } else {
  706:             $curroption = 'norequest';
  707:             $tooloff = ' checked="checked"';
  708:         }
  709:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  710:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  711:                   '<table><tr><td valign="top">'."\n".
  712:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  713:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  714:                   '</label></td>';
  715:         foreach my $option (@options) {
  716:             if ($option eq 'validate') {
  717:                 my $canvalidate = 0;
  718:                 if (ref($validations{$item}) eq 'HASH') {
  719:                     if ($validations{$item}{'_external_'}) {
  720:                         $canvalidate = 1;
  721:                     }
  722:                 }
  723:                 next if (!$canvalidate);
  724:             }
  725:             my $checked = '';
  726:             if ($option eq $curroption) {
  727:                 $checked = ' checked="checked"';
  728:             }
  729:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  730:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  731:                        '" value="'.$option.'"'.$checked.' />'.
  732:                        $reqtitles{$option}.'</label>';
  733:             if ($option eq 'autolimit') {
  734:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  735:                            $item.'_limit" size="1" '.
  736:                            'value="'.$currlimit.'" /></span>'.
  737:                            '<br />'.$reqtitles{'unlimited'};
  738:             } else {
  739:                 $output .= '</span>';
  740:             }
  741:             $output .= '</td>';
  742:         }
  743:         $output .= '</td></tr></table></td>'."\n".
  744:                    &Apache::loncommon::end_data_table_row()."\n";
  745:     }
  746:     return $output;
  747: }
  748: 
  749: sub domainrole_req {
  750:     my ($ccuname,$ccdomain) = @_;
  751:     return '<br /><h3>'.
  752:            &mt('Can Request Assignment of Domain Roles?').
  753:            '</h3>'."\n".
  754:            &Apache::loncommon::start_data_table().
  755:            &build_tools_display($ccuname,$ccdomain,
  756:                                 'requestauthor').
  757:            &Apache::loncommon::end_data_table();
  758: }
  759: 
  760: sub authoring_defaults {
  761:     my ($ccuname,$ccdomain) = @_;
  762:     return '<br /><h3>'.
  763:            &mt('Authoring Space defaults (if role assigned)').
  764:            '</h3>'."\n".
  765:            &Apache::loncommon::start_data_table().
  766:            &build_tools_display($ccuname,$ccdomain,
  767:                                 'authordefaults').
  768:            &user_quotas($ccuname,$ccdomain,'author').
  769:            &Apache::loncommon::end_data_table();
  770: }
  771: 
  772: sub courserequest_titles {
  773:     my %titles = &Apache::lonlocal::texthash (
  774:                                    official   => 'Official',
  775:                                    unofficial => 'Unofficial',
  776:                                    community  => 'Communities',
  777:                                    textbook   => 'Textbook',
  778:                                    placement  => 'Placement Tests',
  779:                                    lti        => 'LTI Provider',
  780:                                    norequest  => 'Not allowed',
  781:                                    approval   => 'Approval by Dom. Coord.',
  782:                                    validate   => 'With validation',
  783:                                    autolimit  => 'Numerical limit',
  784:                                    unlimited  => '(blank for unlimited)',
  785:                  );
  786:     return %titles;
  787: }
  788: 
  789: sub courserequest_display {
  790:     my %titles = &Apache::lonlocal::texthash (
  791:                                    approval   => 'Yes, need approval',
  792:                                    validate   => 'Yes, with validation',
  793:                                    norequest  => 'No',
  794:    );
  795:    return %titles;
  796: }
  797: 
  798: sub requestauthor_titles {
  799:     my %titles = &Apache::lonlocal::texthash (
  800:                                    norequest  => 'Not allowed',
  801:                                    approval   => 'Approval by Dom. Coord.',
  802:                                    automatic  => 'Automatic approval',
  803:                  );
  804:     return %titles;
  805: 
  806: }
  807: 
  808: sub requestauthor_display {
  809:     my %titles = &Apache::lonlocal::texthash (
  810:                                    approval   => 'Yes, need approval',
  811:                                    automatic  => 'Yes, automatic approval',
  812:                                    norequest  => 'No',
  813:    );
  814:    return %titles;
  815: }
  816: 
  817: sub requestchange_display {
  818:     my %titles = &Apache::lonlocal::texthash (
  819:                                    approval   => "availability set to 'on' (approval required)", 
  820:                                    automatic  => "availability set to 'on' (automatic approval)",
  821:                                    norequest  => "availability set to 'off'",
  822:    );
  823:    return %titles;
  824: }
  825: 
  826: sub curr_requestauthor {
  827:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  828:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  829:     if ($uname eq '' || $udom eq '') {
  830:         $uname = $env{'user.name'};
  831:         $udom = $env{'user.domain'};
  832:         $isadv = $env{'user.adv'};
  833:     }
  834:     my (%userenv,%settings,$val);
  835:     my @options = ('automatic','approval');
  836:     %userenv =
  837:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  838:     if ($userenv{'requestauthor'}) {
  839:         $val = $userenv{'requestauthor'};
  840:         @{$inststatuses} = ('_custom_');
  841:     } else {
  842:         my %alltasks;
  843:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  844:             %settings = %{$domconfig->{'requestauthor'}};
  845:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  846:                 $val = $settings{'_LC_adv'};
  847:                 @{$inststatuses} = ('_LC_adv_');
  848:             } else {
  849:                 if ($userenv{'inststatus'} ne '') {
  850:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  851:                 } else {
  852:                     @{$inststatuses} = ('default');
  853:                 }
  854:                 foreach my $status (@{$inststatuses}) {
  855:                     if (exists($settings{$status})) {
  856:                         my $value = $settings{$status};
  857:                         next unless ($value);
  858:                         unless (exists($alltasks{$value})) {
  859:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  860:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  861:                                     push(@{$alltasks{$value}},$status);
  862:                                 }
  863:                             } else {
  864:                                 @{$alltasks{$value}} = ($status);
  865:                             }
  866:                         }
  867:                     }
  868:                 }
  869:                 foreach my $option (@options) {
  870:                     if ($alltasks{$option}) {
  871:                         $val = $option;
  872:                         last;
  873:                     }
  874:                 }
  875:             }
  876:         }
  877:     }
  878:     return $val;
  879: }
  880: 
  881: # =================================================================== Phase one
  882: 
  883: sub print_username_entry_form {
  884:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  885:         $permission) = @_;
  886:     my $defdom=$env{'request.role.domain'};
  887:     my $formtoset = 'crtuser';
  888:     if (exists($env{'form.startrolename'})) {
  889:         $formtoset = 'docustom';
  890:         $env{'form.rolename'} = $env{'form.startrolename'};
  891:     } elsif ($env{'form.origform'} eq 'crtusername') {
  892:         $formtoset =  $env{'form.origform'};
  893:     }
  894: 
  895:     my ($jsback,$elements) = &crumb_utilities();
  896: 
  897:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  898:         '<script type="text/javascript">'."\n".
  899:         '// <![CDATA['."\n".
  900:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  901:         '// ]]>'."\n".
  902:         '</script>'."\n";
  903: 
  904:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  905:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  906:         && (&Apache::lonnet::allowed('mcr','/'))) {
  907:         $jscript .= &customrole_javascript();
  908:     }
  909:     my $helpitem = 'Course_Change_Privileges';
  910:     if ($env{'form.action'} eq 'custom') {
  911:         if ($context eq 'course') {
  912:             $helpitem = 'Course_Editing_Custom_Roles';
  913:         } elsif ($context eq 'domain') {
  914:             $helpitem = 'Domain_Editing_Custom_Roles';
  915:         }
  916:     } elsif ($env{'form.action'} eq 'singlestudent') {
  917:         $helpitem = 'Course_Add_Student';
  918:     } elsif ($env{'form.action'} eq 'accesslogs') {
  919:         $helpitem = 'Domain_User_Access_Logs';
  920:     } elsif ($context eq 'author') {
  921:         $helpitem = 'Author_Change_Privileges';
  922:     } elsif ($context eq 'domain') {
  923:         if ($permission->{'cusr'}) {
  924:             $helpitem = 'Domain_Change_Privileges';
  925:         } elsif ($permission->{'view'}) {
  926:             $helpitem = 'Domain_View_Privileges';
  927:         } else {
  928:             undef($helpitem);
  929:         }
  930:     }
  931:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  932:     if ($env{'form.action'} eq 'custom') {
  933:         push(@{$brcrum},
  934:                  {href=>"javascript:backPage(document.crtuser)",       
  935:                   text=>"Pick custom role",
  936:                   help => $helpitem,}
  937:                  );
  938:     } else {
  939:         push (@{$brcrum},
  940:                   {href => "javascript:backPage(document.crtuser)",
  941:                    text => $breadcrumb_text{'search'},
  942:                    help => $helpitem,
  943:                    faq  => 282,
  944:                    bug  => 'Instructor Interface',}
  945:                   );
  946:     }
  947:     my %loaditems = (
  948:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  949:                     );
  950:     my $args = {bread_crumbs           => $brcrum,
  951:                 bread_crumbs_component => 'User Management',
  952:                 add_entries            => \%loaditems,};
  953:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  954: 
  955:     my %lt=&Apache::lonlocal::texthash(
  956:                     'srst' => 'Search for a user and enroll as a student',
  957:                     'srme' => 'Search for a user and enroll as a member',
  958:                     'srad' => 'Search for a user and modify/add user information or roles',
  959:                     'srvu' => 'Search for a user and view user information and roles',
  960:                     'srva' => 'Search for a user and view access log information',
  961: 		    'usr'  => "Username",
  962:                     'dom'  => "Domain",
  963:                     'ecrp' => "Define or Edit Custom Role",
  964:                     'nr'   => "role name",
  965:                     'cre'  => "Next",
  966: 				       );
  967: 
  968:     if ($env{'form.action'} eq 'custom') {
  969:         if (&Apache::lonnet::allowed('mcr','/')) {
  970:             my $newroletext = &mt('Define new custom role:');
  971:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  972:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  973:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  974:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  975:                       &Apache::loncommon::start_data_table().
  976:                       &Apache::loncommon::start_data_table_row().
  977:                       '<td>');
  978:             if (keys(%existingroles) > 0) {
  979:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  980:             } else {
  981:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  982:             }
  983:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  984:                       &Apache::loncommon::end_data_table_row());
  985:             if (keys(%existingroles) > 0) {
  986:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  987:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  988:                           &mt('View/Modify existing role:').'</b></label></td>'.
  989:                           '<td align="center"><br />'.
  990:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  991:                           '<option value="" selected="selected">'.
  992:                           &mt('Select'));
  993:                 foreach my $role (sort(keys(%existingroles))) {
  994:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  995:                 }
  996:                 $r->print('</select>'.
  997:                           '</td>'.
  998:                           &Apache::loncommon::end_data_table_row());
  999:             }
 1000:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
 1001:                       '<input name="customeditor" type="submit" value="'.
 1002:                       $lt{'cre'}.'" /></p>'.
 1003:                       '</form>');
 1004:         }
 1005:     } else {
 1006:         my $actiontext = $lt{'srad'};
 1007:         my $fixeddom;
 1008:         if ($env{'form.action'} eq 'singlestudent') {
 1009:             if ($crstype eq 'Community') {
 1010:                 $actiontext = $lt{'srme'};
 1011:             } else {
 1012:                 $actiontext = $lt{'srst'};
 1013:             }
 1014:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1015:             $actiontext = $lt{'srva'};
 1016:             $fixeddom = 1;
 1017:         } elsif (($env{'form.action'} eq 'singleuser') &&
 1018:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
 1019:             $actiontext = $lt{'srvu'};
 1020:             $fixeddom = 1;
 1021:         }
 1022:         $r->print("<h3>$actiontext</h3>");
 1023:         if ($env{'form.origform'} ne 'crtusername') {
 1024:             if ($response) {
 1025:                $r->print("\n<div>$response</div>".
 1026:                          '<br clear="all" />');
 1027:             }
 1028:         }
 1029:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
 1030:     }
 1031: }
 1032: 
 1033: sub customrole_javascript {
 1034:     my $js = <<"END";
 1035: <script type="text/javascript">
 1036: // <![CDATA[
 1037: 
 1038: function setCustomFields() {
 1039:     if (document.docustom.customroleaction.length > 0) {
 1040:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1041:             if (document.docustom.customroleaction[i].checked) {
 1042:                 if (document.docustom.customroleaction[i].value == 'new') {
 1043:                     document.docustom.rolename.selectedIndex = 0;
 1044:                 } else {
 1045:                     document.docustom.newrolename.value = '';
 1046:                 }
 1047:             }
 1048:         }
 1049:     }
 1050:     return;
 1051: }
 1052: 
 1053: function setCustomAction(caller) {
 1054:     if (document.docustom.customroleaction.length > 0) {
 1055:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1056:             if (document.docustom.customroleaction[i].value == caller) {
 1057:                 document.docustom.customroleaction[i].checked = true;
 1058:             }
 1059:         }
 1060:     }
 1061:     setCustomFields();
 1062:     return;
 1063: }
 1064: 
 1065: // ]]>
 1066: </script>
 1067: END
 1068:     return $js;
 1069: }
 1070: 
 1071: sub entry_form {
 1072:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
 1073:     my ($usertype,$inexact);
 1074:     if (ref($srch) eq 'HASH') {
 1075:         if (($srch->{'srchin'} eq 'dom') &&
 1076:             ($srch->{'srchby'} eq 'uname') &&
 1077:             ($srch->{'srchtype'} eq 'exact') &&
 1078:             ($srch->{'srchdomain'} ne '') &&
 1079:             ($srch->{'srchterm'} ne '')) {
 1080:             my (%curr_rules,%got_rules);
 1081:             my ($rules,$ruleorder) =
 1082:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
 1083:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
 1084:         } else {
 1085:             $inexact = 1;
 1086:         }
 1087:     }
 1088:     my ($cancreate,$noinstd);
 1089:     if ($env{'form.action'} eq 'accesslogs') {
 1090:         $noinstd = 1;
 1091:     } else {
 1092:         $cancreate =
 1093:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
 1094:     }
 1095:     my ($userpicker,$cansearch) = 
 1096:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
 1097:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
 1098:     my $srchbutton = &mt('Search');
 1099:     if ($env{'form.action'} eq 'singlestudent') {
 1100:         $srchbutton = &mt('Search and Enroll');
 1101:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1102:         $srchbutton = &mt('Search');
 1103:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
 1104:         $srchbutton = &mt('Search or Add New User');
 1105:     }
 1106:     my $output;
 1107:     if ($cansearch) {
 1108:         $output = <<"ENDBLOCK";
 1109: <form action="/adm/createuser" method="post" name="crtuser">
 1110: <input type="hidden" name="action" value="$env{'form.action'}" />
 1111: <input type="hidden" name="phase" value="get_user_info" />
 1112: $userpicker
 1113: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 1114: </form>
 1115: ENDBLOCK
 1116:     } else {
 1117:         $output = '<p>'.$userpicker.'</p>';
 1118:     }
 1119:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
 1120:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1121:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
 1122:         my $defdom=$env{'request.role.domain'};
 1123:         my ($trusted,$untrusted);
 1124:         if ($context eq 'course') {
 1125:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
 1126:         } elsif ($context eq 'author') {
 1127:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
 1128:         } elsif ($context eq 'domain') {
 1129:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
 1130:         }
 1131:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
 1132:         my %lt=&Apache::lonlocal::texthash(
 1133:                   'enro' => 'Enroll one student',
 1134:                   'enrm' => 'Enroll one member',
 1135:                   'admo' => 'Add/modify a single user',
 1136:                   'crea' => 'create new user if required',
 1137:                   'uskn' => "username is known",
 1138:                   'crnu' => 'Create a new user',
 1139:                   'usr'  => 'Username',
 1140:                   'dom'  => 'in domain',
 1141:                   'enrl' => 'Enroll',
 1142:                   'cram'  => 'Create/Modify user',
 1143:         );
 1144:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
 1145:         my ($title,$buttontext,$showresponse);
 1146:         if ($env{'form.action'} eq 'singlestudent') {
 1147:             if ($crstype eq 'Community') {
 1148:                 $title = $lt{'enrm'};
 1149:             } else {
 1150:                 $title = $lt{'enro'};
 1151:             }
 1152:             $buttontext = $lt{'enrl'};
 1153:         } else {
 1154:             $title = $lt{'admo'};
 1155:             $buttontext = $lt{'cram'};
 1156:         }
 1157:         if ($cancreate) {
 1158:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
 1159:         } else {
 1160:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
 1161:         }
 1162:         if ($env{'form.origform'} eq 'crtusername') {
 1163:             $showresponse = $responsemsg;
 1164:         }
 1165:         $output .= <<"ENDDOCUMENT";
 1166: <br />
 1167: <form action="/adm/createuser" method="post" name="crtusername">
 1168: <input type="hidden" name="action" value="$env{'form.action'}" />
 1169: <input type="hidden" name="phase" value="createnewuser" />
 1170: <input type="hidden" name="srchtype" value="exact" />
 1171: <input type="hidden" name="srchby" value="uname" />
 1172: <input type="hidden" name="srchin" value="dom" />
 1173: <input type="hidden" name="forcenewuser" value="1" />
 1174: <input type="hidden" name="origform" value="crtusername" />
 1175: <h3>$title</h3>
 1176: $showresponse
 1177: <table>
 1178:  <tr>
 1179:   <td>$lt{'usr'}:</td>
 1180:   <td><input type="text" size="15" name="srchterm" /></td>
 1181:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
 1182:   <td>&nbsp;$sellink&nbsp;</td>
 1183:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
 1184:  </tr>
 1185: </table>
 1186: </form>
 1187: ENDDOCUMENT
 1188:     }
 1189:     return $output;
 1190: }
 1191: 
 1192: sub user_modification_js {
 1193:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1194:     
 1195:     return <<END;
 1196: <script type="text/javascript" language="Javascript">
 1197: // <![CDATA[
 1198: 
 1199:     $pjump_def
 1200:     $dc_setcourse_code
 1201: 
 1202:     function dateset() {
 1203:         eval("document.cu."+document.cu.pres_marker.value+
 1204:             ".value=document.cu.pres_value.value");
 1205:         modalWindow.close();
 1206:     }
 1207: 
 1208:     $nondc_setsection_code
 1209: // ]]>
 1210: </script>
 1211: END
 1212: }
 1213: 
 1214: # =================================================================== Phase two
 1215: sub print_user_selection_page {
 1216:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1217:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1218:     my $sortby = $env{'form.sortby'};
 1219: 
 1220:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1221:         $sortby = 'lastname';
 1222:     }
 1223: 
 1224:     my ($jsback,$elements) = &crumb_utilities();
 1225: 
 1226:     my $jscript = (<<ENDSCRIPT);
 1227: <script type="text/javascript">
 1228: // <![CDATA[
 1229: function pickuser(uname,udom) {
 1230:     document.usersrchform.seluname.value=uname;
 1231:     document.usersrchform.seludom.value=udom;
 1232:     document.usersrchform.phase.value="userpicked";
 1233:     document.usersrchform.submit();
 1234: }
 1235: 
 1236: $jsback
 1237: // ]]>
 1238: </script>
 1239: ENDSCRIPT
 1240: 
 1241:     my %lt=&Apache::lonlocal::texthash(
 1242:                                        'usrch'          => "User Search to add/modify roles",
 1243:                                        'stusrch'        => "User Search to enroll student",
 1244:                                        'memsrch'        => "User Search to enroll member",
 1245:                                        'srcva'          => "Search for a user and view access log information",
 1246:                                        'usrvu'          => "User Search to view user roles",
 1247:                                        'usel'           => "Select a user to add/modify roles",
 1248:                                        'suvr'           => "Select a user to view roles",
 1249:                                        'stusel'         => "Select a user to enroll as a student",
 1250:                                        'memsel'         => "Select a user to enroll as a member",
 1251:                                        'vacsel'         => "Select a user to view access log",
 1252:                                        'username'       => "username",
 1253:                                        'domain'         => "domain",
 1254:                                        'lastname'       => "last name",
 1255:                                        'firstname'      => "first name",
 1256:                                        'permanentemail' => "permanent e-mail",
 1257:                                       );
 1258:     if ($context eq 'requestcrs') {
 1259:         $r->print('<div>');
 1260:     } else {
 1261:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1262:         my $helpitem;
 1263:         if ($env{'form.action'} eq 'singleuser') {
 1264:             $helpitem = 'Course_Change_Privileges';
 1265:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1266:             $helpitem = 'Course_Add_Student';
 1267:         } elsif ($context eq 'author') {
 1268:             $helpitem = 'Author_Change_Privileges';
 1269:         } elsif ($context eq 'domain') {
 1270:             $helpitem = 'Domain_Change_Privileges';
 1271:         }
 1272:         push (@{$brcrum},
 1273:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1274:                    text => $breadcrumb_text{'search'},
 1275:                    faq  => 282,
 1276:                    bug  => 'Instructor Interface',},
 1277:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1278:                    text => $breadcrumb_text{'userpicked'},
 1279:                    faq  => 282,
 1280:                    bug  => 'Instructor Interface',
 1281:                    help => $helpitem}
 1282:                   );
 1283:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1284:         if ($env{'form.action'} eq 'singleuser') {
 1285:             my $readonly;
 1286:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1287:                 $readonly = 1;
 1288:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1289:             } else {
 1290:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1291:             }
 1292:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1293:             if ($readonly) {
 1294:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1295:             } else {
 1296:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1297:             }
 1298:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1299:             $r->print($jscript."<b>");
 1300:             if ($crstype eq 'Community') {
 1301:                 $r->print($lt{'memsrch'});
 1302:             } else {
 1303:                 $r->print($lt{'stusrch'});
 1304:             }
 1305:             $r->print("</b><br />");
 1306:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1307:             $r->print('</form><h3>');
 1308:             if ($crstype eq 'Community') {
 1309:                 $r->print($lt{'memsel'});
 1310:             } else {
 1311:                 $r->print($lt{'stusel'});
 1312:             }
 1313:             $r->print('</h3>');
 1314:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1315:             $r->print("<b>$lt{'srcva'}</b><br />");
 1316:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1317:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1318:         }
 1319:     }
 1320:     $r->print('<form name="usersrchform" method="post" action="">'.
 1321:               &Apache::loncommon::start_data_table()."\n".
 1322:               &Apache::loncommon::start_data_table_header_row()."\n".
 1323:               ' <th> </th>'."\n");
 1324:     foreach my $field (@fields) {
 1325:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1326:                   "'".$field."'".';document.usersrchform.submit();">'.
 1327:                   $lt{$field}.'</a></th>'."\n");
 1328:     }
 1329:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1330: 
 1331:     my @sorted_users = sort {
 1332:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1333:             ||
 1334:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1335:             ||
 1336:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1337: 	    ||
 1338: 	lc($a) cmp lc($b)
 1339:         } (keys(%$srch_results));
 1340: 
 1341:     foreach my $user (@sorted_users) {
 1342:         my ($uname,$udom) = split(/:/,$user);
 1343:         my $onclick;
 1344:         if ($context eq 'requestcrs') {
 1345:             $onclick =
 1346:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1347:                                                "'$srch_results->{$user}->{firstname}',".
 1348:                                                "'$srch_results->{$user}->{lastname}',".
 1349:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1350:         } else {
 1351:             $onclick =
 1352:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1353:         }
 1354:         $r->print(&Apache::loncommon::start_data_table_row().
 1355:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1356:                   $onclick.' /></td>'.
 1357:                   '<td><tt>'.$uname.'</tt></td>'.
 1358:                   '<td><tt>'.$udom.'</tt></td>');
 1359:         foreach my $field ('lastname','firstname','permanentemail') {
 1360:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1361:         }
 1362:         $r->print(&Apache::loncommon::end_data_table_row());
 1363:     }
 1364:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1365:     if (ref($srcharray) eq 'ARRAY') {
 1366:         foreach my $item (@{$srcharray}) {
 1367:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1368:         }
 1369:     }
 1370:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1371:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1372:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1373:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1374:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1375:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1376:     if ($context eq 'requestcrs') {
 1377:         $r->print($opener_elements.'</form></div>');
 1378:     } else {
 1379:         $r->print($response.'</form>');
 1380:     }
 1381: }
 1382: 
 1383: sub print_user_query_page {
 1384:     my ($r,$caller,$brcrum) = @_;
 1385: # FIXME - this is for a network-wide name search (similar to catalog search)
 1386: # To use frames with similar behavior to catalog/portfolio search.
 1387: # To be implemented. 
 1388:     return;
 1389: }
 1390: 
 1391: sub print_user_modification_page {
 1392:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1393:         $brcrum,$showcredits) = @_;
 1394:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1395:         my $usermsg = &mt('No username and/or domain provided.');
 1396:         $env{'form.phase'} = '';
 1397: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1398:                                    $permission);
 1399:         return;
 1400:     }
 1401:     my ($form,$formname);
 1402:     if ($env{'form.action'} eq 'singlestudent') {
 1403:         $form = 'document.enrollstudent';
 1404:         $formname = 'enrollstudent';
 1405:     } else {
 1406:         $form = 'document.cu';
 1407:         $formname = 'cu';
 1408:     }
 1409:     my %abv_auth = &auth_abbrev();
 1410:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1411:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1412:     if ($uhome eq 'no_host') {
 1413:         my $usertype;
 1414:         my ($rules,$ruleorder) =
 1415:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1416:             $usertype =
 1417:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1418:                                                       \%curr_rules,\%got_rules);
 1419:         my $cancreate =
 1420:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1421:                                                    $usertype);
 1422:         if (!$cancreate) {
 1423:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1424:             my %usertypetext = (
 1425:                 official   => 'institutional',
 1426:                 unofficial => 'non-institutional',
 1427:             );
 1428:             my $response;
 1429:             if ($env{'form.origform'} eq 'crtusername') {
 1430:                 $response = '<span class="LC_warning">'.
 1431:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1432:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1433:                             '</span><br />';
 1434:             }
 1435:             $response .= '<p class="LC_warning">'
 1436:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1437:                         .' ';
 1438:             if ($context eq 'domain') {
 1439:                 $response .= &mt('Please contact a [_1] for assistance.',
 1440:                                  &Apache::lonnet::plaintext('dc'));
 1441:             } else {
 1442:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1443:                                 ,'<a href="'.$helplink.'">','</a>');
 1444:             }
 1445:             $response .= '</p><br />';
 1446:             $env{'form.phase'} = '';
 1447:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1448:                                        $permission);
 1449:             return;
 1450:         }
 1451:         $newuser = 1;
 1452:         my $checkhash;
 1453:         my $checks = { 'username' => 1 };
 1454:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1455:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1456:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1457:         if (ref($alerts{'username'}) eq 'HASH') {
 1458:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1459:                 my $domdesc =
 1460:                     &Apache::lonnet::domain($ccdomain,'description');
 1461:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1462:                     my $userchkmsg;
 1463:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1464:                         $userchkmsg = 
 1465:                             &Apache::loncommon::instrule_disallow_msg('username',
 1466:                                                                  $domdesc,1).
 1467:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1468:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1469:                             'username');
 1470:                     }
 1471:                     $env{'form.phase'} = '';
 1472:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1473:                                                $permission);
 1474:                     return;
 1475:                 }
 1476:             }
 1477:         }
 1478:     } else {
 1479:         $newuser = 0;
 1480:     }
 1481:     if ($response) {
 1482:         $response = '<br />'.$response;
 1483:     }
 1484: 
 1485:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1486:     my $dc_setcourse_code = '';
 1487:     my $nondc_setsection_code = '';                                        
 1488:     my %loaditem;
 1489: 
 1490:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1491: 
 1492:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1493:                                     $crstype,$groupslist,$newuser,
 1494:                                     $formname,\%loaditem,$permission);
 1495:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1496:     my $helpitem = 'Course_Change_Privileges';
 1497:     if ($env{'form.action'} eq 'singlestudent') {
 1498:         $helpitem = 'Course_Add_Student';
 1499:     } elsif ($context eq 'author') {
 1500:         $helpitem = 'Author_Change_Privileges';
 1501:     } elsif ($context eq 'domain') {
 1502:         $helpitem = 'Domain_Change_Privileges';
 1503:         $js .= &set_custom_js();
 1504:     }
 1505:     push (@{$brcrum},
 1506:         {href => "javascript:backPage($form)",
 1507:          text => $breadcrumb_text{'search'},
 1508:          faq  => 282,
 1509:          bug  => 'Instructor Interface',});
 1510:     if ($env{'form.phase'} eq 'userpicked') {
 1511:        push(@{$brcrum},
 1512:               {href => "javascript:backPage($form,'get_user_info','select')",
 1513:                text => $breadcrumb_text{'userpicked'},
 1514:                faq  => 282,
 1515:                bug  => 'Instructor Interface',});
 1516:     }
 1517:     push(@{$brcrum},
 1518:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1519:              text => $breadcrumb_text{'modify'},
 1520:              faq  => 282,
 1521:              bug  => 'Instructor Interface',
 1522:              help => $helpitem});
 1523:     my $args = {'add_entries'           => \%loaditem,
 1524:                 'bread_crumbs'          => $brcrum,
 1525:                 'bread_crumbs_component' => 'User Management'};
 1526:     if ($env{'form.popup'}) {
 1527:         $args->{'no_nav_bar'} = 1;
 1528:     }
 1529:     if (($context eq 'domain') && ($env{'request.role.domain'} eq $ccdomain)) {
 1530:         my @toggles;
 1531:         if (&Apache::lonnet::allowed('cau',$ccdomain)) {
 1532:             my ($isadv,$isauthor) =
 1533:                 &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1534:             unless ($isauthor) {
 1535:                 push(@toggles,'requestauthor');
 1536:             }
 1537:             push(@toggles,('webdav','editors','archive'));
 1538:         }
 1539:         if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1540:             push(@toggles,('aboutme','blog','portfolio','portaccess','timezone'));
 1541:         }
 1542:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1543:             push(@toggles,('official','unofficial','community','textbook','placement','lti'));
 1544:         }
 1545:         if (@toggles) {
 1546:             my $onload;
 1547:             foreach my $item (@toggles) {
 1548:                 $onload .= "toggleCustom(document.cu,'customtext_$item','custom$item');";
 1549:             }
 1550:             $args->{'add_entries'} = {
 1551:                                        'onload' => $onload,
 1552:                                      };
 1553:         }
 1554:     }
 1555:     my $start_page =
 1556:         &Apache::loncommon::start_page('User Management',$js,$args);
 1557: 
 1558:     my $forminfo =<<"ENDFORMINFO";
 1559: <form action="/adm/createuser" method="post" name="$formname">
 1560: <input type="hidden" name="phase" value="update_user_data" />
 1561: <input type="hidden" name="ccuname" value="$ccuname" />
 1562: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1563: <input type="hidden" name="pres_value"  value="" />
 1564: <input type="hidden" name="pres_type"   value="" />
 1565: <input type="hidden" name="pres_marker" value="" />
 1566: ENDFORMINFO
 1567:     my (%inccourses,$roledom,$defaultcredits);
 1568:     if ($context eq 'course') {
 1569:         $inccourses{$env{'request.course.id'}}=1;
 1570:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1571:         if ($showcredits) {
 1572:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1573:         }
 1574:     } elsif ($context eq 'author') {
 1575:         $roledom = $env{'request.role.domain'};
 1576:     } elsif ($context eq 'domain') {
 1577:         foreach my $key (keys(%env)) {
 1578:             $roledom = $env{'request.role.domain'};
 1579:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1580:                 $inccourses{$1.'_'.$2}=1;
 1581:             }
 1582:         }
 1583:     } else {
 1584:         foreach my $key (keys(%env)) {
 1585: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1586: 	        $inccourses{$1.'_'.$2}=1;
 1587:             }
 1588:         }
 1589:     }
 1590:     my $title = '';
 1591:     my $need_quota_js;
 1592:     if ($newuser) {
 1593:         my ($portfolioform,$domroleform);
 1594:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1595:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1596:             # Current user has quota or user tools modification privileges
 1597:             $portfolioform = '<br /><h3>'.
 1598:                              &mt('User Tools').
 1599:                              '</h3>'."\n".
 1600:                              &Apache::loncommon::start_data_table();
 1601:             if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1602:                 $portfolioform .= &build_tools_display($ccuname,$ccdomain,'tools');
 1603:             }
 1604:             if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1605:                 $portfolioform .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1606:                 $need_quota_js = 1;
 1607:             }
 1608:             $portfolioform .= &Apache::loncommon::end_data_table();
 1609:         }
 1610:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1611:             ($ccdomain eq $env{'request.role.domain'})) {
 1612:             $domroleform = &domainrole_req($ccuname,$ccdomain).
 1613:                            &authoring_defaults($ccuname,$ccdomain);
 1614:             $need_quota_js = 1;
 1615:         }
 1616:         my $readonly;
 1617:         unless ($permission->{'cusr'}) {
 1618:             $readonly = 1;
 1619:         }
 1620:         &initialize_authen_forms($ccdomain,$formname,'','',$readonly);
 1621:         my %lt=&Apache::lonlocal::texthash(
 1622:                 'lg'             => 'Login Data',
 1623:                 'hs'             => "Home Server",
 1624:         );
 1625: 	$r->print(<<ENDTITLE);
 1626: $start_page
 1627: $response
 1628: $forminfo
 1629: <script type="text/javascript" language="Javascript">
 1630: // <![CDATA[
 1631: $loginscript
 1632: // ]]>
 1633: </script>
 1634: <input type='hidden' name='makeuser' value='1' />
 1635: ENDTITLE
 1636:         if ($env{'form.action'} eq 'singlestudent') {
 1637:             if ($crstype eq 'Community') {
 1638:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1639:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1640:             } else {
 1641:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1642:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1643:             }
 1644:         } else {
 1645:                 $title = &mt('Create New User [_1] in domain [_2]',
 1646:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1647:         }
 1648:         $r->print('<h2>'.$title.'</h2>'."\n");
 1649:         $r->print('<div class="LC_left_float">');
 1650:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1651:                                          $inst_results{$ccuname.':'.$ccdomain},$readonly));
 1652:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1653:         my ($home_server_pick,$numlib) = 
 1654:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1655:                                                       'default','hide');
 1656:         if ($numlib > 1) {
 1657:             $r->print("
 1658: <br />
 1659: $lt{'hs'}: $home_server_pick
 1660: <br />");
 1661:         } else {
 1662:             $r->print($home_server_pick);
 1663:         }
 1664:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1665:             $r->print('<br /><h3>'.
 1666:                       &mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1667:                       &Apache::loncommon::start_data_table().
 1668:                       &build_tools_display($ccuname,$ccdomain,
 1669:                                            'requestcourses').
 1670:                       &Apache::loncommon::end_data_table());
 1671:         }
 1672:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1673:                   $lt{'lg'}.'</h3>');
 1674:         my ($fixedauth,$varauth,$authmsg); 
 1675:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1676:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1677:             my ($rules,$ruleorder) = 
 1678:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1679:             if (ref($rules) eq 'HASH') {
 1680:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1681:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1682:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1683:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1684:                     } else { 
 1685:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1686:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1687:                         if ($authtype =~ /^krb(4|5)$/) {
 1688:                             my $ver = $1;
 1689:                             if ($authparm ne '') {
 1690:                                 $fixedauth = <<"KERB"; 
 1691: <input type="hidden" name="login" value="krb" />
 1692: <input type="hidden" name="krbver" value="$ver" />
 1693: <input type="hidden" name="krbarg" value="$authparm" />
 1694: KERB
 1695:                             }
 1696:                         } else {
 1697:                             $fixedauth = 
 1698: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1699:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1700:                                 $fixedauth .=    
 1701: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1702:                             } else {
 1703:                                 if ($authtype eq 'int') {
 1704:                                     $varauth = '<br />'.
 1705: &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>';
 1706:                                 } elsif ($authtype eq 'loc') {
 1707:                                     $varauth = '<br />'.
 1708: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1709:                                 } else {
 1710:                                     $varauth =
 1711: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1712:                                 }
 1713:                             }
 1714:                         }
 1715:                     }
 1716:                 } else {
 1717:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1718:                 }
 1719:             }
 1720:             if ($authmsg) {
 1721:                 $r->print(<<ENDAUTH);
 1722: $fixedauth
 1723: $authmsg
 1724: $varauth
 1725: ENDAUTH
 1726:             }
 1727:         } else {
 1728:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1729:         }
 1730:         $r->print($portfolioform.$domroleform);
 1731:         if ($env{'form.action'} eq 'singlestudent') {
 1732:             $r->print(&date_sections_select($context,$newuser,$formname,
 1733:                                             $permission,$crstype,$ccuname,
 1734:                                             $ccdomain,$showcredits));
 1735:         }
 1736:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1737:     } else { # user already exists
 1738: 	$r->print($start_page.$forminfo);
 1739:         if ($env{'form.action'} eq 'singlestudent') {
 1740:             if ($crstype eq 'Community') {
 1741:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1742:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1743:             } else {
 1744:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1745:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1746:             }
 1747:         } else {
 1748:             if ($permission->{'cusr'}) {
 1749:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1750:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1751:             } else {
 1752:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1753:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1754:             }
 1755:         }
 1756:         $r->print('<h2>'.$title.'</h2>'."\n");
 1757:         $r->print('<div class="LC_left_float">');
 1758:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1759:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1760:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1761:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1762:             $r->print('<br /><h3>'.&mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1763:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1764:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1765:                 $r->print(&Apache::loncommon::start_data_table());
 1766:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1767:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1768:                 } else {
 1769:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1770:                                                       $env{'request.role.domain'}));
 1771:                 }
 1772:                 $r->print(&Apache::loncommon::end_data_table());
 1773:             } else {
 1774:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1775:                               &Apache::lonnet::domain($ccdomain,'description')));
 1776:             }
 1777:         }
 1778:         $r->print('</div>');
 1779:         my @order = ('auth','quota','tools','requestauthor','authordefaults');
 1780:         my %user_text;
 1781:         my ($isadv,$isauthor) = 
 1782:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1783:         if (((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1784:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1785:             ($env{'request.role.domain'} eq $ccdomain)) {
 1786:             if (!$isauthor) {
 1787:                 $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1788:             }
 1789:             $user_text{'authordefaults'} = &authoring_defaults($ccuname,$ccdomain);
 1790:             if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1791:                 $need_quota_js = 1;
 1792:             }
 1793:         }
 1794:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1795:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1796:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1797:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1798:             $user_text{'quota'} = '<br /><h3>'.&mt('User Tools').'</h3>'."\n".
 1799:                                   &Apache::loncommon::start_data_table();
 1800:             if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1801:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1802:                 $user_text{'quota'} .= &build_tools_display($ccuname,$ccdomain,'tools');
 1803:             }
 1804:             # Current user has quota modification privileges
 1805:             if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1806:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1807:                 $user_text{'quota'} .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1808:                 $need_quota_js = 1;
 1809:             }
 1810:             $user_text{'quota'} .= &Apache::loncommon::end_data_table();
 1811:         }
 1812:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1813:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1814:                 my %lt=&Apache::lonlocal::texthash(
 1815:                     'dska'  => "Disk quotas for user's portfolio",
 1816:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1817:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1818:                 );
 1819:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1820: <h3>$lt{'dska'}</h3>
 1821: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1822: ENDNOPORTPRIV
 1823:             }
 1824:         }
 1825:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1826:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1827:                 my %lt=&Apache::lonlocal::texthash(
 1828:                     'utav'  => "User Tools Availability",
 1829:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, Personal Information Page, or Time Zone settings for this user.",
 1830:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1831:                 );
 1832:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1833: <h3>$lt{'utav'}</h3>
 1834: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1835: ENDNOTOOLSPRIV
 1836:             }
 1837:         }
 1838:         my $gotdiv = 0; 
 1839:         foreach my $item (@order) {
 1840:             if ($user_text{$item} ne '') {
 1841:                 unless ($gotdiv) {
 1842:                     $r->print('<div class="LC_left_float">');
 1843:                     $gotdiv = 1;
 1844:                 }
 1845:                 $r->print('<br />'.$user_text{$item});
 1846:             }
 1847:         }
 1848:         if ($env{'form.action'} eq 'singlestudent') {
 1849:             unless ($gotdiv) {
 1850:                 $r->print('<div class="LC_left_float">');
 1851:             }
 1852:             my $credits;
 1853:             if ($showcredits) {
 1854:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1855:                 if ($credits eq '') {
 1856:                     $credits = $defaultcredits;
 1857:                 }
 1858:             }
 1859:             $r->print(&date_sections_select($context,$newuser,$formname,
 1860:                                             $permission,$crstype,$ccuname,
 1861:                                             $ccdomain,$showcredits));
 1862:         }
 1863:         if ($gotdiv) {
 1864:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1865:         }
 1866:         my $statuses;
 1867:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1868:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1869:             $statuses = ['active'];
 1870:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1871:                  ($env{'request.course.sec'} &&
 1872:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1873:             $statuses = ['active'];
 1874:         }
 1875:         if ($env{'form.action'} ne 'singlestudent') {
 1876:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1877:                                     $roledom,$crstype,$showcredits,$statuses);
 1878:         }
 1879:     } ## End of new user/old user logic
 1880:     if ($env{'form.action'} eq 'singlestudent') {
 1881:         my $btntxt;
 1882:         if ($crstype eq 'Community') {
 1883:             $btntxt = &mt('Enroll Member');
 1884:         } else {
 1885:             $btntxt = &mt('Enroll Student');
 1886:         }
 1887:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1888:     } elsif ($permission->{'cusr'}) {
 1889:         $r->print('<div class="LC_left_float">'.
 1890:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1891:         my $addrolesdisplay = 0;
 1892:         if ($context eq 'domain' || $context eq 'author') {
 1893:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1894:         }
 1895:         if ($context eq 'domain') {
 1896:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1897:             if (!$addrolesdisplay) {
 1898:                 $addrolesdisplay = $add_domainroles;
 1899:             }
 1900:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1901:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1902:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1903:         } elsif ($context eq 'author') {
 1904:             if ($addrolesdisplay) {
 1905:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1906:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1907:                 if ($newuser) {
 1908:                     $r->print(' onclick="auth_check()" \>'."\n");
 1909:                 } else {
 1910:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1911:                 }
 1912:             } else {
 1913:                 $r->print('</fieldset></div>'.
 1914:                           '<div class="LC_clear_float_footer"></div>'.
 1915:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1916:                           &mt('Back to previous page').'</a>');
 1917:             }
 1918:         } else {
 1919:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1920:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1921:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1922:         }
 1923:     }
 1924:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1925:     $r->print('<input type="hidden" name="currstate" value="" />');
 1926:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1927:     if ($need_quota_js) {
 1928:         $r->print(&user_quota_js());
 1929:     }
 1930:     return;
 1931: }
 1932: 
 1933: sub singleuser_breadcrumb {
 1934:     my ($crstype,$context,$domain) = @_;
 1935:     my %breadcrumb_text;
 1936:     if ($env{'form.action'} eq 'singlestudent') {
 1937:         if ($crstype eq 'Community') {
 1938:             $breadcrumb_text{'search'} = 'Enroll a member';
 1939:         } else {
 1940:             $breadcrumb_text{'search'} = 'Enroll a student';
 1941:         }
 1942:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1943:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1944:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1945:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1946:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1947:         $breadcrumb_text{'activity'} = 'Activity';
 1948:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1949:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1950:         $breadcrumb_text{'search'} = "View user's roles";
 1951:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1952:         $breadcrumb_text{'modify'} = 'User roles';
 1953:     } else {
 1954:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1955:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1956:         $breadcrumb_text{'modify'} = 'Set user role';
 1957:     }
 1958:     return %breadcrumb_text;
 1959: }
 1960: 
 1961: sub date_sections_select {
 1962:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1963:         $showcredits) = @_;
 1964:     my $credits;
 1965:     if ($showcredits) {
 1966:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1967:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1968:         if ($credits eq '') {
 1969:             $credits = $defaultcredits;
 1970:         }
 1971:     }
 1972:     my $cid = $env{'request.course.id'};
 1973:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1974:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1975:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1976:                                                   undef,$formname,$permission);
 1977:     my $rowtitle = 'Section';
 1978:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1979:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1980:                                               $permission,$context,'',$crstype,
 1981:                                               $showcredits,$credits);
 1982:     my $output = $date_table.$secbox;
 1983:     return $output;
 1984: }
 1985: 
 1986: sub validation_javascript {
 1987:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1988:         $loaditem,$permission) = @_;
 1989:     my $dc_setcourse_code = '';
 1990:     my $nondc_setsection_code = '';
 1991:     if ($context eq 'domain') {
 1992:         if ((ref($permission) eq 'HASH') && ($permission->{'cusr'})) {
 1993:             my $dcdom = $env{'request.role.domain'};
 1994:             $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1995:             $dc_setcourse_code =
 1996:                 &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1997:         }
 1998:     } else {
 1999:         my $checkauth; 
 2000:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2001:             $checkauth = 1;
 2002:         }
 2003:         if ($context eq 'course') {
 2004:             $nondc_setsection_code =
 2005:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 2006:                                                               undef,$checkauth,
 2007:                                                               $crstype);
 2008:         }
 2009:         if ($checkauth) {
 2010:             $nondc_setsection_code .= 
 2011:                 &Apache::lonuserutils::verify_authen($formname,$context);
 2012:         }
 2013:     }
 2014:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 2015:                                    $nondc_setsection_code,$groupslist);
 2016:     my ($jsback,$elements) = &crumb_utilities();
 2017:     $js .= "\n".
 2018:            '<script type="text/javascript">'."\n".
 2019:            '// <![CDATA['."\n".
 2020:            $jsback."\n".
 2021:            '// ]]>'."\n".
 2022:            '</script>'."\n";
 2023:     return $js;
 2024: }
 2025: 
 2026: sub display_existing_roles {
 2027:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 2028:         $showcredits,$statuses) = @_;
 2029:     my $now=time;
 2030:     my $showall = 1;
 2031:     my ($showexpired,$showactive);
 2032:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 2033:         $showall = 0;
 2034:         if (grep(/^expired$/,@{$statuses})) {
 2035:             $showexpired = 1;
 2036:         }
 2037:         if (grep(/^active$/,@{$statuses})) {
 2038:             $showactive = 1;
 2039:         }
 2040:         if ($showexpired && $showactive) {
 2041:             $showall = 1;
 2042:         }
 2043:     }
 2044:     my %lt=&Apache::lonlocal::texthash(
 2045:                     'rer'  => "Existing Roles",
 2046:                     'rev'  => "Revoke",
 2047:                     'del'  => "Delete",
 2048:                     'ren'  => "Re-Enable",
 2049:                     'rol'  => "Role",
 2050:                     'ext'  => "Extent",
 2051:                     'crd'  => "Credits",
 2052:                     'sta'  => "Start",
 2053:                     'end'  => "End",
 2054:                                        );
 2055:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 2056:     if ($context eq 'course' || $context eq 'author') {
 2057:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 2058:         my %roleshash = 
 2059:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 2060:                               ['active','previous','future'],\@roles,$roledom,1);
 2061:         foreach my $key (keys(%roleshash)) {
 2062:             my ($start,$end) = split(':',$roleshash{$key});
 2063:             next if ($start eq '-1' || $end eq '-1');
 2064:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 2065:             if ($context eq 'course') {
 2066:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 2067:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 2068:             } elsif ($context eq 'author') {
 2069:                 if ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2070:                     my ($audom,$auname) = ($1,$2);
 2071:                     next unless (($rnum eq $auname) && ($rdom eq $audom));
 2072:                 } else {
 2073:                     next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 2074:                 }
 2075:             }
 2076:             my ($newkey,$newvalue,$newrole);
 2077:             $newkey = '/'.$rdom.'/'.$rnum;
 2078:             if ($sec ne '') {
 2079:                 $newkey .= '/'.$sec;
 2080:             }
 2081:             $newvalue = $role;
 2082:             if ($role =~ /^cr/) {
 2083:                 $newrole = 'cr';
 2084:             } else {
 2085:                 $newrole = $role;
 2086:             }
 2087:             $newkey .= '_'.$newrole;
 2088:             if ($start ne '' && $end ne '') {
 2089:                 $newvalue .= '_'.$end.'_'.$start;
 2090:             } elsif ($end ne '') {
 2091:                 $newvalue .= '_'.$end;
 2092:             }
 2093:             $rolesdump{$newkey} = $newvalue;
 2094:         }
 2095:     } else {
 2096:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 2097:     }
 2098:     # Build up table of user roles to allow revocation and re-enabling of roles.
 2099:     my ($tmp) = keys(%rolesdump);
 2100:     return if ($tmp =~ /^(con_lost|error)/i);
 2101:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 2102:                                 my $b1=join('_',(split('_',$b))[1,0]);
 2103:                                 return $a1 cmp $b1;
 2104:                             } keys(%rolesdump)) {
 2105:         next if ($area =~ /^rolesdef/);
 2106:         my $envkey=$area;
 2107:         my $role = $rolesdump{$area};
 2108:         my $thisrole=$area;
 2109:         $area =~ s/\_\w\w$//;
 2110:         my ($role_code,$role_end_time,$role_start_time) =
 2111:             split(/_/,$role);
 2112:         my $active=1;
 2113:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 2114:         if ($active) {
 2115:             next unless($showall || $showactive);
 2116:         } else {
 2117:             next unless($showall || $showexpired);
 2118:         }
 2119: # Is this a custom role? Get role owner and title.
 2120:         my ($croleudom,$croleuname,$croletitle)=
 2121:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 2122:         my $allowed=0;
 2123:         my $delallowed=0;
 2124:         my $sortkey=$role_code;
 2125:         my $class='Unknown';
 2126:         my $credits='';
 2127:         my $csec;
 2128:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 2129:             $class='Course';
 2130:             my ($coursedom,$coursedir) = ($1,$2);
 2131:             my $cid = $1.'_'.$2;
 2132:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 2133:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 2134:             my %coursedata=
 2135:                 &Apache::lonnet::coursedescription($cid);
 2136:             if ($coursedir =~ /^$match_community$/) {
 2137:                 $class='Community';
 2138:             }
 2139:             $sortkey.="\0$coursedom";
 2140:             my $carea;
 2141:             if (defined($coursedata{'description'})) {
 2142:                 $carea=$coursedata{'description'}.
 2143:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 2144:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 2145:                 $sortkey.="\0".$coursedata{'description'};
 2146:             } else {
 2147:                 if ($class eq 'Community') {
 2148:                     $carea=&mt('Unavailable community').': '.$area;
 2149:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 2150:                 } else {
 2151:                     $carea=&mt('Unavailable course').': '.$area;
 2152:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 2153:                 }
 2154:             }
 2155:             $sortkey.="\0$coursedir";
 2156:             $inccourses->{$cid}=1;
 2157:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 2158:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 2159:                 $credits =
 2160:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 2161:                                       $coursedom,$coursedir);
 2162:                 if ($credits eq '') {
 2163:                     $credits = $defaultcredits;
 2164:                 }
 2165:             }
 2166:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 2167:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2168:                 $allowed=1;
 2169:             }
 2170:             unless ($allowed) {
 2171:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 2172:                 if ($isowner) {
 2173:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 2174:                         $allowed = 1;
 2175:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 2176:                         $allowed = 1;
 2177:                     }
 2178:                 }
 2179:             } 
 2180:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 2181:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 2182:                 $delallowed=1;
 2183:             }
 2184: # - custom role. Needs more info, too
 2185:             if ($croletitle) {
 2186:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 2187:                     $allowed=1;
 2188:                     $thisrole.='.'.$role_code;
 2189:                 }
 2190:             }
 2191:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 2192:                 $csec = $2;
 2193:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 2194:                 $sortkey.="\0$csec";
 2195:                 if (!$allowed) {
 2196:                     if ($env{'request.course.sec'} eq $csec) {
 2197:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 2198:                             $allowed = 1;
 2199:                         }
 2200:                     }
 2201:                 }
 2202:             }
 2203:             $area=$carea;
 2204:         } else {
 2205:             $sortkey.="\0".$area;
 2206:             # Determine if current user is able to revoke privileges
 2207:             if ($area=~m{^/($match_domain)/}) {
 2208:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 2209:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2210:                    $allowed=1;
 2211:                 }
 2212:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 2213:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 2214:                     ($role_code ne 'dc')) {
 2215:                     $delallowed=1;
 2216:                 }
 2217:             } else {
 2218:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 2219:                     $allowed=1;
 2220:                 }
 2221:             }
 2222:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 2223:                 $class='Authoring Space';
 2224:             } elsif ($role_code eq 'su') {
 2225:                 $class='System';
 2226:             } else {
 2227:                 $class='Domain';
 2228:             }
 2229:         }
 2230:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 2231:             $area=~m{/($match_domain)/($match_username)};
 2232:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 2233:                 $allowed=1;
 2234:             } elsif (&Apache::lonuserutils::coauthorpriv($2,$1)) {
 2235:                 $allowed=1;
 2236:             } else {
 2237:                 $allowed=0;
 2238:             }
 2239:         }
 2240:         my $row = '';
 2241:         if ($showall) {
 2242:             $row.= '<td>';
 2243:             if (($active) && ($allowed)) {
 2244:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 2245:             } else {
 2246:                 if ($active) {
 2247:                     $row.='&nbsp;';
 2248:                 } else {
 2249:                     $row.=&mt('expired or revoked');
 2250:                 }
 2251:             }
 2252:             $row.='</td><td>';
 2253:             if ($allowed && !$active) {
 2254:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 2255:             } else {
 2256:                 $row.='&nbsp;';
 2257:             }
 2258:             $row.='</td><td>';
 2259:             if ($delallowed) {
 2260:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 2261:             } else {
 2262:                 $row.='&nbsp;';
 2263:             }
 2264:             $row.= '</td>';
 2265:         }
 2266:         my $plaintext='';
 2267:         if (!$croletitle) {
 2268:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2269:             if (($showcredits) && ($credits ne '')) {
 2270:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2271:                               '<span class="LC_fontsize_small">'.
 2272:                               &mt('Credits: [_1]',$credits).
 2273:                               '</span></span>';
 2274:             }
 2275:         } else {
 2276:             $plaintext=
 2277:                 &mt('Custom role [_1][_2]defined by [_3]',
 2278:                         '"'.$croletitle.'"',
 2279:                         '<br />',
 2280:                         $croleuname.':'.$croleudom);
 2281:         }
 2282:         $row.= '<td>'.$plaintext.'</td>'.
 2283:                '<td>'.$area.'</td>'.
 2284:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2285:                                             : '&nbsp;' ).'</td>'.
 2286:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2287:                                             : '&nbsp;' ).'</td>';
 2288:         $sortrole{$sortkey}=$envkey;
 2289:         $roletext{$envkey}=$row;
 2290:         $roleclass{$envkey}=$class;
 2291:         if ($allowed) {
 2292:             $rolepriv{$envkey}='edit';
 2293:         } else {
 2294:             if ($context eq 'domain') {
 2295:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2296:                     ($envkey=~m{^/$ccdomain/})) {
 2297:                     $rolepriv{$envkey}='view';
 2298:                 }
 2299:             } elsif ($context eq 'course') {
 2300:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2301:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2302:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2303:                     $rolepriv{$envkey}='view';
 2304:                 }
 2305:             }
 2306:         }
 2307:     } # end of foreach        (table building loop)
 2308: 
 2309:     my $rolesdisplay = 0;
 2310:     my %output = ();
 2311:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2312:         $output{$type} = '';
 2313:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2314:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2315:                  $output{$type}.=
 2316:                       &Apache::loncommon::start_data_table_row().
 2317:                       $roletext{$sortrole{$which}}.
 2318:                       &Apache::loncommon::end_data_table_row();
 2319:             }
 2320:         }
 2321:         unless($output{$type} eq '') {
 2322:             $output{$type} = '<tr class="LC_info_row">'.
 2323:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2324:                       $output{$type};
 2325:             $rolesdisplay = 1;
 2326:         }
 2327:     }
 2328:     if ($rolesdisplay == 1) {
 2329:         my $contextrole='';
 2330:         if ($env{'request.course.id'}) {
 2331:             if (&Apache::loncommon::course_type() eq 'Community') {
 2332:                 $contextrole = &mt('Existing Roles in this Community');
 2333:             } else {
 2334:                 $contextrole = &mt('Existing Roles in this Course');
 2335:             }
 2336:         } elsif ($env{'request.role'} =~ /^au\./) {
 2337:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2338:         } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)/$}) {
 2339:             $contextrole = &mt('Existing Co-Author Roles in [_1] Authoring Space',
 2340:                                '<i>'.$1.'_'.$2.'</i>');
 2341:         } else {
 2342:             if ($showall) {
 2343:                 $contextrole = &mt('Existing Roles in this Domain');
 2344:             } elsif ($showactive) {
 2345:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2346:             } elsif ($showexpired) {
 2347:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2348:             }
 2349:         }
 2350:         $r->print('<div class="LC_left_float">'.
 2351: '<fieldset><legend>'.$contextrole.'</legend>'.
 2352: &Apache::loncommon::start_data_table("LC_createuser").
 2353: &Apache::loncommon::start_data_table_header_row());
 2354:         if ($showall) {
 2355:             $r->print(
 2356: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2357:             );
 2358:         } elsif ($showexpired) {
 2359:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2360:         }
 2361:         $r->print(
 2362: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2363: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2364: &Apache::loncommon::end_data_table_header_row());
 2365:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2366:             if ($output{$type}) {
 2367:                 $r->print($output{$type}."\n");
 2368:             }
 2369:         }
 2370:         $r->print(&Apache::loncommon::end_data_table().
 2371:                   '</fieldset></div>');
 2372:     }
 2373:     return;
 2374: }
 2375: 
 2376: sub new_coauthor_roles {
 2377:     my ($r,$ccuname,$ccdomain) = @_;
 2378:     my $addrolesdisplay = 0;
 2379:     #
 2380:     # Co-Author
 2381:     #
 2382:     my ($cuname,$cudom);
 2383:     if (($env{'request.role'} eq "au./$env{'user.domain'}/") ||
 2384:         ($env{'request.role'} eq "dc./$env{'user.domain'}/")) {
 2385:         $cuname=$env{'user.name'};
 2386:         $cudom=$env{'request.role.domain'};
 2387:         # No sense in assigning co-author role to yourself
 2388:         if ((&Apache::lonuserutils::authorpriv($cuname,$cudom)) &&
 2389:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2390:             $addrolesdisplay = 1;
 2391:         }
 2392:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2393:         ($cudom,$cuname) = ($1,$2);
 2394:         if ((&Apache::lonuserutils::coauthorpriv($cuname,$cudom)) &&
 2395:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain) &&
 2396:             ($cudom ne $ccdomain || $cuname ne $ccuname)) {
 2397:             $addrolesdisplay = 1;
 2398:         }
 2399:     }
 2400:     if ($addrolesdisplay) {
 2401:         my %lt=&Apache::lonlocal::texthash(
 2402:                     'cs'   => "Authoring Space",
 2403:                     'act'  => "Activate",
 2404:                     'rol'  => "Role",
 2405:                     'ext'  => "Extent",
 2406:                     'sta'  => "Start",
 2407:                     'end'  => "End",
 2408:                     'cau'  => "Co-Author",
 2409:                     'caa'  => "Assistant Co-Author",
 2410:                     'ssd'  => "Set Start Date",
 2411:                     'sed'  => "Set End Date"
 2412:                                        );
 2413:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2414:                   &Apache::loncommon::start_data_table()."\n".
 2415:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2416:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2417:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2418:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2419:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2420:                   &Apache::loncommon::start_data_table_row().'
 2421:            <td>
 2422:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2423:            </td>
 2424:            <td>'.$lt{'cau'}.'</td>
 2425:            <td>'.$cudom.'_'.$cuname.'</td>
 2426:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2427:              <a href=
 2428: "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>
 2429: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2430: <a href=
 2431: "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".
 2432:               &Apache::loncommon::end_data_table_row()."\n".
 2433:               &Apache::loncommon::start_data_table_row()."\n".
 2434: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2435: <td>'.$lt{'caa'}.'</td>
 2436: <td>'.$cudom.'_'.$cuname.'</td>
 2437: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2438: <a href=
 2439: "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>
 2440: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2441: <a href=
 2442: "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".
 2443:              &Apache::loncommon::end_data_table_row()."\n".
 2444:              &Apache::loncommon::end_data_table());
 2445:     } elsif ($env{'request.role'} =~ /^au\./) {
 2446:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2447:                                                 $env{'request.role.domain'}))) {
 2448:             $r->print('<span class="LC_error">'.
 2449:                       &mt('You do not have privileges to assign co-author roles.').
 2450:                       '</span>');
 2451:         } elsif (($env{'user.name'} eq $ccuname) &&
 2452:              ($env{'user.domain'} eq $ccdomain)) {
 2453:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2454:         }
 2455:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2456:         if (!(&Apache::lonuserutils::coauthorpriv($2,$1))) {
 2457:             $r->print('<span class="LC_error">'.
 2458:                       &mt('You do not have privileges to assign co-author roles.').
 2459:                       '</span>');
 2460:         } elsif (($env{'user.name'} eq $ccuname) &&
 2461:              ($env{'user.domain'} eq $ccdomain)) {
 2462:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in an author area in Authoring Space in which you already have a co-author role is not permitted'));
 2463:         } elsif (($cudom eq $ccdomain) && ($cuname eq $ccuname)) {
 2464:             $r->print(&mt("Assigning a co-author or assistant co-author role to an Authoring Space's author is not permitted"));
 2465:         }
 2466:     }
 2467:     return $addrolesdisplay;;
 2468: }
 2469: 
 2470: sub new_domain_roles {
 2471:     my ($r,$ccdomain) = @_;
 2472:     my $addrolesdisplay = 0;
 2473:     #
 2474:     # Domain level
 2475:     #
 2476:     my $num_domain_level = 0;
 2477:     my $domaintext =
 2478:     '<h4>'.&mt('Domain Level').'</h4>'.
 2479:     &Apache::loncommon::start_data_table().
 2480:     &Apache::loncommon::start_data_table_header_row().
 2481:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2482:     &mt('Extent').'</th>'.
 2483:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2484:     &Apache::loncommon::end_data_table_header_row();
 2485:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2486:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2487:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2488:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2489:         foreach my $role (@allroles) {
 2490:             next if ($role eq 'ad');
 2491:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2492:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2493:                if ($role eq 'dc') {
 2494:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2495:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2496:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2497:                        next unless ($uintdom eq $intdom);
 2498:                    }
 2499:                }
 2500:                my $plrole=&Apache::lonnet::plaintext($role);
 2501:                my %lt=&Apache::lonlocal::texthash(
 2502:                     'ssd'  => "Set Start Date",
 2503:                     'sed'  => "Set End Date"
 2504:                                        );
 2505:                $num_domain_level ++;
 2506:                $domaintext .=
 2507: &Apache::loncommon::start_data_table_row().
 2508: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2509: <td>'.$plrole.'</td>
 2510: <td>'.$thisdomain.'</td>
 2511: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2512: <a href=
 2513: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2514: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2515: <a href=
 2516: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2517: &Apache::loncommon::end_data_table_row();
 2518:             }
 2519:         }
 2520:     }
 2521:     $domaintext.= &Apache::loncommon::end_data_table();
 2522:     if ($num_domain_level > 0) {
 2523:         $r->print($domaintext);
 2524:         $addrolesdisplay = 1;
 2525:     }
 2526:     return $addrolesdisplay;
 2527: }
 2528: 
 2529: sub user_authentication {
 2530:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2531:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2532:     my $outcome;
 2533:     my %lt=&Apache::lonlocal::texthash(
 2534:                    'err'   => "ERROR",
 2535:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2536:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2537:                    'sldb'  => "Please specify login data below",
 2538:                    'ld'    => "Login Data"
 2539:     );
 2540:     # Check for a bad authentication type
 2541:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2542:         # bad authentication scheme
 2543:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2544:             &initialize_authen_forms($ccdomain,$formname);
 2545: 
 2546:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2547:             $outcome = <<ENDBADAUTH;
 2548: <script type="text/javascript" language="Javascript">
 2549: // <![CDATA[
 2550: $loginscript
 2551: // ]]>
 2552: </script>
 2553: <span class="LC_error">$lt{'err'}:
 2554: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2555: <h3>$lt{'ld'}</h3>
 2556: $choices
 2557: ENDBADAUTH
 2558:         } else {
 2559:             # This user is not allowed to modify the user's
 2560:             # authentication scheme, so just notify them of the problem
 2561:             $outcome = <<ENDBADAUTH;
 2562: <span class="LC_error"> $lt{'err'}: 
 2563: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2564: </span>
 2565: ENDBADAUTH
 2566:         }
 2567:     } else { # Authentication type is valid
 2568:         
 2569:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2570:         my ($authformcurrent,$can_modify,@authform_others) =
 2571:             &modify_login_block($ccdomain,$currentauth);
 2572:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2573:             # Current user has login modification privileges
 2574:             $outcome =
 2575:                        '<script type="text/javascript" language="Javascript">'."\n".
 2576:                        '// <![CDATA['."\n".
 2577:                        $loginscript."\n".
 2578:                        '// ]]>'."\n".
 2579:                        '</script>'."\n".
 2580:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2581:                        &Apache::loncommon::start_data_table().
 2582:                        &Apache::loncommon::start_data_table_row().
 2583:                        '<td>'.$authformnop;
 2584:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2585:                 $outcome .= '</td>'."\n".
 2586:                             &Apache::loncommon::end_data_table_row().
 2587:                             &Apache::loncommon::start_data_table_row().
 2588:                             '<td>'.$authformcurrent.'</td>'.
 2589:                             &Apache::loncommon::end_data_table_row()."\n";
 2590:             } else {
 2591:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2592:                             &Apache::loncommon::end_data_table_row()."\n";
 2593:             }
 2594:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2595:                 foreach my $item (@authform_others) { 
 2596:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2597:                                 '<td>'.$item.'</td>'.
 2598:                                 &Apache::loncommon::end_data_table_row()."\n";
 2599:                 }
 2600:             }
 2601:             $outcome .= &Apache::loncommon::end_data_table();
 2602:         } else {
 2603:             if (($currentauth =~ /^internal:/) &&
 2604:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2605:                 $outcome = <<"ENDJS";
 2606: <script type="text/javascript">
 2607: // <![CDATA[
 2608: function togglePwd(form) {
 2609:     if (form.newintpwd.length) {
 2610:         if (document.getElementById('LC_ownersetpwd')) {
 2611:             for (var i=0; i<form.newintpwd.length; i++) {
 2612:                 if (form.newintpwd[i].checked) {
 2613:                     if (form.newintpwd[i].value == 1) {
 2614:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2615:                     } else {
 2616:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2617:                     }
 2618:                 }
 2619:             }
 2620:         }
 2621:     }
 2622: }
 2623: // ]]>
 2624: </script>
 2625: ENDJS
 2626: 
 2627:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2628:                             &Apache::loncommon::start_data_table().
 2629:                             &Apache::loncommon::start_data_table_row().
 2630:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2631:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2632:                             &mt('No').'</label>'.('&nbsp;'x2).
 2633:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2634:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2635:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2636:                             '<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>'.
 2637:                             &Apache::loncommon::end_data_table_row().
 2638:                             &Apache::loncommon::end_data_table();
 2639:             }
 2640:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2641:                 # Current user has rights to view domain preferences for user's domain
 2642:                 my $result;
 2643:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2644:                     my ($krbver,$krbrealm) = ($1,$2);
 2645:                     if ($krbrealm eq '') {
 2646:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2647:                     } else {
 2648:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2649:                                       $krbrealm,$krbver);
 2650:                     }
 2651:                 } elsif ($currentauth =~ /^internal:/) {
 2652:                     $result = &mt('Currently internally authenticated.');
 2653:                 } elsif ($currentauth =~ /^localauth:/) {
 2654:                     $result = &mt('Currently using local (institutional) authentication.');
 2655:                 } elsif ($currentauth =~ /^unix:/) {
 2656:                     $result = &mt('Currently Filesystem Authenticated.');
 2657:                 } elsif ($currentauth =~ /^lti:/) {
 2658:                     $result = &mt('Currently LTI authenticated.');
 2659:                 }
 2660:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2661:                            &Apache::loncommon::start_data_table().
 2662:                            &Apache::loncommon::start_data_table_row().
 2663:                            '<td>'.$result.'</td>'.
 2664:                            &Apache::loncommon::end_data_table_row()."\n".
 2665:                            &Apache::loncommon::end_data_table();
 2666:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2667:                 my %lt=&Apache::lonlocal::texthash(
 2668:                            'ccld'  => "Change Current Login Data",
 2669:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2670:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2671:                 );
 2672:                 $outcome .= <<ENDNOPRIV;
 2673: <h3>$lt{'ccld'}</h3>
 2674: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2675: <input type="hidden" name="login" value="nochange" />
 2676: ENDNOPRIV
 2677:             }
 2678:         }
 2679:     }  ## End of "check for bad authentication type" logic
 2680:     return $outcome;
 2681: }
 2682: 
 2683: sub modify_login_block {
 2684:     my ($dom,$currentauth) = @_;
 2685:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2686:     my ($authnum,%can_assign) =
 2687:         &Apache::loncommon::get_assignable_auth($dom);
 2688:     my ($authformcurrent,@authform_others,$show_override_msg);
 2689:     if ($currentauth=~/^krb(4|5):/) {
 2690:         $authformcurrent=$authformkrb;
 2691:         if ($can_assign{'int'}) {
 2692:             push(@authform_others,$authformint);
 2693:         }
 2694:         if ($can_assign{'loc'}) {
 2695:             push(@authform_others,$authformloc);
 2696:         }
 2697:         if ($can_assign{'lti'}) {
 2698:             push(@authform_others,$authformlti);
 2699:         }
 2700:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2701:             $show_override_msg = 1;
 2702:         }
 2703:     } elsif ($currentauth=~/^internal:/) {
 2704:         $authformcurrent=$authformint;
 2705:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2706:             push(@authform_others,$authformkrb);
 2707:         }
 2708:         if ($can_assign{'loc'}) {
 2709:             push(@authform_others,$authformloc);
 2710:         }
 2711:         if ($can_assign{'lti'}) {
 2712:             push(@authform_others,$authformlti);
 2713:         }
 2714:         if ($can_assign{'int'}) {
 2715:             $show_override_msg = 1;
 2716:         }
 2717:     } elsif ($currentauth=~/^unix:/) {
 2718:         $authformcurrent=$authformfsys;
 2719:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2720:             push(@authform_others,$authformkrb);
 2721:         }
 2722:         if ($can_assign{'int'}) {
 2723:             push(@authform_others,$authformint);
 2724:         }
 2725:         if ($can_assign{'loc'}) {
 2726:             push(@authform_others,$authformloc);
 2727:         }
 2728:         if ($can_assign{'lti'}) {
 2729:             push(@authform_others,$authformlti);
 2730:         }
 2731:         if ($can_assign{'fsys'}) {
 2732:             $show_override_msg = 1;
 2733:         }
 2734:     } elsif ($currentauth=~/^localauth:/) {
 2735:         $authformcurrent=$authformloc;
 2736:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2737:             push(@authform_others,$authformkrb);
 2738:         }
 2739:         if ($can_assign{'int'}) {
 2740:             push(@authform_others,$authformint);
 2741:         }
 2742:         if ($can_assign{'lti'}) {
 2743:             push(@authform_others,$authformlti);
 2744:         }
 2745:         if ($can_assign{'loc'}) {
 2746:             $show_override_msg = 1;
 2747:         }
 2748:     } elsif ($currentauth=~/^lti:/) {
 2749:         $authformcurrent=$authformlti;
 2750:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2751:             push(@authform_others,$authformkrb);
 2752:         }
 2753:         if ($can_assign{'int'}) {
 2754:             push(@authform_others,$authformint);
 2755:         }
 2756:         if ($can_assign{'loc'}) {
 2757:             push(@authform_others,$authformloc);
 2758:         }
 2759:     }
 2760:     if ($show_override_msg) {
 2761:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2762:                            '</td></tr>'."\n".
 2763:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2764:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2765:                            '<td align="right"><span class="LC_cusr_emph">'.
 2766:                             &mt('will override current values').
 2767:                             '</span></td></tr></table>';
 2768:     }
 2769:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2770: }
 2771: 
 2772: sub personal_data_display {
 2773:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$readonly,$rolesarray,$now,
 2774:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2775:     my ($output,%userenv,%canmodify,%canmodify_status,$disabled);
 2776:     my @userinfo = ('firstname','middlename','lastname','generation',
 2777:                     'permanentemail','id');
 2778:     my $rowcount = 0;
 2779:     my $editable = 0;
 2780:     my %textboxsize = (
 2781:                        firstname      => '15',
 2782:                        middlename     => '15',
 2783:                        lastname       => '15',
 2784:                        generation     => '5',
 2785:                        permanentemail => '25',
 2786:                        id             => '15',
 2787:                       );
 2788: 
 2789:     my %lt=&Apache::lonlocal::texthash(
 2790:                 'pd'             => "Personal Data",
 2791:                 'firstname'      => "First Name",
 2792:                 'middlename'     => "Middle Name",
 2793:                 'lastname'       => "Last Name",
 2794:                 'generation'     => "Generation",
 2795:                 'permanentemail' => "Permanent e-mail address",
 2796:                 'id'             => "Student/Employee ID",
 2797:                 'lg'             => "Login Data",
 2798:                 'inststatus'     => "Affiliation",
 2799:                 'email'          => 'E-mail address',
 2800:                 'valid'          => 'Validation',
 2801:                 'username'       => 'Username',
 2802:     );
 2803: 
 2804:     %canmodify_status =
 2805:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2806:                                                    ['inststatus'],$rolesarray);
 2807:     if (!$newuser) {
 2808:         # Get the users information
 2809:         %userenv = &Apache::lonnet::get('environment',
 2810:                    ['firstname','middlename','lastname','generation',
 2811:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2812:         %canmodify =
 2813:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2814:                                                        \@userinfo,$rolesarray);
 2815:     } elsif ($context eq 'selfcreate') {
 2816:         if ($newuser eq 'email') {
 2817:             if (ref($emailusername) eq 'HASH') {
 2818:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2819:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2820:                     @userinfo = ();
 2821:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2822:                         foreach my $field (@{$infofields}) { 
 2823:                             if ($emailusername->{$usertype}->{$field}) {
 2824:                                 push(@userinfo,$field);
 2825:                                 $canmodify{$field} = 1;
 2826:                                 unless ($textboxsize{$field}) {
 2827:                                     $textboxsize{$field} = 25;
 2828:                                 }
 2829:                                 unless ($lt{$field}) {
 2830:                                     $lt{$field} = $infotitles->{$field};
 2831:                                 }
 2832:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2833:                                     $lt{$field} .= '<b>*</b>';
 2834:                                 }
 2835:                             }
 2836:                         }
 2837:                     }
 2838:                 }
 2839:             }
 2840:         } else {
 2841:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2842:                                                $inst_results,$rolesarray);
 2843:         }
 2844:     } elsif ($readonly) {
 2845:         $disabled = ' disabled="disabled"';
 2846:     }
 2847: 
 2848:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2849:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2850:               &Apache::lonhtmlcommon::start_pick_box();
 2851:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2852:         my $size = 25;
 2853:         if ($condition) {
 2854:             if ($condition =~ /^\@[^\@]+$/) {
 2855:                 $size = 10;
 2856:             } else {
 2857:                 undef($condition);
 2858:             }
 2859:         } 
 2860:         if ($excluded) {
 2861:             unless ($excluded =~ /^\@[^\@]+$/) {
 2862:                 undef($condition);
 2863:             }
 2864:         }
 2865:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2866:                                                      'LC_oddrow_value')."\n".
 2867:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2868:         if ($condition) {
 2869:             $output .= $condition;
 2870:         } elsif ($excluded) {
 2871:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2872:                                                                      $excluded).'</span>';
 2873:         }
 2874:         if ($usernameset eq 'first') {
 2875:             $output .= '<br /><span style="font-size: smaller">';
 2876:             if ($condition) {
 2877:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2878:                                       $condition);
 2879:             } else {
 2880:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2881:             }
 2882:             $output .= '</span>';
 2883:         }
 2884:         $rowcount ++;
 2885:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2886:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2887:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2888:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2889:                                                     'LC_pick_box_title',
 2890:                                                     'LC_oddrow_value')."\n".
 2891:                    $upassone."\n".
 2892:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2893:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2894:                                                      'LC_pick_box_title',
 2895:                                                      'LC_oddrow_value')."\n".
 2896:                    $upasstwo.
 2897:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2898:         if ($usernameset eq 'free') {
 2899:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2900:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2901:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2902:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2903:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2904:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2905:                        &mt('No').'</label></span>'."\n".
 2906:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2907:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2908:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2909:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2910:             $rowcount ++;
 2911:         }
 2912:     }
 2913:     foreach my $item (@userinfo) {
 2914:         my $rowtitle = $lt{$item};
 2915:         my $hiderow = 0;
 2916:         if ($item eq 'generation') {
 2917:             $rowtitle = $genhelp.$rowtitle;
 2918:         }
 2919:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2920:         if ($newuser) {
 2921:             if (ref($inst_results) eq 'HASH') {
 2922:                 if ($inst_results->{$item} ne '') {
 2923:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2924:                 } else {
 2925:                     if ($context eq 'selfcreate') {
 2926:                         if ($canmodify{$item}) {
 2927:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2928:                             $editable ++;
 2929:                         } else {
 2930:                             $hiderow = 1;
 2931:                         }
 2932:                     } else {
 2933:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2934:                     }
 2935:                 }
 2936:             } else {
 2937:                 if ($context eq 'selfcreate') {
 2938:                     if ($canmodify{$item}) {
 2939:                         if ($newuser eq 'email') {
 2940:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2941:                         } else {
 2942:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2943:                         }
 2944:                         $editable ++;
 2945:                     } else {
 2946:                         $hiderow = 1;
 2947:                     }
 2948:                 } else {
 2949:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2950:                 }
 2951:             }
 2952:         } else {
 2953:             if ($canmodify{$item}) {
 2954:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2955:                 if (($item eq 'id') && (!$newuser)) {
 2956:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2957:                 }
 2958:             } else {
 2959:                 $row .= $userenv{$item};
 2960:             }
 2961:         }
 2962:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2963:         if (!$hiderow) {
 2964:             $output .= $row;
 2965:             $rowcount ++;
 2966:         }
 2967:     }
 2968:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2969:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2970:         if (ref($types) eq 'ARRAY') {
 2971:             if (@{$types} > 0) {
 2972:                 my ($hiderow,$shown);
 2973:                 if ($canmodify_status{'inststatus'}) {
 2974:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2975:                 } else {
 2976:                     if ($userenv{'inststatus'} eq '') {
 2977:                         $hiderow = 1;
 2978:                     } else {
 2979:                         my @showitems;
 2980:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2981:                             if (exists($usertypes->{$item})) {
 2982:                                 push(@showitems,$usertypes->{$item});
 2983:                             } else {
 2984:                                 push(@showitems,$item);
 2985:                             }
 2986:                         }
 2987:                         if (@showitems) {
 2988:                             $shown = join(', ',@showitems);
 2989:                         } else {
 2990:                             $hiderow = 1;
 2991:                         }
 2992:                     }
 2993:                 }
 2994:                 if (!$hiderow) {
 2995:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2996:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2997:                     if ($context eq 'selfcreate') {
 2998:                         $rowcount ++;
 2999:                     }
 3000:                     $output .= $row;
 3001:                 }
 3002:             }
 3003:         }
 3004:     }
 3005:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 3006:         if ($captchaform) {
 3007:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 3008:                                                          'LC_pick_box_title')."\n".
 3009:                        $captchaform."\n".'<br /><br />'.
 3010:                        &Apache::lonhtmlcommon::row_closure(1); 
 3011:             $rowcount ++;
 3012:         }
 3013:         if ($showsubmit) {
 3014:             my $submit_text = &mt('Create account');
 3015:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 3016:                        '<br /><input type="submit" name="createaccount" value="'.
 3017:                        $submit_text.'" />';
 3018:             if ($usertype ne '') {
 3019:                 $output .= '<input type="hidden" name="type" value="'.
 3020:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 3021:             }
 3022:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 3023:         }
 3024:     }
 3025:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 3026:     if (wantarray) {
 3027:         if ($context eq 'selfcreate') {
 3028:             return($output,$rowcount,$editable);
 3029:         } else {
 3030:             return $output;
 3031:         }
 3032:     } else {
 3033:         return $output;
 3034:     }
 3035: }
 3036: 
 3037: sub pick_inst_statuses {
 3038:     my ($curr,$usertypes,$types) = @_;
 3039:     my ($output,$rem,@currtypes);
 3040:     if ($curr ne '') {
 3041:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 3042:     }
 3043:     my $numinrow = 2;
 3044:     if (ref($types) eq 'ARRAY') {
 3045:         $output = '<table>';
 3046:         my $lastcolspan; 
 3047:         for (my $i=0; $i<@{$types}; $i++) {
 3048:             if (defined($usertypes->{$types->[$i]})) {
 3049:                 my $rem = $i%($numinrow);
 3050:                 if ($rem == 0) {
 3051:                     if ($i<@{$types}-1) {
 3052:                         if ($i > 0) { 
 3053:                             $output .= '</tr>';
 3054:                         }
 3055:                         $output .= '<tr>';
 3056:                     }
 3057:                 } elsif ($i==@{$types}-1) {
 3058:                     my $colsleft = $numinrow - $rem;
 3059:                     if ($colsleft > 1) {
 3060:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 3061:                     }
 3062:                 }
 3063:                 my $check = ' ';
 3064:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 3065:                     $check = ' checked="checked" ';
 3066:                 }
 3067:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 3068:                            '<span class="LC_nobreak"><label>'.
 3069:                            '<input type="checkbox" name="inststatus" '.
 3070:                            'value="'.$types->[$i].'"'.$check.'/>'.
 3071:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 3072:             }
 3073:         }
 3074:         $output .= '</tr></table>';
 3075:     }
 3076:     return $output;
 3077: }
 3078: 
 3079: sub selfcreate_canmodify {
 3080:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 3081:     if (ref($inst_results) eq 'HASH') {
 3082:         my @inststatuses = &get_inststatuses($inst_results);
 3083:         if (@inststatuses == 0) {
 3084:             @inststatuses = ('default');
 3085:         }
 3086:         $rolesarray = \@inststatuses;
 3087:     }
 3088:     my %canmodify =
 3089:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 3090:                                                    $rolesarray);
 3091:     return %canmodify;
 3092: }
 3093: 
 3094: sub get_inststatuses {
 3095:     my ($insthashref) = @_;
 3096:     my @inststatuses = ();
 3097:     if (ref($insthashref) eq 'HASH') {
 3098:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 3099:             @inststatuses = @{$insthashref->{'inststatus'}};
 3100:         }
 3101:     }
 3102:     return @inststatuses;
 3103: }
 3104: 
 3105: # ================================================================= Phase Three
 3106: sub update_user_data {
 3107:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 3108:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 3109:                                           $env{'form.ccdomain'});
 3110:     # Error messages
 3111:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 3112:     my $end       = '</span><br /><br />';
 3113:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 3114:                     "'$env{'form.prevphase'}','modify')".'" />'.
 3115:                     &mt('Return to previous page').'</a>'.
 3116:                     &Apache::loncommon::end_page();
 3117:     my $now = time;
 3118:     my $title;
 3119:     if (exists($env{'form.makeuser'})) {
 3120: 	$title='Set Privileges for New User';
 3121:     } else {
 3122:         $title='Modify User Privileges';
 3123:     }
 3124:     my $newuser = 0;
 3125:     my ($jsback,$elements) = &crumb_utilities();
 3126:     my $jscript = '<script type="text/javascript">'."\n".
 3127:                   '// <![CDATA['."\n".
 3128:                   $jsback."\n".
 3129:                   '// ]]>'."\n".
 3130:                   '</script>'."\n";
 3131:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 3132:     push (@{$brcrum},
 3133:              {href => "javascript:backPage(document.userupdate)",
 3134:               text => $breadcrumb_text{'search'},
 3135:               faq  => 282,
 3136:               bug  => 'Instructor Interface',}
 3137:              );
 3138:     if ($env{'form.prevphase'} eq 'userpicked') {
 3139:         push(@{$brcrum},
 3140:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 3141:                 text => $breadcrumb_text{'userpicked'},
 3142:                 faq  => 282,
 3143:                 bug  => 'Instructor Interface',});
 3144:     }
 3145:     my $helpitem = 'Course_Change_Privileges';
 3146:     if ($env{'form.action'} eq 'singlestudent') {
 3147:         $helpitem = 'Course_Add_Student';
 3148:     } elsif ($context eq 'author') {
 3149:         $helpitem = 'Author_Change_Privileges';
 3150:     } elsif ($context eq 'domain') {
 3151:         $helpitem = 'Domain_Change_Privileges';
 3152:     }
 3153:     push(@{$brcrum}, 
 3154:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 3155:              text => $breadcrumb_text{'modify'},
 3156:              faq  => 282,
 3157:              bug  => 'Instructor Interface',},
 3158:             {href => "/adm/createuser",
 3159:              text => "Result",
 3160:              faq  => 282,
 3161:              bug  => 'Instructor Interface',
 3162:              help => $helpitem});
 3163:     my $args = {bread_crumbs          => $brcrum,
 3164:                 bread_crumbs_component => 'User Management'};
 3165:     if ($env{'form.popup'}) {
 3166:         $args->{'no_nav_bar'} = 1;
 3167:     }
 3168:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 3169:     $r->print(&update_result_form($uhome));
 3170:     # Check Inputs
 3171:     if (! $env{'form.ccuname'} ) {
 3172: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 3173: 	return;
 3174:     }
 3175:     if (  $env{'form.ccuname'} ne 
 3176: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 3177: 	$r->print($error.&mt('Invalid login name.').'  '.
 3178: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 3179: 		  $end.$rtnlink);
 3180: 	return;
 3181:     }
 3182:     if (! $env{'form.ccdomain'}       ) {
 3183: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 3184: 	return;
 3185:     }
 3186:     if (  $env{'form.ccdomain'} ne
 3187: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 3188: 	$r->print($error.&mt('Invalid domain name.').'  '.
 3189: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 3190: 		  $end.$rtnlink);
 3191: 	return;
 3192:     }
 3193:     if ($uhome eq 'no_host') {
 3194:         $newuser = 1;
 3195:     }
 3196:     if (! exists($env{'form.makeuser'})) {
 3197:         # Modifying an existing user, so check the validity of the name
 3198:         if ($uhome eq 'no_host') {
 3199:             $r->print(
 3200:                 $error
 3201:                .'<p class="LC_error">'
 3202:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 3203:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 3204:                .'</p>');
 3205:             return;
 3206:         }
 3207:     }
 3208:     # Determine authentication method and password for the user being modified
 3209:     my $amode='';
 3210:     my $genpwd='';
 3211:     if ($env{'form.login'} eq 'krb') {
 3212: 	$amode='krb';
 3213: 	$amode.=$env{'form.krbver'};
 3214: 	$genpwd=$env{'form.krbarg'};
 3215:     } elsif ($env{'form.login'} eq 'int') {
 3216: 	$amode='internal';
 3217: 	$genpwd=$env{'form.intarg'};
 3218:     } elsif ($env{'form.login'} eq 'fsys') {
 3219: 	$amode='unix';
 3220: 	$genpwd=$env{'form.fsysarg'};
 3221:     } elsif ($env{'form.login'} eq 'loc') {
 3222: 	$amode='localauth';
 3223: 	$genpwd=$env{'form.locarg'};
 3224: 	$genpwd=" " if (!$genpwd);
 3225:     } elsif ($env{'form.login'} eq 'lti') {
 3226:         $amode='lti';
 3227:         $genpwd=" ";
 3228:     } elsif (($env{'form.login'} eq 'nochange') ||
 3229:              ($env{'form.login'} eq ''        )) { 
 3230:         # There is no need to tell the user we did not change what they
 3231:         # did not ask us to change.
 3232:         # If they are creating a new user but have not specified login
 3233:         # information this will be caught below.
 3234:     } else {
 3235:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 3236:             return;
 3237:     }
 3238: 
 3239:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 3240:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 3241:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 3242:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 3243: 
 3244:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 3245:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3246:     my @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
 3247:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 3248:     my @requestauthor = ('requestauthor');
 3249:     my @authordefaults = ('webdav','editors','archive');
 3250:     my ($othertitle,$usertypes,$types) = 
 3251:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 3252:     my %canmodify_status =
 3253:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 3254:                                                    ['inststatus']);
 3255:     if ($env{'form.makeuser'}) {
 3256: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 3257:         # Check for the authentication mode and password
 3258:         if (! $amode || ! $genpwd) {
 3259: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 3260: 	    return;
 3261: 	}
 3262:         # Determine desired host
 3263:         my $desiredhost = $env{'form.hserver'};
 3264:         if (lc($desiredhost) eq 'default') {
 3265:             $desiredhost = undef;
 3266:         } else {
 3267:             my %home_servers = 
 3268: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 3269:             if (! exists($home_servers{$desiredhost})) {
 3270:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 3271:                 return;
 3272:             }
 3273:         }
 3274:         # Check ID format
 3275:         my %checkhash;
 3276:         my %checks = ('id' => 1);
 3277:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 3278:             'newuser' => $newuser, 
 3279:             'id' => $env{'form.cid'},
 3280:         );
 3281:         if ($env{'form.cid'} ne '') {
 3282:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 3283:                                           \%rulematch,\%inst_results,\%curr_rules);
 3284:             if (ref($alerts{'id'}) eq 'HASH') {
 3285:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3286:                     my $domdesc =
 3287:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 3288:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 3289:                         my $userchkmsg;
 3290:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 3291:                             $userchkmsg  = 
 3292:                                 &Apache::loncommon::instrule_disallow_msg('id',
 3293:                                                                     $domdesc,1).
 3294:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 3295:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 3296:                         }
 3297:                         $r->print($error.&mt('Invalid ID format').$end.
 3298:                                   $userchkmsg.$rtnlink);
 3299:                         return;
 3300:                     }
 3301:                 }
 3302:             }
 3303:         }
 3304:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 3305: 	# Call modifyuser
 3306: 	my $result = &Apache::lonnet::modifyuser
 3307: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 3308:              $amode,$genpwd,$env{'form.cfirstname'},
 3309:              $env{'form.cmiddlename'},$env{'form.clastname'},
 3310:              $env{'form.cgeneration'},undef,$desiredhost,
 3311:              $env{'form.cpermanentemail'});
 3312: 	$r->print(&mt('Generating user').': '.$result);
 3313:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 3314:                                                $env{'form.ccdomain'});
 3315:         my (%changeHash,%newcustom,%changed,%changedinfo);
 3316:         if ($uhome ne 'no_host') {
 3317:             if ($context eq 'domain') {
 3318:                 foreach my $name ('portfolio','author') {
 3319:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3320:                         if ($env{'form.'.$name.'quota'} eq '') {
 3321:                             $newcustom{$name.'quota'} = 0;
 3322:                         } else {
 3323:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 3324:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 3325:                         }
 3326:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 3327:                             $changed{$name.'quota'} = 1;
 3328:                         }
 3329:                     }
 3330:                 }
 3331:                 foreach my $item (@usertools) {
 3332:                     if ($env{'form.custom'.$item} == 1) {
 3333:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3334:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3335:                                                      \%changeHash,'tools');
 3336:                     }
 3337:                 }
 3338:                 foreach my $item (@requestcourses) {
 3339:                     if ($env{'form.custom'.$item} == 1) {
 3340:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3341:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3342:                             $newcustom{$item} .= '=';
 3343:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3344:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3345:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3346:                             }
 3347:                         }
 3348:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3349:                                                       \%changeHash,'requestcourses');
 3350:                     }
 3351:                 }
 3352:                 if ($env{'form.customrequestauthor'} == 1) {
 3353:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3354:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3355:                                                     $newcustom{'requestauthor'},
 3356:                                                     \%changeHash,'requestauthor');
 3357:                 }
 3358:                 if ($env{'form.customeditors'} == 1) {
 3359:                     my @editors;
 3360:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 3361:                     if (@posseditors) {
 3362:                         foreach my $editor (@posseditors) {
 3363:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 3364:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 3365:                                     push(@editors,$editor);
 3366:                                 }
 3367:                             }
 3368:                         }
 3369:                     }
 3370:                     if (@editors) {
 3371:                         @editors = sort(@editors);
 3372:                         $changed{'editors'} = &tool_admin('editors',join(',',@editors),
 3373:                                                           \%changeHash,'authordefaults');
 3374:                     }
 3375:                 }
 3376:                 if ($env{'form.customwebdav'} == 1) {
 3377:                     $newcustom{'webdav'} = $env{'form.authordefaults_webdav'};
 3378:                     $changed{'webdav'} = &tool_admin('webdav',$newcustom{'webdav'},
 3379:                                                      \%changeHash,'authordefaults');
 3380:                 }
 3381:                 if ($env{'form.customarchive'} == 1) {
 3382:                     $newcustom{'archive'} = $env{'form.authordefaults_archive'};
 3383:                     $changed{'archive'} = &tool_admin('archive',$newcustom{'archive'},
 3384:                                                       \%changeHash,'authordefaults');
 3385: 
 3386:                 }
 3387:             }
 3388:             if ($canmodify_status{'inststatus'}) {
 3389:                 if (exists($env{'form.inststatus'})) {
 3390:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3391:                     if (@inststatuses > 0) {
 3392:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3393:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3394:                     }
 3395:                 }
 3396:             }
 3397:             if (keys(%changed)) {
 3398:                 foreach my $item (@userinfo) {
 3399:                     $changeHash{$item}  = $env{'form.c'.$item};
 3400:                 }
 3401:                 my $chgresult =
 3402:                      &Apache::lonnet::put('environment',\%changeHash,
 3403:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3404:             }
 3405:         }
 3406:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3407:                   &Apache::lonnet::hostname($uhome));
 3408:     } elsif (($env{'form.login'} ne 'nochange') &&
 3409:              ($env{'form.login'} ne ''        )) {
 3410: 	# Modify user privileges
 3411:         if (! $amode || ! $genpwd) {
 3412: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3413: 	    return;
 3414: 	}
 3415: 	# Only allow authentication modification if the person has authority
 3416: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3417: 	    $r->print('Modifying authentication: '.
 3418:                       &Apache::lonnet::modifyuserauth(
 3419: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3420:                        $amode,$genpwd));
 3421:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3422: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3423: 	} else {
 3424: 	    # Okay, this is a non-fatal error.
 3425: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3426: 	}
 3427:     } elsif (($env{'form.intarg'} ne '') &&
 3428:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3429:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3430:         $r->print('Modifying authentication: '.
 3431:                   &Apache::lonnet::modifyuserauth(
 3432:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3433:                   'internal',$env{'form.intarg'}));
 3434:     }
 3435:     $r->rflush(); # Finish display of header before time consuming actions start
 3436:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3437:     ##
 3438:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3439:     if ($context eq 'course') {
 3440:         ($cnum,$cdom) =
 3441:             &Apache::lonuserutils::get_course_identity();
 3442:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3443:         if ($showcredits) {
 3444:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3445:         }
 3446:     }
 3447:     if (! $env{'form.makeuser'} ) {
 3448:         # Check for need to change
 3449:         my %userenv = &Apache::lonnet::get
 3450:             ('environment',['firstname','middlename','lastname','generation',
 3451:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3452:              'tools.aboutme','tools.blog','tools.webdav',
 3453:              'tools.portfolio','tools.timezone','tools.portaccess',
 3454:              'authormanagers','authoreditors','authorarchive','requestauthor',
 3455:              'requestcourses.official','requestcourses.unofficial',
 3456:              'requestcourses.community','requestcourses.textbook',
 3457:              'requestcourses.placement','requestcourses.lti',
 3458:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3459:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3460:              'reqcrsotherdom.placement','domcoord.author'],
 3461:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3462:         my ($tmp) = keys(%userenv);
 3463:         if ($tmp =~ /^(con_lost|error)/i) { 
 3464:             %userenv = ();
 3465:         }
 3466:         unless (($userenv{'domcoord.author'} eq 'blocked') &&
 3467:                 (($env{'user.name'} ne $env{'form.ccuname'}) ||
 3468:                  ($env{'user.domain'} ne $env{'form.ccdomain'}))) {
 3469:             push(@authordefaults,'managers');
 3470:         }
 3471:         my $no_forceid_alert;
 3472:         # Check to see if user information can be changed
 3473:         my %domconfig =
 3474:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3475:                                      $env{'form.ccdomain'});
 3476:         my @statuses = ('active','future');
 3477:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3478:         my ($auname,$audom);
 3479:         if ($context eq 'author') {
 3480:             $auname = $env{'user.name'};
 3481:             $audom = $env{'user.domain'};     
 3482:         }
 3483:         foreach my $item (keys(%roles)) {
 3484:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3485:             if ($context eq 'course') {
 3486:                 if ($cnum ne '' && $cdom ne '') {
 3487:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3488:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3489:                             push(@userroles,$role);
 3490:                         }
 3491:                     }
 3492:                 }
 3493:             } elsif ($context eq 'author') {
 3494:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3495:                     if (!grep(/^\Q$role\E$/,@userroles)) {
 3496:                         push(@userroles,$role);
 3497:                     }
 3498:                 }
 3499:             }
 3500:         }
 3501:         if ($env{'form.action'} eq 'singlestudent') {
 3502:             if (!grep(/^st$/,@userroles)) {
 3503:                 push(@userroles,'st');
 3504:             }
 3505:         } else {
 3506:             # Check for course or co-author roles being activated or re-enabled
 3507:             if ($context eq 'author' || $context eq 'course') {
 3508:                 foreach my $key (keys(%env)) {
 3509:                     if ($context eq 'author') {
 3510:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3511:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3512:                                 push(@userroles,$1);
 3513:                             }
 3514:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3515:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3516:                                 push(@userroles,$1);
 3517:                             }
 3518:                         }
 3519:                     } elsif ($context eq 'course') {
 3520:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3521:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3522:                                 push(@userroles,$1);
 3523:                             }
 3524:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3525:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3526:                                 push(@userroles,$1);
 3527:                             }
 3528:                         }
 3529:                     }
 3530:                 }
 3531:             }
 3532:         }
 3533:         #Check to see if we can change personal data for the user 
 3534:         my (@mod_disallowed,@longroles);
 3535:         foreach my $role (@userroles) {
 3536:             if ($role eq 'cr') {
 3537:                 push(@longroles,'Custom');
 3538:             } else {
 3539:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3540:             }
 3541:         }
 3542:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3543:         foreach my $item (@userinfo) {
 3544:             # Strip leading and trailing whitespace
 3545:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3546:             if (!$canmodify{$item}) {
 3547:                 if (defined($env{'form.c'.$item})) {
 3548:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3549:                         push(@mod_disallowed,$item);
 3550:                     }
 3551:                 }
 3552:                 $env{'form.c'.$item} = $userenv{$item};
 3553:             }
 3554:         }
 3555:         # Check to see if we can change the Student/Employee ID
 3556:         my $forceid = $env{'form.forceid'};
 3557:         my $recurseid = $env{'form.recurseid'};
 3558:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3559:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3560:                                             $env{'form.ccuname'});
 3561:         if (($uidhash{$env{'form.ccuname'}}) && 
 3562:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3563:             (!$forceid)) {
 3564:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3565:                 $env{'form.cid'} = $userenv{'id'};
 3566:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3567:                                    .'<br />'
 3568:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3569:                                    .'<br />'."\n";
 3570:             }
 3571:         }
 3572:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3573:             my $checkhash;
 3574:             my $checks = { 'id' => 1 };
 3575:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3576:                    { 'newuser' => $newuser,
 3577:                      'id'  => $env{'form.cid'}, 
 3578:                    };
 3579:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3580:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3581:             if (ref($alerts{'id'}) eq 'HASH') {
 3582:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3583:                    $env{'form.cid'} = $userenv{'id'};
 3584:                 }
 3585:             }
 3586:         }
 3587:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3588:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3589:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3590:             %oldsettingstatus,%newsettingstatus);
 3591:         @disporder = ('inststatus');
 3592:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3593:             push(@disporder,('requestcourses','requestauthor','authordefaults'));
 3594:         } else {
 3595:             push(@disporder,'reqcrsotherdom');
 3596:         }
 3597:         push(@disporder,('quota','tools'));
 3598:         $oldinststatus = $userenv{'inststatus'};
 3599:         foreach my $name ('portfolio','author') {
 3600:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3601:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3602:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3603:         }
 3604:         my %canshow;
 3605:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3606:             $canshow{'quota'} = 1;
 3607:         }
 3608:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3609:             $canshow{'tools'} = 1;
 3610:         }
 3611:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3612:             $canshow{'requestcourses'} = 1;
 3613:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3614:             $canshow{'reqcrsotherdom'} = 1;
 3615:         }
 3616:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3617:             $canshow{'inststatus'} = 1;
 3618:         }
 3619:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3620:             $canshow{'requestauthor'} = 1;
 3621:             $canshow{'authordefaults'} = 1;
 3622:         }
 3623:         my (%changeHash,%changed);
 3624:         if ($oldinststatus eq '') {
 3625:             $oldsettings{'inststatus'} = $othertitle; 
 3626:         } else {
 3627:             if (ref($usertypes) eq 'HASH') {
 3628:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3629:             } else {
 3630:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3631:             }
 3632:         }
 3633:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3634:         if ($canmodify_status{'inststatus'}) {
 3635:             $canshow{'inststatus'} = 1;
 3636:             if (exists($env{'form.inststatus'})) {
 3637:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3638:                 if (@inststatuses > 0) {
 3639:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3640:                     $changeHash{'inststatus'} = $newinststatus;
 3641:                     if ($newinststatus ne $oldinststatus) {
 3642:                         $changed{'inststatus'} = $newinststatus;
 3643:                         foreach my $name ('portfolio','author') {
 3644:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3645:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3646:                         }
 3647:                     }
 3648:                     if (ref($usertypes) eq 'HASH') {
 3649:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3650:                     } else {
 3651:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3652:                     }
 3653:                 }
 3654:             } else {
 3655:                 $newinststatus = '';
 3656:                 $changeHash{'inststatus'} = $newinststatus;
 3657:                 $newsettings{'inststatus'} = $othertitle;
 3658:                 if ($newinststatus ne $oldinststatus) {
 3659:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3660:                     foreach my $name ('portfolio','author') {
 3661:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3662:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3663:                     }
 3664:                 }
 3665:             }
 3666:         } elsif ($context ne 'selfcreate') {
 3667:             $canshow{'inststatus'} = 1;
 3668:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3669:         }
 3670:         foreach my $name ('portfolio','author') {
 3671:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3672:         }
 3673:         if ($context eq 'domain') {
 3674:             foreach my $name ('portfolio','author') {
 3675:                 if ($userenv{$name.'quota'} ne '') {
 3676:                     $oldquota{$name} = $userenv{$name.'quota'};
 3677:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3678:                         if ($env{'form.'.$name.'quota'} eq '') {
 3679:                             $newquota{$name} = 0;
 3680:                         } else {
 3681:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3682:                             $newquota{$name} =~ s/[^\d\.]//g;
 3683:                         }
 3684:                         if ($newquota{$name} != $oldquota{$name}) {
 3685:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3686:                                 $changed{$name.'quota'} = 1;
 3687:                             }
 3688:                         }
 3689:                     } else {
 3690:                         if (&quota_admin('',\%changeHash,$name)) {
 3691:                             $changed{$name.'quota'} = 1;
 3692:                             $newquota{$name} = $newdefquota{$name};
 3693:                             $newisdefault{$name} = 1;
 3694:                         }
 3695:                     }
 3696:                 } else {
 3697:                     $oldisdefault{$name} = 1;
 3698:                     $oldquota{$name} = $olddefquota{$name};
 3699:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3700:                         if ($env{'form.'.$name.'quota'} eq '') {
 3701:                             $newquota{$name} = 0;
 3702:                         } else {
 3703:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3704:                             $newquota{$name} =~ s/[^\d\.]//g;
 3705:                         }
 3706:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3707:                             $changed{$name.'quota'} = 1;
 3708:                         }
 3709:                     } else {
 3710:                         $newquota{$name} = $newdefquota{$name};
 3711:                         $newisdefault{$name} = 1;
 3712:                     }
 3713:                 }
 3714:                 if ($oldisdefault{$name}) {
 3715:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3716:                 }  else {
 3717:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3718:                 }
 3719:                 if ($newisdefault{$name}) {
 3720:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3721:                 } else {
 3722:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3723:                 }
 3724:             }
 3725:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3726:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3727:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3728:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3729:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3730:                 my ($isadv,$isauthor) =
 3731:                     &Apache::lonnet::is_advanced_user($env{'form.ccdomain'},$env{'form.ccuname'});
 3732:                 unless ($isauthor) {
 3733:                     &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3734:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3735:                 }
 3736:                 &tool_changes('authordefaults',\@authordefaults,\%oldsettings,\%oldsettingstext,
 3737:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3738:             } else {
 3739:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3740:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3741:             }
 3742:         }
 3743:         foreach my $item (@userinfo) {
 3744:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3745:                 $namechanged{$item} = 1;
 3746:             }
 3747:         }
 3748:         foreach my $name ('portfolio','author') {
 3749:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3750:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3751:         }
 3752:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3753:             my ($chgresult,$namechgresult);
 3754:             if (keys(%changed) > 0) {
 3755:                 $chgresult =
 3756:                     &Apache::lonnet::put('environment',\%changeHash,
 3757:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3758:                 if ($chgresult eq 'ok') {
 3759:                     my ($ca_mgr_del,%ca_mgr_add);
 3760:                     if ($changed{'managers'}) {
 3761:                         my (@adds,@dels);
 3762:                         if ($changeHash{'authormanagers'} eq '') {
 3763:                             @dels = split(/,/,$userenv{'authormanagers'});
 3764:                         } elsif ($userenv{'authormanagers'} eq '') {
 3765:                             @adds = split(/,/,$changeHash{'authormanagers'});
 3766:                         } else {
 3767:                             my @old = split(/,/,$userenv{'authormanagers'});
 3768:                             my @new = split(/,/,$changeHash{'authormanagers'});
 3769:                             my @diffs = &Apache::loncommon::compare_arrays(\@old,\@new);
 3770:                             if (@diffs) {
 3771:                                 foreach my $user (@diffs) {
 3772:                                     if (grep(/^\Q$user\E$/,@old)) {
 3773:                                         push(@dels,$user);
 3774:                                     } elsif (grep(/^\Q$user\E$/,@new)) {
 3775:                                         push(@adds,$user);
 3776:                                     }
 3777:                                 }
 3778:                             }
 3779:                         }
 3780:                         my $key = "internal.manager./$env{'form.ccdomain'}/$env{'form.ccuname'}";
 3781:                         if (@dels) {
 3782:                             foreach my $user (@dels) {
 3783:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3784:                                     &Apache::lonnet::del('environment',[$key],$2,$1);
 3785:                                 }
 3786:                             }
 3787:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3788:                             if (grep(/^\Q$curruser\E$/,@dels)) {
 3789:                                 $ca_mgr_del = $key;
 3790:                             }
 3791:                         }
 3792:                         if (@adds) {
 3793:                             foreach my $user (@adds) {
 3794:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3795:                                     &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 3796:                                 }
 3797:                             }
 3798:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3799:                             if (grep(/^\Q$curruser\E$/,@adds)) {
 3800:                                 $ca_mgr_add{$key} = 1;
 3801:                             }
 3802:                         }
 3803:                     }
 3804:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3805:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3806:                         my (%newenvhash,$got_domdefs,%domdefaults,$got_userenv,
 3807:                             %userenv);
 3808:                         my @fromenv = keys(%changed);
 3809:                         push(@fromenv,'inststatus');
 3810:                         foreach my $key (keys(%changed)) {
 3811:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3812:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3813:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3814:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3815:                                     $changeHash{'requestcourses.'.$key};
 3816:                                 if ($changeHash{'requestcourses.'.$key}) {
 3817:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3818:                                 } else {
 3819:                                     unless ($got_domdefs) {
 3820:                                         %domdefaults =
 3821:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3822:                                         $got_domdefs = 1;
 3823:                                     }
 3824:                                     unless ($got_userenv) {
 3825:                                         %userenv =
 3826:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3827:                                                                              $env{'user.name'},@fromenv);
 3828:                                         $got_userenv = 1;
 3829:                                     }
 3830:                                     $newenvhash{'environment.canrequest.'.$key} =
 3831:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3832:                                             $key,'reload','requestcourses',\%userenv,\%domdefaults);
 3833:                                 }
 3834:                             } elsif ($key eq 'requestauthor') {
 3835:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3836:                                 if ($changeHash{$key}) {
 3837:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3838:                                 } else {
 3839:                                     unless ($got_domdefs) {
 3840:                                         %domdefaults =
 3841:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3842:                                         $got_domdefs = 1;
 3843:                                     }
 3844:                                     unless ($got_userenv) {
 3845:                                         %userenv =
 3846:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3847:                                                                              $env{'user.name'},@fromenv);
 3848:                                         $got_userenv = 1;
 3849:                                     }
 3850:                                     $newenvhash{'environment.canrequest.author'} =
 3851:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3852:                                             $key,'reload','requestauthor',\%userenv,\%domdefaults);
 3853:                                 }
 3854:                             } elsif ($key eq 'editors') {
 3855:                                 $newenvhash{'environment.author'.$key} = $changeHash{'author'.$key};
 3856:                                 if ($env{'form.customeditors'}) {
 3857:                                     $newenvhash{'environment.editors'} = $changeHash{'author'.$key};
 3858:                                 } else {
 3859:                                     unless ($got_domdefs) {
 3860:                                         %domdefaults =
 3861:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3862:                                         $got_domdefs = 1;
 3863:                                     }
 3864:                                     if ($domdefaults{'editors'} ne '') {
 3865:                                         $newenvhash{'environment.editors'} = $domdefaults{'editors'};
 3866:                                     } else {
 3867:                                         $newenvhash{'environment.editors'} = 'edit,xml';
 3868:                                     }
 3869:                                 }
 3870:                             } elsif ($key eq 'archive') {
 3871:                                 $newenvhash{'environment.author.'.$key} =
 3872:                                     $changeHash{'author.'.$key};
 3873:                                 if ($changeHash{'author.'.$key} ne '') {
 3874:                                     $newenvhash{'environment.canarchive'} =
 3875:                                         $changeHash{'author.'.$key};
 3876:                                 } else {
 3877:                                     unless ($got_domdefs) {
 3878:                                         %domdefaults =
 3879:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3880:                                         $got_domdefs = 1;
 3881:                                     }
 3882:                                     $newenvhash{'environment.canarchive'} =
 3883:                                         $domdefaults{'archive'};
 3884:                                 }
 3885:                             } elsif ($key ne 'quota') {
 3886:                                 $newenvhash{'environment.tools.'.$key} = 
 3887:                                     $changeHash{'tools.'.$key};
 3888:                                 if ($changeHash{'tools.'.$key} ne '') {
 3889:                                     $newenvhash{'environment.availabletools.'.$key} =
 3890:                                         $changeHash{'tools.'.$key};
 3891:                                 } else {
 3892:                                     unless ($got_domdefs) {
 3893:                                         %domdefaults =
 3894:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3895:                                         $got_domdefs = 1;
 3896:                                     }
 3897:                                     unless ($got_userenv) {
 3898:                                         %userenv =
 3899:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3900:                                                                              $env{'user.name'},@fromenv);
 3901:                                         $got_userenv = 1;
 3902:                                     }
 3903:                                     $newenvhash{'environment.availabletools.'.$key} =
 3904:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3905:                                             $key,'reload','tools',\%userenv,\%domdefaults);
 3906:                                 }
 3907:                             }
 3908:                         }
 3909:                         if (keys(%newenvhash)) {
 3910:                             &Apache::lonnet::appenv(\%newenvhash);
 3911:                         }
 3912:                     } else {
 3913:                         if ($ca_mgr_del) {
 3914:                             &Apache::lonnet::delenv($ca_mgr_del);
 3915:                         }
 3916:                         if (keys(%ca_mgr_add)) {
 3917:                             &Apache::lonnet::appenv(\%ca_mgr_add);
 3918:                         }
 3919:                     }
 3920:                     if ($changed{'aboutme'}) {
 3921:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3922:                                                                      $env{'form.ccdomain'});
 3923:                     }
 3924:                 }
 3925:             }
 3926:             if (keys(%namechanged) > 0) {
 3927:                 foreach my $field (@userinfo) {
 3928:                     $changeHash{$field}  = $env{'form.c'.$field};
 3929:                 }
 3930: # Make the change
 3931:                 $namechgresult =
 3932:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3933:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3934:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3935:                         $changeHash{'lastname'},$changeHash{'generation'},
 3936:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3937:                 %userupdate = (
 3938:                                lastname   => $env{'form.clastname'},
 3939:                                middlename => $env{'form.cmiddlename'},
 3940:                                firstname  => $env{'form.cfirstname'},
 3941:                                generation => $env{'form.cgeneration'},
 3942:                                id         => $env{'form.cid'},
 3943:                              );
 3944:             }
 3945:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3946:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3947:             # Tell the user we changed the name
 3948:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3949:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3950:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3951:                                   \%newsettingstext);
 3952:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3953:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3954:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3955:                     if (($recurseid) &&
 3956:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3957:                         my $idresult = 
 3958:                             &Apache::lonuserutils::propagate_id_change(
 3959:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3960:                                 \%userupdate);
 3961:                         $r->print('<br />'.$idresult.'<br />');
 3962:                     }
 3963:                 }
 3964:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3965:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3966:                     my %newenvhash;
 3967:                     foreach my $key (keys(%changeHash)) {
 3968:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3969:                     }
 3970:                     &Apache::lonnet::appenv(\%newenvhash);
 3971:                 }
 3972:             } else { # error occurred
 3973:                 $r->print(
 3974:                     '<p class="LC_error">'
 3975:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3976:                             '"'.$env{'form.ccuname'}.'"',
 3977:                             '"'.$env{'form.ccdomain'}.'"')
 3978:                    .'</p>');
 3979:             }
 3980:         } else { # End of if ($env ... ) logic
 3981:             # They did not want to change the users name, quota, tool availability,
 3982:             # or ability to request creation of courses, 
 3983:             # but we can still tell them what the name and quota and availabilities are  
 3984:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3985:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3986:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3987:         }
 3988:         if (@mod_disallowed) {
 3989:             my ($rolestr,$contextname);
 3990:             if (@longroles > 0) {
 3991:                 $rolestr = join(', ',@longroles);
 3992:             } else {
 3993:                 $rolestr = &mt('No roles');
 3994:             }
 3995:             if ($context eq 'course') {
 3996:                 $contextname = 'course';
 3997:             } elsif ($context eq 'author') {
 3998:                 $contextname = 'co-author';
 3999:             }
 4000:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 4001:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4002:             foreach my $field (@mod_disallowed) {
 4003:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 4004:             }
 4005:             $r->print('</ul>');
 4006:             if (@mod_disallowed == 1) {
 4007:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 4008:             } else {
 4009:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 4010:             }
 4011:             my $helplink = 'javascript:helpMenu('."'display'".')';
 4012:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 4013:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 4014:                          ,'<a href="'.$helplink.'">','</a>')
 4015:                       .'<br />');
 4016:         }
 4017:         $r->print('<span class="LC_warning">'
 4018:                   .$no_forceid_alert
 4019:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 4020:                   .'</span>');
 4021:     }
 4022:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 4023:     if ($env{'form.action'} eq 'singlestudent') {
 4024:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 4025:                                $crstype,$showcredits,$defaultcredits);
 4026:         my $linktext = ($crstype eq 'Community' ?
 4027:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 4028:         $r->print(
 4029:             &Apache::lonhtmlcommon::actionbox([
 4030:                 '<a href="javascript:backPage(document.userupdate)">'
 4031:                .($crstype eq 'Community' ? 
 4032:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 4033:                .'</a>']));
 4034:     } else {
 4035:         my @rolechanges = &update_roles($r,$context,$showcredits);
 4036:         if (keys(%namechanged) > 0) {
 4037:             if ($context eq 'course') {
 4038:                 if (@userroles > 0) {
 4039:                     if ((@rolechanges == 0) || 
 4040:                         (!(grep(/^st$/,@rolechanges)))) {
 4041:                         if (grep(/^st$/,@userroles)) {
 4042:                             my $classlistupdated =
 4043:                                 &Apache::lonuserutils::update_classlist($cdom,
 4044:                                               $cnum,$env{'form.ccdomain'},
 4045:                                        $env{'form.ccuname'},\%userupdate);
 4046:                         }
 4047:                     }
 4048:                 }
 4049:             }
 4050:         }
 4051:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 4052:                                                      $env{'form.ccdomain'});
 4053:         if ($env{'form.popup'}) {
 4054:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 4055:         } else {
 4056:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 4057:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 4058:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 4059:         }
 4060:     }
 4061: }
 4062: 
 4063: sub display_userinfo {
 4064:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 4065:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 4066:         $newsetting,$newsettingtext) = @_;
 4067:     return unless (ref($order) eq 'ARRAY' &&
 4068:                    ref($canshow) eq 'HASH' && 
 4069:                    ref($requestcourses) eq 'ARRAY' && 
 4070:                    ref($requestauthor) eq 'ARRAY' &&
 4071:                    ref($usertools) eq 'ARRAY' && 
 4072:                    ref($userenv) eq 'HASH' &&
 4073:                    ref($changedhash) eq 'HASH' &&
 4074:                    ref($oldsetting) eq 'HASH' &&
 4075:                    ref($oldsettingtext) eq 'HASH' &&
 4076:                    ref($newsetting) eq 'HASH' &&
 4077:                    ref($newsettingtext) eq 'HASH');
 4078:     my %lt=&Apache::lonlocal::texthash(
 4079:          'ui'             => 'User Information',
 4080:          'uic'            => 'User Information Changed',
 4081:          'firstname'      => 'First Name',
 4082:          'middlename'     => 'Middle Name',
 4083:          'lastname'       => 'Last Name',
 4084:          'generation'     => 'Generation',
 4085:          'id'             => 'Student/Employee ID',
 4086:          'permanentemail' => 'Permanent e-mail address',
 4087:          'portfolioquota' => 'Disk space allocated to portfolio files',
 4088:          'authorquota'    => 'Disk space allocated to Authoring Space',
 4089:          'blog'           => 'Blog Availability',
 4090:          'webdav'         => 'WebDAV Availability',
 4091:          'aboutme'        => 'Personal Information Page Availability',
 4092:          'portfolio'      => 'Portfolio Availability',
 4093:          'portaccess'     => 'Portfolio Shareable',
 4094:          'timezone'       => 'Can set own Time Zone',
 4095:          'official'       => 'Can Request Official Courses',
 4096:          'unofficial'     => 'Can Request Unofficial Courses',
 4097:          'community'      => 'Can Request Communities',
 4098:          'textbook'       => 'Can Request Textbook Courses',
 4099:          'placement'      => 'Can Request Placement Tests',
 4100:          'lti'            => 'Can Request LTI Courses',
 4101:          'requestauthor'  => 'Can Request Author Role',
 4102:          'inststatus'     => "Affiliation",
 4103:          'prvs'           => 'Previous Value:',
 4104:          'chto'           => 'Changed To:',
 4105:          'editors'        => "Available Editors in Authoring Space",
 4106:          'managers'       => "Co-authors who can add/revoke roles",
 4107:          'archive'        => "Managers can download tar.gz file of Authoring Space",
 4108:          'edit'           => 'Standard editor (Edit)',
 4109:          'xml'            => 'Text editor (EditXML)',
 4110:          'daxe'           => 'Daxe editor (Daxe)',
 4111:     );
 4112:     if ($changed) {
 4113:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 4114:                 &Apache::loncommon::start_data_table().
 4115:                 &Apache::loncommon::start_data_table_header_row());
 4116:         $r->print("<th>&nbsp;</th>\n");
 4117:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 4118:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 4119:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4120:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 4121: 
 4122:         foreach my $item (@userinfo) {
 4123:             my $value = $env{'form.c'.$item};
 4124:             #show changes only:
 4125:             unless ($value eq $userenv->{$item}){
 4126:                 $r->print(&Apache::loncommon::start_data_table_row());
 4127:                 $r->print("<td>$lt{$item}</td>\n");
 4128:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 4129:                 $r->print("<td>$value </td>\n");
 4130:                 $r->print(&Apache::loncommon::end_data_table_row());
 4131:             }
 4132:         }
 4133:         foreach my $entry (@{$order}) {
 4134:             if ($canshow->{$entry}) {
 4135:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') ||
 4136:                     ($entry eq 'requestauthor') || ($entry eq 'authordefaults')) {
 4137:                     my @items;
 4138:                     if ($entry eq 'requestauthor') {
 4139:                         @items = ($entry);
 4140:                     } elsif ($entry eq 'authordefaults') {
 4141:                         @items = ('webdav','managers','editors','archive');
 4142:                     } else {
 4143:                         @items = @{$requestcourses};
 4144:                     }
 4145:                     foreach my $item (@items) {
 4146:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 4147:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 4148:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 4149:                             $r->print("<td>$lt{$item}</td><td>\n");
 4150:                             unless ($item eq 'managers') {
 4151:                                 $r->print($oldsetting->{$item});
 4152:                             }
 4153:                             if ($oldsettingtext->{$item}) {
 4154:                                 if ($oldsetting->{$item}) {
 4155:                                     unless ($item eq 'managers') {
 4156:                                         $r->print(' -- ');
 4157:                                     }
 4158:                                 }
 4159:                                 $r->print($oldsettingtext->{$item});
 4160:                             }
 4161:                             $r->print("</td>\n<td>");
 4162:                             unless ($item eq 'managers') {
 4163:                                 $r->print($newsetting->{$item});
 4164:                             }
 4165:                             if ($newsettingtext->{$item}) {
 4166:                                 if ($newsetting->{$item}) {
 4167:                                     unless ($item eq 'managers') {
 4168:                                         $r->print(' -- ');
 4169:                                     }
 4170:                                 }
 4171:                                 $r->print($newsettingtext->{$item});
 4172:                             }
 4173:                             $r->print("</td>\n");
 4174:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4175:                         }
 4176:                     }
 4177:                 } elsif ($entry eq 'tools') {
 4178:                     foreach my $item (@{$usertools}) {
 4179:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 4180:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4181:                             $r->print("<td>$lt{$item}</td>\n");
 4182:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 4183:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 4184:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4185:                         }
 4186:                     }
 4187:                 } elsif ($entry eq 'quota') {
 4188:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 4189:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 4190:                         foreach my $name ('portfolio','author') {
 4191:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 4192:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4193:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 4194:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 4195:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 4196:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4197:                             }
 4198:                         }
 4199:                     }
 4200:                 } else {
 4201:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 4202:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4203:                         $r->print("<td>$lt{$entry}</td>\n");
 4204:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 4205:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 4206:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4207:                     }
 4208:                 }
 4209:             }
 4210:         }
 4211:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 4212:     } else {
 4213:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 4214:                   '<p>'.&mt('No changes made to user information').'</p>');
 4215:     }
 4216:     return;
 4217: }
 4218: 
 4219: sub tool_changes {
 4220:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 4221:         $changed,$newaccess,$newaccesstext) = @_;
 4222:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 4223:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 4224:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 4225:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 4226:         return;
 4227:     }
 4228:     my %reqdisplay = &requestchange_display();
 4229:     if ($context eq 'reqcrsotherdom') {
 4230:         my @options = ('approval','validate','autolimit');
 4231:         my $optregex = join('|',@options);
 4232:         my $cdom = $env{'request.role.domain'};
 4233:         foreach my $tool (@{$usertools}) {
 4234:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4235:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4236:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 4237:             my ($newop,$limit);
 4238:             if ($env{'form.'.$context.'_'.$tool}) {
 4239:                 $newop = $env{'form.'.$context.'_'.$tool};
 4240:                 if ($newop eq 'autolimit') {
 4241:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4242:                     $limit =~ s/\D+//g;
 4243:                     $newop .= '='.$limit;
 4244:                 }
 4245:             }
 4246:             if ($userenv->{$context.'.'.$tool} eq '') {
 4247:                 if ($newop) {
 4248:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 4249:                                                   $changeHash,$context);
 4250:                     if ($changed->{$tool}) {
 4251:                         if ($newop =~ /^autolimit/) {
 4252:                             if ($limit) {
 4253:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4254:                             } else {
 4255:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4256:                             }
 4257:                         } else {
 4258:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 4259:                         }
 4260:                     } else {
 4261:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4262:                     }
 4263:                 }
 4264:             } else {
 4265:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 4266:                 my @new;
 4267:                 my $changedoms;
 4268:                 foreach my $req (@curr) {
 4269:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 4270:                         my $oldop = $1;
 4271:                         if ($oldop =~ /^autolimit=(\d*)/) {
 4272:                             my $limit = $1;
 4273:                             if ($limit) {
 4274:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4275:                             } else {
 4276:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4277:                             }
 4278:                         } else {
 4279:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 4280:                         }
 4281:                         if ($oldop ne $newop) {
 4282:                             $changedoms = 1;
 4283:                             foreach my $item (@curr) {
 4284:                                 my ($reqdom,$option) = split(':',$item);
 4285:                                 unless ($reqdom eq $cdom) {
 4286:                                     push(@new,$item);
 4287:                                 }
 4288:                             }
 4289:                             if ($newop) {
 4290:                                 push(@new,$cdom.':'.$newop);
 4291:                             }
 4292:                             @new = sort(@new);
 4293:                         }
 4294:                         last;
 4295:                     }
 4296:                 }
 4297:                 if ((!$changedoms) && ($newop)) {
 4298:                     $changedoms = 1;
 4299:                     @new = sort(@curr,$cdom.':'.$newop);
 4300:                 }
 4301:                 if ($changedoms) {
 4302:                     my $newdomstr;
 4303:                     if (@new) {
 4304:                         $newdomstr = join(',',@new);
 4305:                     }
 4306:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 4307:                                                   $context);
 4308:                     if ($changed->{$tool}) {
 4309:                         if ($env{'form.'.$context.'_'.$tool}) {
 4310:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 4311:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4312:                                 $limit =~ s/\D+//g;
 4313:                                 if ($limit) {
 4314:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4315:                                 } else {
 4316:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4317:                                 }
 4318:                             } else {
 4319:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 4320:                             }
 4321:                         } else {
 4322:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4323:                         }
 4324:                     }
 4325:                 }
 4326:             }
 4327:         }
 4328:         return;
 4329:     }
 4330:     my %tooldesc = &Apache::lonlocal::texthash(
 4331:         'edit' => 'Standard editor (Edit)',
 4332:         'xml'  => 'Text editor (EditXML)',
 4333:         'daxe' => 'Daxe editor (Daxe)',
 4334:     );
 4335:     foreach my $tool (@{$usertools}) {
 4336:         my ($newval,$limit,$envkey);
 4337:         $envkey = $context.'.'.$tool;
 4338:         if ($context eq 'requestcourses') {
 4339:             $newval = $env{'form.crsreq_'.$tool};
 4340:             if ($newval eq 'autolimit') {
 4341:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 4342:                 $limit =~ s/\D+//g;
 4343:                 $newval .= '='.$limit;
 4344:             }
 4345:         } elsif ($context eq 'requestauthor') {
 4346:             $newval = $env{'form.'.$context};
 4347:             $envkey = $context;
 4348:         } elsif ($context eq 'authordefaults') {
 4349:             if ($tool eq 'editors') {
 4350:                 $envkey = 'authoreditors';
 4351:                 if ($env{'form.customeditors'} == 1) {
 4352:                     my @editors;
 4353:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 4354:                     if (@posseditors) {
 4355:                         foreach my $editor (@posseditors) {
 4356:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 4357:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 4358:                                     push(@editors,$editor);
 4359:                                 }
 4360:                             }
 4361:                         }
 4362:                     }
 4363:                     if (@editors) {
 4364:                         $newval = join(',',(sort(@editors)));
 4365:                     }
 4366:                 }
 4367:             } elsif ($tool eq 'managers') {
 4368:                 $envkey = 'authormanagers';
 4369:                 my @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 4370:                 if (@possibles) {
 4371:                     my %ca_roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},
 4372:                                                                  undef,['active','future'],['ca']);
 4373:                     if (keys(%ca_roles)) {
 4374:                         my @custommanagers;
 4375:                         foreach my $user (@possibles) {
 4376:                             if ($user =~ /^($match_username):($match_domain)$/) {
 4377:                                 if (exists($ca_roles{$user.':ca'})) {
 4378:                                     unless ($user eq $env{'form.ccuname'}.':'.$env{'form.ccdomain'}) {
 4379:                                         push(@custommanagers,$user);
 4380:                                     }
 4381:                                 }
 4382:                             }
 4383:                         }
 4384:                         if (@custommanagers) {
 4385:                             $newval = join(',',sort(@custommanagers));
 4386:                         }
 4387:                     }
 4388:                 }
 4389:             } elsif ($tool eq 'webdav') {
 4390:                 $envkey = 'tools.webdav';
 4391:                 $newval = $env{'form.'.$context.'_'.$tool};
 4392:             } elsif ($tool eq 'archive') {
 4393:                 $envkey = 'authorarchive';
 4394:                 $newval = $env{'form.'.$context.'_'.$tool};
 4395:             }
 4396:         } else {
 4397:             $newval = $env{'form.'.$context.'_'.$tool};
 4398:         }
 4399:         if ($userenv->{$envkey} ne '') {
 4400:             $oldaccess->{$tool} = &mt('custom');
 4401:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4402:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 4403:                     my $currlimit = $1;
 4404:                     if ($currlimit eq '') {
 4405:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4406:                     } else {
 4407:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 4408:                     }
 4409:                 } elsif ($userenv->{$envkey}) {
 4410:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4411:                 } else {
 4412:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4413:                 }
 4414:             } elsif ($context eq 'authordefaults') {
 4415:                 if ($tool eq 'managers') {
 4416:                     if ($userenv->{$envkey} eq '') {
 4417:                         $oldaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4418:                     } else {
 4419:                         my $managers = $userenv->{$envkey};
 4420:                         $managers =~ s/,/, /g;
 4421:                         $oldaccesstext->{$tool} = $managers;
 4422:                     }
 4423:                 } elsif ($tool eq 'editors') {
 4424:                     $oldaccesstext->{$tool} = &mt('can use: [_1]',
 4425:                                                   join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4426:                 } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4427:                     if ($userenv->{$envkey}) {
 4428:                         $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4429:                     } else {
 4430:                         $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4431:                     }
 4432:                 }
 4433:             } else {
 4434:                 if ($userenv->{$envkey}) {
 4435:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4436:                 } else {
 4437:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4438:                 }
 4439:             }
 4440:             $changeHash->{$envkey} = $userenv->{$envkey};
 4441:             if (($env{'form.custom'.$tool} == 1) ||
 4442:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4443:                 if ($newval ne $userenv->{$envkey}) {
 4444:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4445:                                                     $context);
 4446:                     if ($changed->{$tool}) {
 4447:                         $newaccess->{$tool} = &mt('custom');
 4448:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4449:                             if ($newval =~ /^autolimit/) {
 4450:                                 if ($limit) {
 4451:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4452:                                 } else {
 4453:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4454:                                 }
 4455:                             } elsif ($newval) {
 4456:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 4457:                             } else {
 4458:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4459:                             }
 4460:                         } elsif ($context eq 'authordefaults') {
 4461:                             if ($tool eq 'editors') {
 4462:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4463:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$changeHash->{$envkey})));
 4464:                             } elsif ($tool eq 'managers') {
 4465:                                 if ($changeHash->{$envkey} eq '') {
 4466:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4467:                                 } else {
 4468:                                     my $managers = $changeHash->{$envkey};
 4469:                                     $managers =~ s/,/, /g;
 4470:                                     $newaccesstext->{$tool} = $managers;
 4471:                                 }
 4472:                             } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4473:                                 if ($newval) {
 4474:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4475:                                 } else {
 4476:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4477:                                 }
 4478:                             }
 4479:                         } else {
 4480:                             if ($newval) {
 4481:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4482:                             } else {
 4483:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4484:                             }
 4485:                         }
 4486:                     } else {
 4487:                         $newaccess->{$tool} = $oldaccess->{$tool};
 4488:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4489:                             if ($userenv->{$envkey} =~ /^autolimit/) {
 4490:                                 if ($limit) {
 4491:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4492:                                 } else {
 4493:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4494:                                 }
 4495:                             } elsif ($userenv->{$envkey}) {
 4496:                                 $newaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4497:                             } else {
 4498:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4499:                             }
 4500:                         } elsif ($context eq 'authordefaults') {
 4501:                             if ($tool eq 'editors') {
 4502:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4503:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4504:                             } elsif ($tool eq 'managers') {
 4505:                                 if ($userenv->{$envkey} eq '') {
 4506:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4507:                                 } else {
 4508:                                     my $managers = $userenv->{$envkey};
 4509:                                     $managers =~ s/,/, /g;
 4510:                                     $newaccesstext->{$tool} = $managers;
 4511:                                 }
 4512:                             } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4513:                                 if ($userenv->{$envkey}) {
 4514:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4515:                                 } else {
 4516:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4517:                                 }
 4518:                             }
 4519:                         } else {
 4520:                             if ($userenv->{$context.'.'.$tool}) {
 4521:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4522:                             } else {
 4523:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4524:                             }
 4525:                         }
 4526:                     }
 4527:                 } else {
 4528:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4529:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4530:                 }
 4531:             } else {
 4532:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 4533:                 if ($changed->{$tool}) {
 4534:                     $newaccess->{$tool} = &mt('default');
 4535:                 } else {
 4536:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4537:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4538:                         if ($newval =~ /^autolimit/) {
 4539:                             if ($limit) {
 4540:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4541:                             } else {
 4542:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4543:                             }
 4544:                         } elsif ($newval) {
 4545:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4546:                         } else {
 4547:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4548:                         }
 4549:                     } elsif ($context eq 'authordefaults') {
 4550:                         if ($tool eq 'editors') {
 4551:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4552:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4553:                         } elsif ($tool eq 'managers') {
 4554:                             if ($newval eq '') {
 4555:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4556:                             } else {
 4557:                                 my $managers = $newval;
 4558:                                 $managers =~ s/,/, /g;
 4559:                                 $newaccesstext->{$tool} = $managers;
 4560:                             }
 4561:                         } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4562:                             if ($userenv->{$envkey}) {
 4563:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4564:                             } else {
 4565:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4566:                             }
 4567:                         }
 4568:                     } else {
 4569:                         if ($userenv->{$context.'.'.$tool}) {
 4570:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4571:                         } else {
 4572:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4573:                         }
 4574:                     }
 4575:                 }
 4576:             }
 4577:         } else {
 4578:             $oldaccess->{$tool} = &mt('default');
 4579:             if (($env{'form.custom'.$tool} == 1) ||
 4580:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4581:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4582:                                                 $context);
 4583:                 if ($changed->{$tool}) {
 4584:                     $newaccess->{$tool} = &mt('custom');
 4585:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4586:                         if ($newval =~ /^autolimit/) {
 4587:                             if ($limit) {
 4588:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4589:                             } else {
 4590:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4591:                             }
 4592:                         } elsif ($newval) {
 4593:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4594:                         } else {
 4595:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4596:                         }
 4597:                     } elsif ($context eq 'authordefaults') {
 4598:                         if ($tool eq 'managers') {
 4599:                             if ($newval eq '') {
 4600:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4601:                             } else {
 4602:                                 my $managers = $newval;
 4603:                                 $managers =~ s/,/, /g;
 4604:                                 $newaccesstext->{$tool} = $managers;
 4605:                             }
 4606:                         } elsif ($tool eq 'editors') {
 4607:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4608:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4609:                         } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4610:                             if ($newval) {
 4611:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4612:                             } else {
 4613:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4614:                             }
 4615:                         }
 4616:                     } else {
 4617:                         if ($newval) {
 4618:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4619:                         } else {
 4620:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4621:                         }
 4622:                     }
 4623:                 } else {
 4624:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4625:                 }
 4626:             } else {
 4627:                 $newaccess->{$tool} = $oldaccess->{$tool};
 4628:             }
 4629:         }
 4630:     }
 4631:     return;
 4632: }
 4633: 
 4634: sub update_roles {
 4635:     my ($r,$context,$showcredits) = @_;
 4636:     my $now=time;
 4637:     my @rolechanges;
 4638:     my (%disallowed,%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 4639:         %pending,%reject,%notifydc,%status,%unauthorized,%currqueued);
 4640:     $got_role_approvals{$context} = '';
 4641:     $process_by{$context} = {};
 4642:     my @domroles = &Apache::lonuserutils::domain_roles();
 4643:     my @cstrroles = &Apache::lonuserutils::construction_space_roles();
 4644:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
 4645:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 4646:     foreach my $key (keys(%env)) {
 4647: 	next if (! $env{$key});
 4648:         next if ($key eq 'form.action');
 4649: 	# Revoke roles
 4650: 	if ($key=~/^form\.rev/) {
 4651: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 4652: # Revoke standard role
 4653: 		my ($scope,$role) = ($1,$2);
 4654: 		my $result =
 4655: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 4656: 						$env{'form.ccuname'},
 4657: 						$scope,$role,'','',$context);
 4658:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4659:                             &mt('Revoking [_1] in [_2]',
 4660:                                 &Apache::lonnet::plaintext($role),
 4661:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4662:                                 $result ne "ok").'<br />');
 4663:                 if ($result ne "ok") {
 4664:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4665:                 }
 4666: 		if ($role eq 'st') {
 4667: 		    my $result = 
 4668:                         &Apache::lonuserutils::classlist_drop($scope,
 4669:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4670: 			    $now);
 4671:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4672: 		}
 4673:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4674:                     push(@rolechanges,$role);
 4675:                 }
 4676: 	    }
 4677: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4678: # Revoke custom role
 4679:                 my $result = &Apache::lonnet::revokecustomrole(
 4680:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4681:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4682:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4683:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4684:                             $result ne 'ok').'<br />');
 4685:                 if ($result ne "ok") {
 4686:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4687:                 }
 4688:                 if (!grep(/^cr$/,@rolechanges)) {
 4689:                     push(@rolechanges,'cr');
 4690:                 }
 4691: 	    }
 4692: 	} elsif ($key=~/^form\.del/) {
 4693: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4694: # Delete standard role
 4695: 		my ($scope,$role) = ($1,$2);
 4696: 		my $result =
 4697: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4698: 						$env{'form.ccuname'},
 4699: 						$scope,$role,$now,0,1,'',
 4700:                                                 $context);
 4701:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4702:                             &mt('Deleting [_1] in [_2]',
 4703:                                 &Apache::lonnet::plaintext($role),
 4704:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4705:                             $result ne 'ok').'<br />');
 4706:                 if ($result ne "ok") {
 4707:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4708:                 }
 4709: 
 4710: 		if ($role eq 'st') {
 4711: 		    my $result = 
 4712:                         &Apache::lonuserutils::classlist_drop($scope,
 4713:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4714: 			    $now);
 4715: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4716: 		}
 4717:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4718:                     push(@rolechanges,$role);
 4719:                 }
 4720:             }
 4721: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4722:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4723: # Delete custom role
 4724:                 my $result =
 4725:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4726:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4727:                         0,1,$context);
 4728:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4729:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4730:                       $result ne "ok").'<br />');
 4731:                 if ($result ne "ok") {
 4732:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4733:                 }
 4734: 
 4735:                 if (!grep(/^cr$/,@rolechanges)) {
 4736:                     push(@rolechanges,'cr');
 4737:                 }
 4738:             }
 4739: 	} elsif ($key=~/^form\.ren/) {
 4740:             my $udom = $env{'form.ccdomain'};
 4741:             my $uname = $env{'form.ccuname'};
 4742: # Re-enable standard role
 4743: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4744:                 my $url = $1;
 4745:                 my $role = $2;
 4746:                 my $id = $url.'_'.$role;
 4747:                 my $logmsg;
 4748:                 my $output;
 4749:                 if ($role eq 'st') {
 4750:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4751:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4752:                         my $credits;
 4753:                         if ($showcredits) {
 4754:                             my $defaultcredits =
 4755:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4756:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4757:                         }
 4758:                         unless ($udom eq $cdom) {
 4759:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4760:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,$credits,
 4761:                                          \%process_by,\%instdoms,\%got_role_approvals,
 4762:                                          \%got_instdoms,\%reject,\%pending,\%notifydc,
 4763:                                          \%status,\%unauthorized,\%currqueued));
 4764:                         }
 4765:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4766:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4767:                             if ($result eq 'refused' && $logmsg) {
 4768:                                 $output = $logmsg;
 4769:                             } else { 
 4770:                                 $output = &mt('Error: [_1]',$result)."\n";
 4771:                             }
 4772:                         } else {
 4773:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4774:                                         &Apache::lonnet::plaintext($role),
 4775:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4776:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4777:                         }
 4778:                     }
 4779:                 } else {
 4780:                     my ($cdom,$cnum,$csec);
 4781:                     if (grep(/^\Q$role\E$/,@cstrroles)) {
 4782:                         ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_username)$});
 4783:                     } elsif (grep(/^\Q$role\E$/,@domroles)) {
 4784:                         ($cdom) = ($url =~ m{^/($match_domain)/$});
 4785:                     } elsif ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4786:                         ($cdom,$cnum,$csec) = ($1,$2,$3);
 4787:                     }
 4788:                     if ($cdom ne '') {
 4789:                         unless ($udom eq $cdom) {
 4790:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4791:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4792:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4793:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4794:                         }
 4795:                     }
 4796: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4797:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4798:                                $context);
 4799:                     $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4800:                                     &Apache::lonnet::plaintext($role),
 4801:                                     &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4802:                     if ($result ne "ok") {
 4803:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4804:                     }
 4805:                 }
 4806:                 $r->print($output);
 4807:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4808:                     push(@rolechanges,$role);
 4809:                 }
 4810: 	    }
 4811: # Re-enable custom role
 4812: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4813:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4814:                 my $id = $url.'_cr'."/$rdom/$rnam/$rolename";
 4815:                 my $role = "cr/$rdom/$rnam/$rolename";
 4816:                 if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4817:                     my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4818:                     unless ($udom eq $cdom) {
 4819:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4820:                                      $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4821:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4822:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4823:                     }
 4824:                 }
 4825:                 my $result = &Apache::lonnet::assigncustomrole(
 4826:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4827:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4828:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4829:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4830:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4831:                     $result ne "ok").'<br />');
 4832:                 if ($result ne "ok") {
 4833:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4834:                 }
 4835:                 if (!grep(/^cr$/,@rolechanges)) {
 4836:                     push(@rolechanges,'cr');
 4837:                 }
 4838:             }
 4839: 	} elsif ($key=~/^form\.act/) {
 4840:             my $udom = $env{'form.ccdomain'};
 4841:             my $uname = $env{'form.ccuname'};
 4842: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4843:                 # Activate a custom role
 4844: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4845: 		my $url='/'.$one.'/'.$two;
 4846:                 my $id = $url.'_cr/'."$three/$four/$five";
 4847:                 my $role = "cr/$three/$four/$five";
 4848: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4849: 
 4850:                 my $start = ( $env{'form.start_'.$full} ?
 4851:                               $env{'form.start_'.$full} :
 4852:                               $now );
 4853:                 my $end   = ( $env{'form.end_'.$full} ?
 4854:                               $env{'form.end_'.$full} :
 4855:                               0 );
 4856: 
 4857:                 # split multiple sections
 4858:                 my %sections = ();
 4859:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$five);
 4860:                 if ($num_sections == 0) {
 4861:                     unless ($udom eq $one) {
 4862:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4863:                                      $uname,$role,$start,$end,$one,$two,'','',\%process_by,
 4864:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4865:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4866:                     }
 4867:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4868:                 } else {
 4869: 		    my %curr_groups =
 4870: 			&Apache::longroup::coursegroups($one,$two);
 4871:                     my ($restricted,$numchanges);
 4872:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4873:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4874:                             exists($curr_groups{$sec})) {
 4875:                             $disallowed{$sec} = $url;
 4876:                             next;
 4877:                         }
 4878:                         my $securl = $url.'/'.$sec;
 4879:                         my $secid = $securl.'_cr'."/$three/$four/$five";
 4880:                         undef($restricted);
 4881:                         unless ($udom eq $one) {
 4882:                             next if (&Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4883:                                          $uname,$role,$start,$end,$one,$two,$sec,'',\%process_by,
 4884:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4885:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4886:                         }
 4887:                         $numchanges ++;
 4888: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4889:                     }
 4890:                     next unless ($numchanges);
 4891:                 }
 4892:                 if (!grep(/^cr$/,@rolechanges)) {
 4893:                     push(@rolechanges,'cr');
 4894:                 }
 4895: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4896: 		# Activate roles for sections with 3 id numbers
 4897: 		# set start, end times, and the url for the class
 4898: 		my ($one,$two,$three)=($1,$2,$3);
 4899: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ?
 4900: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} :
 4901: 			      $now );
 4902: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ?
 4903: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4904: 			      0 );
 4905: 		my $url='/'.$one.'/'.$two;
 4906:                 my $id = $url.'_'.$three;
 4907:                 # split multiple sections
 4908:                 my %sections = ();
 4909:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4910:                 my ($credits,$numchanges);
 4911:                 if ($three eq 'st') {
 4912:                     if ($showcredits) {
 4913:                         my $defaultcredits = 
 4914:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4915:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4916:                         $credits =~ s/[^\d\.]//g;
 4917:                         if ($credits eq $defaultcredits) {
 4918:                             undef($credits);
 4919:                         }
 4920:                     }
 4921:                 }
 4922:                 if ($num_sections == 0) {
 4923:                     unless ($udom eq $one) {
 4924:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4925:                                      $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4926:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4927:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4928:                     }
 4929:                     $numchanges ++;
 4930:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4931:                 } else {
 4932:                     my %curr_groups = 
 4933: 			&Apache::longroup::coursegroups($one,$two);
 4934:                     my $emptysec = 0;
 4935:                     my $restricted;
 4936:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4937:                         $sec =~ s/\W//g;
 4938:                         if ($sec ne '') {
 4939:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4940:                                 exists($curr_groups{$sec})) {
 4941:                                 $disallowed{$sec} = $url;
 4942:                                 next;
 4943:                             }
 4944:                             my $securl = $url.'/'.$sec;
 4945:                             my $secid = $securl.'_'.$three;
 4946:                             unless ($udom eq $one) {
 4947:                                 undef($restricted);
 4948:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4949:                                                   $uname,$three,$start,$end,$one,$two,$sec,$credits,\%process_by,
 4950:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4951:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4952:                                 next if ($restricted);
 4953:                             }
 4954:                             $numchanges ++;
 4955:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4956:                         } else {
 4957:                             $emptysec = 1;
 4958:                         }
 4959:                     }
 4960:                     if ($emptysec) {
 4961:                         unless ($udom eq $one) {
 4962:                             undef($restricted);
 4963:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4964:                                               $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4965:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4966:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4967:                             next if ($restricted);
 4968:                         }
 4969:                         $numchanges ++;
 4970:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4971:                     }
 4972:                     next unless ($numchanges);
 4973:                 }
 4974:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4975:                     push(@rolechanges,$three);
 4976:                 }
 4977: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4978: 		# Activate roles for sections with two id numbers
 4979: 		# set start, end times, and the url for the class
 4980: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ?
 4981: 			      $env{'form.start_'.$1.'_'.$2} :
 4982: 			      $now );
 4983: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ?
 4984: 			      $env{'form.end_'.$1.'_'.$2} :
 4985: 			      0 );
 4986:                 my $one = $1;
 4987:                 my $two = $2;
 4988: 		my $url='/'.$one.'/';
 4989:                 my $id = $url.'_'.$two;
 4990:                 my ($cdom,$cnum) = split(/\//,$one);
 4991:                 # split multiple sections
 4992:                 my %sections = ();
 4993:                 my ($restricted,$numchanges);
 4994:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4995:                 if ($num_sections == 0) {
 4996:                     unless ($udom eq $one) {
 4997:                         $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4998:                                           $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4999:                                           \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 5000:                                           \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 5001:                         next if ($restricted);
 5002:                     }
 5003:                     $numchanges ++;
 5004:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 5005:                 } else {
 5006:                     my $emptysec = 0;
 5007:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 5008:                         if ($sec ne '') {
 5009:                             my $securl = $url.'/'.$sec;
 5010:                             my $secid = $securl.'_'.$two;
 5011:                             unless ($udom eq $one) {
 5012:                                 undef($restricted);
 5013:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 5014:                                                   $uname,$two,$start,$end,$cdom,$cnum,$sec,'',\%process_by,
 5015:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 5016:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 5017:                                 next if ($restricted);
 5018:                             }
 5019:                             $numchanges ++;
 5020:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 5021:                         } else {
 5022:                             $emptysec = 1;
 5023:                         }
 5024:                     }
 5025:                     if ($emptysec) {
 5026:                         unless ($udom eq $one) {
 5027:                             undef($restricted);
 5028:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 5029:                                               $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 5030:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 5031:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 5032:                             next if ($restricted);
 5033:                         }
 5034:                         $numchanges ++;
 5035:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 5036:                     }
 5037:                     next unless ($numchanges); 
 5038:                 }
 5039:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 5040:                     push(@rolechanges,$two);
 5041:                 }
 5042: 	    } else {
 5043: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 5044:             }
 5045:             foreach my $key (sort(keys(%disallowed))) {
 5046:                 $r->print('<p class="LC_warning">');
 5047:                 if (($key eq 'none') || ($key eq 'all')) {  
 5048:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 5049:                 } else {
 5050:                     $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>'));
 5051:                 }
 5052:                 $r->print('</p><p>'
 5053:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 5054:                              ,'<a href="javascript:history.go(-1)'
 5055:                              ,'</a>')
 5056:                          .'</p><br />'
 5057:                 );
 5058:             }
 5059: 	}
 5060:     } # End of foreach (keys(%env))
 5061:     if ((keys(%reject)) || (keys(%unauthorized))) {
 5062:         $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5063:     }
 5064:     if ((keys(%pending)) || (keys(%currqueued))) {
 5065:         $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5066:     }
 5067: # Flush the course logs so reverse user roles immediately updated
 5068:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5069:     if (@rolechanges == 0) {
 5070:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 5071:     }
 5072:     return @rolechanges;
 5073: }
 5074: 
 5075: sub get_user_credits {
 5076:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 5077:     if ($cdom eq '' || $cnum eq '') {
 5078:         return unless ($env{'request.course.id'});
 5079:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5080:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5081:     }
 5082:     my $credits;
 5083:     my %currhash =
 5084:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 5085:     if (keys(%currhash) > 0) {
 5086:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 5087:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 5088:         $credits = $items[$crdidx];
 5089:         $credits =~ s/[^\d\.]//g;
 5090:     }
 5091:     if ($credits eq $defaultcredits) {
 5092:         undef($credits);
 5093:     }
 5094:     return $credits;
 5095: }
 5096: 
 5097: sub enroll_single_student {
 5098:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 5099:         $showcredits,$defaultcredits) = @_;
 5100:     $r->print('<h3>');
 5101:     if ($crstype eq 'Community') {
 5102:         $r->print(&mt('Enrolling Member'));
 5103:     } else {
 5104:         $r->print(&mt('Enrolling Student'));
 5105:     }
 5106:     $r->print('</h3>');
 5107: 
 5108:     # Remove non alphanumeric values from section
 5109:     $env{'form.sections'}=~s/\W//g;
 5110: 
 5111:     my $credits;
 5112:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 5113:         $credits = $env{'form.credits'};
 5114:         $credits =~ s/[^\d\.]//g;
 5115:         if ($credits ne '') {
 5116:             if ($credits eq $defaultcredits) {
 5117:                 undef($credits);
 5118:             }
 5119:         }
 5120:     }
 5121:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 5122:     my (%got_role_approvals,%got_instdoms,%process_by,%instdoms,%pending,%reject,%notifydc,
 5123:         %status,%unauthorized,%currqueued);
 5124:     unless ($env{'form.ccdomain'} eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 5125:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5126:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5127:         my $csec = $env{'form.sections'};
 5128:         my $id = "/$cdom/$cnum";
 5129:         if ($csec ne '') {
 5130:             $id .= "/$csec";
 5131:         }
 5132:         $id .= '_st';
 5133:         if (&Apache::lonuserutils::restricted_dom($context,$id,$env{'form.ccdomain'},$env{'form.ccuname'},
 5134:                                                   'st',$startdate,$enddate,$cdom,$cnum,$csec,$credits,
 5135:                                                   \%process_by,\%instdoms,\%got_role_approvals,\%got_instdoms,
 5136:                                                   \%reject,\%pending,\%notifydc,\%status,\%unauthorized,\%currqueued)) {
 5137:             if ((keys(%reject)) || (keys(%unauthorized))) {
 5138:                 $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5139:             }
 5140:             if ((keys(%pending)) || (keys(%currqueued))) {
 5141:                 $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5142:             }
 5143:             return;
 5144:         }
 5145:     }
 5146: 
 5147:     # Clean out any old student roles the user has in this class.
 5148:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 5149:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 5150:     my $enroll_result =
 5151:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 5152:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 5153:             $env{'form.cmiddlename'},$env{'form.clastname'},
 5154:             $env{'form.generation'},$env{'form.sections'},$enddate,
 5155:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 5156:             $credits);
 5157:     if ($enroll_result =~ /^ok/) {
 5158:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 5159:         if ($env{'form.sections'} ne '') {
 5160:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 5161:         }
 5162:         my ($showstart,$showend);
 5163:         if ($startdate <= $now) {
 5164:             $showstart = &mt('Access starts immediately');
 5165:         } else {
 5166:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 5167:         }
 5168:         if ($enddate == 0) {
 5169:             $showend = &mt('ends: no ending date');
 5170:         } else {
 5171:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 5172:         }
 5173:         $r->print('.<br />'.$showstart.'; '.$showend);
 5174:         if ($startdate <= $now && !$newuser) {
 5175:             $r->print('<p class="LC_info">');
 5176:             if ($crstype eq 'Community') {
 5177:                 $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.'));
 5178:             } else {
 5179:                 $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.'));
 5180:            }
 5181:            $r->print('</p>');
 5182:         }
 5183:     } else {
 5184:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 5185:     }
 5186:     return;
 5187: }
 5188: 
 5189: sub get_defaultquota_text {
 5190:     my ($settingstatus) = @_;
 5191:     my $defquotatext; 
 5192:     if ($settingstatus eq '') {
 5193:         $defquotatext = &mt('default');
 5194:     } else {
 5195:         my ($usertypes,$order) =
 5196:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 5197:         if ($usertypes->{$settingstatus} eq '') {
 5198:             $defquotatext = &mt('default');
 5199:         } else {
 5200:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 5201:         }
 5202:     }
 5203:     return $defquotatext;
 5204: }
 5205: 
 5206: sub update_result_form {
 5207:     my ($uhome) = @_;
 5208:     my $outcome = 
 5209:     '<form name="userupdate" method="post" action="">'."\n";
 5210:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 5211:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5212:     }
 5213:     if ($env{'form.origname'} ne '') {
 5214:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 5215:     }
 5216:     foreach my $item ('sortby','seluname','seludom') {
 5217:         if (exists($env{'form.'.$item})) {
 5218:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5219:         }
 5220:     }
 5221:     if ($uhome eq 'no_host') {
 5222:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 5223:     }
 5224:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 5225:                 '<input type="hidden" name="currstate" value="" />'."\n".
 5226:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5227:                 '</form>';
 5228:     return $outcome;
 5229: }
 5230: 
 5231: sub quota_admin {
 5232:     my ($setquota,$changeHash,$name) = @_;
 5233:     my $quotachanged;
 5234:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 5235:         # Current user has quota modification privileges
 5236:         if (ref($changeHash) eq 'HASH') {
 5237:             $quotachanged = 1;
 5238:             $changeHash->{$name.'quota'} = $setquota;
 5239:         }
 5240:     }
 5241:     return $quotachanged;
 5242: }
 5243: 
 5244: sub tool_admin {
 5245:     my ($tool,$settool,$changeHash,$context) = @_;
 5246:     my $canchange = 0; 
 5247:     if ($context eq 'requestcourses') {
 5248:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 5249:             $canchange = 1;
 5250:         }
 5251:     } elsif ($context eq 'reqcrsotherdom') {
 5252:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 5253:             $canchange = 1;
 5254:         }
 5255:     } elsif ($context eq 'requestauthor') {
 5256:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5257:             $canchange = 1;
 5258:         }
 5259:     } elsif ($context eq 'authordefaults') {
 5260:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5261:             $canchange = 1;
 5262:         }
 5263:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 5264:         # Current user has quota modification privileges
 5265:         $canchange = 1;
 5266:     }
 5267:     my $toolchanged;
 5268:     if ($canchange) {
 5269:         if (ref($changeHash) eq 'HASH') {
 5270:             $toolchanged = 1;
 5271:             if ($tool eq 'requestauthor') {
 5272:                 $changeHash->{$context} = $settool;
 5273:             } elsif (($tool eq 'managers') || ($tool eq 'editors') || ($tool eq 'archive')) {
 5274:                 $changeHash->{'author'.$tool} = $settool;
 5275:             } elsif ($tool eq 'webdav') {
 5276:                 $changeHash->{'tools.'.$tool} = $settool;
 5277:             } else {
 5278:                 $changeHash->{$context.'.'.$tool} = $settool;
 5279:             }
 5280:         }
 5281:     }
 5282:     return $toolchanged;
 5283: }
 5284: 
 5285: sub build_roles {
 5286:     my ($sectionstr,$sections,$role) = @_;
 5287:     my $num_sections = 0;
 5288:     if ($sectionstr=~ /,/) {
 5289:         my @secnums = split/,/,$sectionstr;
 5290:         if ($role eq 'st') {
 5291:             $secnums[0] =~ s/\W//g;
 5292:             $$sections{$secnums[0]} = 1;
 5293:             $num_sections = 1;
 5294:         } else {
 5295:             foreach my $sec (@secnums) {
 5296:                 $sec =~ ~s/\W//g;
 5297:                 if (!($sec eq "")) {
 5298:                     if (exists($$sections{$sec})) {
 5299:                         $$sections{$sec} ++;
 5300:                     } else {
 5301:                         $$sections{$sec} = 1;
 5302:                         $num_sections ++;
 5303:                     }
 5304:                 }
 5305:             }
 5306:         }
 5307:     } else {
 5308:         $sectionstr=~s/\W//g;
 5309:         unless ($sectionstr eq '') {
 5310:             $$sections{$sectionstr} = 1;
 5311:             $num_sections ++;
 5312:         }
 5313:     }
 5314: 
 5315:     return $num_sections;
 5316: }
 5317: 
 5318: # ========================================================== Custom Role Editor
 5319: 
 5320: sub custom_role_editor {
 5321:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5322:     my $action = $env{'form.customroleaction'};
 5323:     my ($rolename,$helpitem);
 5324:     if ($action eq 'new') {
 5325:         $rolename=$env{'form.newrolename'};
 5326:     } else {
 5327:         $rolename=$env{'form.rolename'};
 5328:     }
 5329: 
 5330:     my ($crstype,$context);
 5331:     if ($env{'request.course.id'}) {
 5332:         $crstype = &Apache::loncommon::course_type();
 5333:         $context = 'course';
 5334:         $helpitem = 'Course_Editing_Custom_Roles';
 5335:     } else {
 5336:         $context = 'domain';
 5337:         $crstype = 'course';
 5338:         $helpitem = 'Domain_Editing_Custom_Roles';
 5339:     }
 5340: 
 5341:     $rolename=~s/[^A-Za-z0-9]//gs;
 5342:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 5343: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 5344:                                    $permission);
 5345:         return;
 5346:     }
 5347: 
 5348:     my $formname = 'form1';
 5349:     my %privs=();
 5350:     my $body_top = '<h2>';
 5351: # ------------------------------------------------------- Does this role exist?
 5352:     my ($rdummy,$roledef)=
 5353: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5354:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5355:         $body_top .= &mt('Existing Role').' "';
 5356: # ------------------------------------------------- Get current role privileges
 5357:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 5358:         if ($privs{'system'} =~ /bre\&S/) {
 5359:             if ($context eq 'domain') {
 5360:                 $crstype = 'Course';
 5361:             } elsif ($crstype eq 'Community') {
 5362:                 $privs{'system'} =~ s/bre\&S//;
 5363:             }
 5364:         } elsif ($context eq 'domain') {
 5365:             $crstype = 'Course';
 5366:         }
 5367:     } else {
 5368:         $body_top .= &mt('New Role').' "';
 5369:         $roledef='';
 5370:     }
 5371:     $body_top .= $rolename.'"</h2>';
 5372: 
 5373: # ------------------------------------------------------- What can be assigned?
 5374:     my %full=();
 5375:     my %levels=(
 5376:                  course => {},
 5377:                  domain => {},
 5378:                  system => {},
 5379:                );
 5380:     my %levelscurrent=(
 5381:                         course => {},
 5382:                         domain => {},
 5383:                         system => {},
 5384:                       );
 5385:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5386:     my ($jsback,$elements) = &crumb_utilities();
 5387:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5388:     my $head_script =
 5389:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 5390:                                                   \%full,\@templateroles,$jsback);
 5391:     push (@{$brcrum},
 5392:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 5393:                text => "Pick custom role",
 5394:                faq  => 282,bug=>'Instructor Interface',},
 5395:               {href => "javascript:backPage(document.$formname,'','')",
 5396:                text => "Edit custom role",
 5397:                faq  => 282,
 5398:                bug  => 'Instructor Interface',
 5399:                help => $helpitem}
 5400:               );
 5401:     my $args = { bread_crumbs          => $brcrum,
 5402:                  bread_crumbs_component => 'User Management'};
 5403:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 5404:                                              $head_script,$args).
 5405:               $body_top);
 5406:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 5407:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 5408:                                                         \@templateroles,$prefix));
 5409: 
 5410:     $r->print(<<ENDCCF);
 5411: <input type="hidden" name="phase" value="set_custom_roles" />
 5412: <input type="hidden" name="rolename" value="$rolename" />
 5413: ENDCCF
 5414:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5415:                                                        \%levelscurrent,$prefix));
 5416:     $r->print(&Apache::loncommon::end_data_table().
 5417:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 5418:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 5419:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 5420:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 5421:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 5422: }
 5423: 
 5424: # ---------------------------------------------------------- Call to definerole
 5425: sub set_custom_role {
 5426:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5427:     my $rolename=$env{'form.rolename'};
 5428:     $rolename=~s/[^A-Za-z0-9]//gs;
 5429:     if (!$rolename) {
 5430: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5431:         return;
 5432:     }
 5433:     my ($jsback,$elements) = &crumb_utilities();
 5434:     my $jscript = '<script type="text/javascript">'
 5435:                  .'// <![CDATA['."\n"
 5436:                  .$jsback."\n"
 5437:                  .'// ]]>'."\n"
 5438:                  .'</script>'."\n";
 5439:     my $helpitem = 'Course_Editing_Custom_Roles';
 5440:     if ($context eq 'domain') {
 5441:         $helpitem = 'Domain_Editing_Custom_Roles';
 5442:     }
 5443:     push(@{$brcrum},
 5444:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 5445:          text => "Pick custom role",
 5446:          faq  => 282,
 5447:          bug  => 'Instructor Interface',},
 5448:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 5449:          text => "Edit custom role",
 5450:          faq  => 282,
 5451:          bug  => 'Instructor Interface',},
 5452:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 5453:          text => "Result",
 5454:          faq  => 282,
 5455:          bug  => 'Instructor Interface',
 5456:          help => $helpitem,}
 5457:         );
 5458:     my $args = { bread_crumbs           => $brcrum,
 5459:                  bread_crumbs_component => 'User Management'};
 5460:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 5461: 
 5462:     my $newrole;
 5463:     my ($rdummy,$roledef)=
 5464: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5465: 
 5466: # ------------------------------------------------------- Does this role exist?
 5467:     $r->print('<h3>');
 5468:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5469: 	$r->print(&mt('Existing Role').' "');
 5470:     } else {
 5471: 	$r->print(&mt('New Role').' "');
 5472: 	$roledef='';
 5473:         $newrole = 1;
 5474:     }
 5475:     $r->print($rolename.'"</h3>');
 5476: # ------------------------------------------------- Assign role and show result
 5477: 
 5478:     my $errmsg;
 5479:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 5480:     # Assign role and return result
 5481:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 5482:                                              $newprivs{'c'});
 5483:     if ($result ne 'ok') {
 5484:         $errmsg = ': '.$result;
 5485:     }
 5486:     my $message =
 5487:         &Apache::lonhtmlcommon::confirm_success(
 5488:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 5489:     if ($env{'request.course.id'}) {
 5490:         my $url='/'.$env{'request.course.id'};
 5491:         $url=~s/\_/\//g;
 5492:         $result =
 5493:             &Apache::lonnet::assigncustomrole(
 5494:                 $env{'user.domain'},$env{'user.name'},
 5495:                 $url,
 5496:                 $env{'user.domain'},$env{'user.name'},
 5497:                 $rolename,undef,undef,undef,$context);
 5498:         if ($result ne 'ok') {
 5499:             $errmsg = ': '.$result;
 5500:         }
 5501:         $message .=
 5502:             '<br />'
 5503:            .&Apache::lonhtmlcommon::confirm_success(
 5504:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 5505:     }
 5506:     $r->print(
 5507:         &Apache::loncommon::confirmwrapper($message)
 5508:        .'<br />'
 5509:        .&Apache::lonhtmlcommon::actionbox([
 5510:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 5511:            .&mt('Create or edit another custom role')
 5512:            .'</a>'])
 5513:        .'<form name="customresult" method="post" action="">'
 5514:        .&Apache::lonhtmlcommon::echo_form_input([])
 5515:        .'</form>'
 5516:     );
 5517: }
 5518: 
 5519: sub show_role_requests {
 5520:     my ($caller,$dom) = @_;
 5521:     my $showrolereqs;
 5522:     my %domconfig = &Apache::lonnet::get_dom('configuration',['privacy'],$dom);
 5523:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 5524:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 5525:             my %approvalconf = %{$domconfig{'privacy'}{'approval'}};
 5526:             foreach my $key ('instdom','extdom') {
 5527:                 if (ref($approvalconf{$key}) eq 'HASH') {
 5528:                     if (keys(%{$approvalconf{$key}})) {
 5529:                         foreach my $context ('domain','author','course','community') {
 5530:                             if ($approvalconf{$key}{$context} eq $caller) {
 5531:                                 $showrolereqs = 1;
 5532:                                 last if ($showrolereqs);
 5533:                             }
 5534:                         }
 5535:                     }
 5536:                 }
 5537:                 last if ($showrolereqs);
 5538:             }
 5539:         }
 5540:     }
 5541:     return $showrolereqs;
 5542: }
 5543: 
 5544: sub display_coauthor_managers {
 5545:     my ($permission) = @_;
 5546:     my $output;
 5547:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5548:         $output = '<form action="/adm/createuser" method="post" name="camanagers">'.
 5549:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5550:                   '<p>';
 5551:         my (@possmanagers,@custommanagers);
 5552:         my %userenv =
 5553:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5554:                                              $env{'user.name'},
 5555:                                              'authormanagers');
 5556:         my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5557:                                                      ['active','future'],['ca']);
 5558:         if (keys(%ca_roles)) {
 5559:             foreach my $entry (sort(keys(%ca_roles))) {
 5560:                 if ($entry =~ /^($match_username\:$match_domain):ca$/) {
 5561:                     my $user = $1;
 5562:                     unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5563:                         push(@possmanagers,$user);
 5564:                     }
 5565:                 }
 5566:             }
 5567:         }
 5568:         if ($userenv{'authormanagers'} eq '') {
 5569:             $output .= &mt('Currently author manages co-author roles');
 5570:         } else {
 5571:             if (keys(%ca_roles)) {
 5572:                 foreach my $user (split(/,/,$userenv{'authormanagers'})) {
 5573:                     if ($user =~ /^($match_username)\:($match_domain)$/) {
 5574:                         if (exists($ca_roles{$user.':ca'})) {
 5575:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5576:                                 push(@custommanagers,$user);
 5577:                             }
 5578:                         }
 5579:                     }
 5580:                 }
 5581:             }
 5582:             if (@custommanagers) {
 5583:                 $output .= &mt('Co-authors with active or future roles who currently manage co-author roles: [_1]',
 5584:                               '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @custommanagers));
 5585:             } else {
 5586:                 $output .= &mt('Currently author manages co-author roles');
 5587:             }
 5588:         }
 5589:         $output .= "</p>\n";
 5590:         if (@possmanagers) {
 5591:             $output .= '<p>'.&mt('If checked, can manage').': ';
 5592:             foreach my $user (@possmanagers) {
 5593:                  my $checked;
 5594:                  if (grep(/^\Q$user\E$/,@custommanagers)) {
 5595:                      $checked = ' checked="checked"';
 5596:                  }
 5597:                  $output .= '<span style="LC_nobreak"><label>'.
 5598:                             '<input type="checkbox" name="custommanagers" '.
 5599:                             'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
 5600:                             &Apache::loncommon::plainname(split(/:/,$user))." ($user)".'</label></span> '."\n";
 5601:             }
 5602:             $output .= '<input type="hidden" name="state" value="process" /></p>'."\n".
 5603:                        '<p><input type="submit" value="'.&mt('Save changes').'" /></p>'."\n";
 5604:         } else {
 5605:             $output .= '<p>'.&mt('No co-author roles assignable as manager').'</p>';
 5606:         }
 5607:         $output .= '</form>';
 5608:     } else {
 5609:         $output = '<span class="LC_warning">'.
 5610:                   &mt('You do not have permission to perform this action').
 5611:                   '</span>';
 5612:     }
 5613:     return $output;
 5614: }
 5615: 
 5616: sub update_coauthor_managers {
 5617:     my ($permission) = @_;
 5618:     my $output;
 5619:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5620:         my ($current,$newval,@possibles,@managers);
 5621:         my %userenv =
 5622:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5623:                                              $env{'user.name'},
 5624:                                              'authormanagers');
 5625:         $current = $userenv{'authormanagers'};
 5626:         @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 5627:         if (@possibles) {
 5628:             my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5629:                                                          ['active','future'],['ca']);
 5630:             if (keys(%ca_roles)) {
 5631:                 foreach my $user (@possibles) {
 5632:                     if ($user =~ /^($match_username):($match_domain)$/) {
 5633:                         if (exists($ca_roles{$user.':ca'})) {
 5634:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5635:                                 push(@managers,$user);
 5636:                             }
 5637:                         }
 5638:                     }
 5639:                 }
 5640:                 if (@managers) {
 5641:                     $newval = join(',',sort(@managers));
 5642:                 }
 5643:             }
 5644:         }
 5645:         if ($current eq $newval) {
 5646:             $output = &mt('No changes made to management of co-author roles');
 5647:         } else {
 5648:             my $chgresult =
 5649:                 &Apache::lonnet::put('environment',{'authormanagers' => $newval},
 5650:                                      $env{'user.domain'},$env{'user.name'});
 5651:             if ($chgresult eq 'ok') {
 5652:                 &Apache::lonnet::appenv({'environment.authormanagers' => $newval});
 5653:                 my (@adds,@dels);
 5654:                 if ($newval eq '') {
 5655:                     @dels = split(/,/,$current);
 5656:                 } elsif ($current eq '') {
 5657:                     @adds = @managers;
 5658:                 } else {
 5659:                     my @old = split(/,/,$current);
 5660:                     my @diffs = &Apache::loncommon::compare_arrays(\@old,\@managers);
 5661:                     if (@diffs) {
 5662:                         foreach my $user (@diffs) {
 5663:                             if (grep(/^\Q$user\E$/,@old)) {
 5664:                                 push(@dels,$user);
 5665:                             } elsif (grep(/^\Q$user\E$/,@managers)) {
 5666:                                 push(@adds,$user);
 5667:                             }
 5668:                         }
 5669:                     }
 5670:                 }
 5671:                 my $key = "internal.manager./$env{'user.domain'}/$env{'user.name'}";
 5672:                 if (@dels) {
 5673:                     foreach my $user (@dels) {
 5674:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5675:                             &Apache::lonnet::del('environment',[$key],$2,$1);
 5676:                         }
 5677:                     }
 5678:                 }
 5679:                 if (@adds) {
 5680:                     foreach my $user (@adds) {
 5681:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5682:                             &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 5683:                         }
 5684:                     }
 5685:                 }
 5686:                 if ($newval eq '') {
 5687:                     $output = &mt('Management of co-authors set to be author-only');
 5688:                 } else {
 5689:                     $output .= &mt('Co-authors who can manage co-author roles set to: [_1]',
 5690:                                    '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @managers));
 5691:                 }
 5692:             }
 5693:         }
 5694:     } else {
 5695:         $output = '<span class="LC_warning">'.
 5696:                   &mt('You do not have permission to perform this action').
 5697:                   '</span>';
 5698:     }
 5699:     return $output;
 5700: }
 5701: 
 5702: # ================================================================ Main Handler
 5703: sub handler {
 5704:     my $r = shift;
 5705:     if ($r->header_only) {
 5706:        &Apache::loncommon::content_type($r,'text/html');
 5707:        $r->send_http_header;
 5708:        return OK;
 5709:     }
 5710:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 5711: 
 5712:     if ($env{'request.course.id'}) {
 5713:         $context = 'course';
 5714:         $crstype = &Apache::loncommon::course_type();
 5715:     } elsif ($env{'request.role'} =~ /^au\./) {
 5716:         $context = 'author';
 5717:     } elsif ($env{'request.role'} =~ m{^(ca|aa)\./$match_domain/$match_username$}) {
 5718:         $context = 'coauthor';
 5719:     } else {
 5720:         $context = 'domain';
 5721:     }
 5722: 
 5723:     my ($permission,$allowed) =
 5724:         &Apache::lonuserutils::get_permission($context,$crstype);
 5725:     if (($context eq 'coauthor') && ($allowed)) {
 5726:         $context = 'author';
 5727:     }
 5728: 
 5729:     if ($allowed) {
 5730:         my @allhelp;
 5731:         if ($context eq 'course') {
 5732:             $cid = $env{'request.course.id'};
 5733:             $cdom = $env{'course.'.$cid.'.domain'};
 5734:             $cnum = $env{'course.'.$cid.'.num'};
 5735: 
 5736:             if ($permission->{'cusr'}) {
 5737:                 push(@allhelp,'Course_Create_Class_List');
 5738:             }
 5739:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5740:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 5741:             }
 5742:             if ($permission->{'custom'}) {
 5743:                 push(@allhelp,'Course_Editing_Custom_Roles');
 5744:             }
 5745:             if ($permission->{'cusr'}) {
 5746:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 5747:             }
 5748:             unless ($permission->{'cusr_section'}) {
 5749:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 5750:                     push(@allhelp,'Course_Automated_Enrollment');
 5751:                 }
 5752:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 5753:                     push(@allhelp,'Course_Approve_Selfenroll');
 5754:                 }
 5755:             }
 5756:             if ($permission->{'grp_manage'}) {
 5757:                 push(@allhelp,'Course_Manage_Group');
 5758:             }
 5759:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5760:                 push(@allhelp,'Course_User_Logs');
 5761:             }
 5762:         } elsif ($context eq 'author') {
 5763:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5764:                            'Author_View_Coauthor_List','Author_User_Logs'));
 5765:         } elsif ($context eq 'coauthor') {
 5766:             if ($permission->{'cusr'}) {
 5767:                 push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5768:                                'Author_View_Coauthor_List','Author_User_Logs'));
 5769:             } elsif ($permission->{'view'}) {
 5770:                 push(@allhelp,'Author_View_Coauthor_List');
 5771:             }
 5772:         } else {
 5773:             if ($permission->{'cusr'}) {
 5774:                 push(@allhelp,'Domain_Change_Privileges');
 5775:                 if ($permission->{'activity'}) {
 5776:                     push(@allhelp,'Domain_User_Access_Logs');
 5777:                 }
 5778:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 5779:                 if ($permission->{'custom'}) {
 5780:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 5781:                 }
 5782:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 5783:             } elsif ($permission->{'view'}) {
 5784:                 push(@allhelp,'Domain_View_Privileges');
 5785:                 if ($permission->{'activity'}) {
 5786:                     push(@allhelp,'Domain_User_Access_Logs');
 5787:                 }
 5788:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 5789:             }
 5790:         }
 5791:         if (@allhelp) {
 5792:             $allhelpitems = join(',',@allhelp);
 5793:         }
 5794:     }
 5795: 
 5796:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5797:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 5798:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue',
 5799:          'forceedit']);
 5800:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5801:     my $args;
 5802:     my $brcrum = [];
 5803:     my $bread_crumbs_component = 'User Management';
 5804:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 5805:         $brcrum = [{href=>"/adm/createuser",
 5806:                     text=>"User Management",
 5807:                     help=>$allhelpitems}
 5808:                   ];
 5809:     }
 5810:     if (!$allowed) {
 5811:         if ($context eq 'course') {
 5812:             $r->internal_redirect('/adm/viewclasslist');
 5813:             return OK;
 5814:         } elsif ($context eq 'coauthor') {
 5815:             $r->internal_redirect('/adm/viewcoauthors');
 5816:             return OK;
 5817:         }
 5818:         $env{'user.error.msg'}=
 5819:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 5820:                                  "or view user status.";
 5821:         return HTTP_NOT_ACCEPTABLE;
 5822:     }
 5823: 
 5824:     &Apache::loncommon::content_type($r,'text/html');
 5825:     $r->send_http_header;
 5826: 
 5827:     my $showcredits;
 5828:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 5829:          ($context eq 'domain')) {
 5830:         my %domdefaults = 
 5831:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 5832:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 5833:             $showcredits = 1;
 5834:         }
 5835:     }
 5836: 
 5837:     # Main switch on form.action and form.state, as appropriate
 5838:     if (! exists($env{'form.action'})) {
 5839:         $args = {bread_crumbs => $brcrum,
 5840:                  bread_crumbs_component => $bread_crumbs_component}; 
 5841:         $r->print(&header(undef,$args));
 5842:         $r->print(&print_main_menu($permission,$context,$crstype));
 5843:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 5844:         my $helpitem = 'Course_Create_Class_List';
 5845:         if ($context eq 'author') {
 5846:             $helpitem = 'Author_Create_Coauthor_List';
 5847:         } elsif ($context eq 'domain') {
 5848:             $helpitem = 'Domain_Create_Users';
 5849:         }
 5850:         push(@{$brcrum},
 5851:               { href => '/adm/createuser?action=upload&state=',
 5852:                 text => 'Upload Users List',
 5853:                 help => $helpitem,
 5854:               });
 5855:         $bread_crumbs_component = 'Upload Users List';
 5856:         $args = {bread_crumbs           => $brcrum,
 5857:                  bread_crumbs_component => $bread_crumbs_component};
 5858:         $r->print(&header(undef,$args));
 5859:         $r->print('<form name="studentform" method="post" '.
 5860:                   'enctype="multipart/form-data" '.
 5861:                   ' action="/adm/createuser">'."\n");
 5862:         if (! exists($env{'form.state'})) {
 5863:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5864:         } elsif ($env{'form.state'} eq 'got_file') {
 5865:             my $result = 
 5866:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 5867:                                                                  $permission,
 5868:                                                                  $crstype,$showcredits);
 5869:             if ($result eq 'missingdata') {
 5870:                 delete($env{'form.state'});
 5871:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5872:             }
 5873:         } elsif ($env{'form.state'} eq 'enrolling') {
 5874:             if ($env{'form.datatoken'}) {
 5875:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 5876:                                                                     $permission,
 5877:                                                                     $showcredits);
 5878:                 if ($result eq 'missingdata') {
 5879:                     delete($env{'form.state'});
 5880:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5881:                 } elsif ($result eq 'invalidhome') {
 5882:                     $env{'form.state'} = 'got_file';
 5883:                     delete($env{'form.lcserver'});
 5884:                     my $result =
 5885:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 5886:                                                                          $crstype,$showcredits);
 5887:                     if ($result eq 'missingdata') {
 5888:                         delete($env{'form.state'});
 5889:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5890:                     }
 5891:                 }
 5892:             } else {
 5893:                 delete($env{'form.state'});
 5894:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5895:             }
 5896:         } else {
 5897:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5898:         }
 5899:         $r->print('</form>');
 5900:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 5901:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 5902:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 5903:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 5904:         my $phase = $env{'form.phase'};
 5905:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 5906: 	&Apache::loncreateuser::restore_prev_selections();
 5907: 	my $srch;
 5908: 	foreach my $item (@search) {
 5909: 	    $srch->{$item} = $env{'form.'.$item};
 5910: 	}
 5911:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 5912:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 5913:             if ($env{'form.phase'} eq 'createnewuser') {
 5914:                 my $response;
 5915:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 5916:                     my $response =
 5917:                         '<span class="LC_warning">'
 5918:                        .&mt('You must specify a valid username. Only the following are allowed:'
 5919:                            .' letters numbers - . @')
 5920:                        .'</span>';
 5921:                     $env{'form.phase'} = '';
 5922:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 5923:                                                $crstype,$brcrum,$permission);
 5924:                 } else {
 5925:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 5926:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 5927:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 5928:                                                   $srch,$response,$context,
 5929:                                                   $permission,$crstype,$brcrum,
 5930:                                                   $showcredits);
 5931:                 }
 5932:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 5933:                 my ($currstate,$response,$forcenewuser,$results) = 
 5934:                     &user_search_result($context,$srch);
 5935:                 if ($env{'form.currstate'} eq 'modify') {
 5936:                     $currstate = $env{'form.currstate'};
 5937:                 }
 5938:                 if ($currstate eq 'select') {
 5939:                     &print_user_selection_page($r,$response,$srch,$results,
 5940:                                                \@search,$context,undef,$crstype,
 5941:                                                $brcrum);
 5942:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 5943:                     my ($ccuname,$ccdomain,$uhome);
 5944:                     if (($srch->{'srchby'} eq 'uname') && 
 5945:                         ($srch->{'srchtype'} eq 'exact')) {
 5946:                         $ccuname = $srch->{'srchterm'};
 5947:                         $ccdomain= $srch->{'srchdomain'};
 5948:                     } else {
 5949:                         my @matchedunames = keys(%{$results});
 5950:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 5951:                     }
 5952:                     $ccuname =&LONCAPA::clean_username($ccuname);
 5953:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 5954:                     if ($env{'form.action'} eq 'accesslogs') {
 5955:                         my $uhome;
 5956:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 5957:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 5958:                         }
 5959:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 5960:                             $env{'form.phase'} = '';
 5961:                             undef($forcenewuser);
 5962:                             #if ($response) {
 5963:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 5964:                             #        $response .= '<br /><br />';
 5965:                             #    }
 5966:                             #}
 5967:                             &print_username_entry_form($r,$context,$response,$srch,
 5968:                                                        $forcenewuser,$crstype,$brcrum,
 5969:                                                        $permission);
 5970:                         } else {
 5971:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5972:                         }
 5973:                     } else {
 5974:                         if ($env{'form.forcenewuser'}) {
 5975:                             $response = '';
 5976:                         }
 5977:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 5978:                                                       $srch,$response,$context,
 5979:                                                       $permission,$crstype,$brcrum);
 5980:                     }
 5981:                 } elsif ($currstate eq 'query') {
 5982:                     &print_user_query_page($r,'createuser',$brcrum);
 5983:                 } else {
 5984:                     $env{'form.phase'} = '';
 5985:                     &print_username_entry_form($r,$context,$response,$srch,
 5986:                                                $forcenewuser,$crstype,$brcrum,
 5987:                                                $permission);
 5988:                 }
 5989:             } elsif ($env{'form.phase'} eq 'userpicked') {
 5990:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 5991:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 5992:                 if ($env{'form.action'} eq 'accesslogs') {
 5993:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5994:                 } else {
 5995:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 5996:                                                   $context,$permission,$crstype,
 5997:                                                   $brcrum);
 5998:                 }
 5999:             } elsif ($env{'form.action'} eq 'accesslogs') {
 6000:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 6001:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 6002:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 6003:             }
 6004:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 6005:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 6006:         } else {
 6007:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 6008:                                        $brcrum,$permission);
 6009:         }
 6010:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 6011:         my $prefix;
 6012:         if ($env{'form.phase'} eq 'set_custom_roles') {
 6013:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 6014:         } else {
 6015:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 6016:         }
 6017:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 6018:              ($permission->{'cusr'}) && 
 6019:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 6020:         push(@{$brcrum},
 6021:                  {href => '/adm/createuser?action=processauthorreq',
 6022:                   text => 'Authoring Space requests',
 6023:                   help => 'Domain_Role_Approvals'});
 6024:         $bread_crumbs_component = 'Authoring requests';
 6025:         if ($env{'form.state'} eq 'done') {
 6026:             push(@{$brcrum},
 6027:                      {href => '/adm/createuser?action=authorreqqueue',
 6028:                       text => 'Result',
 6029:                       help => 'Domain_Role_Approvals'});
 6030:             $bread_crumbs_component = 'Authoring request result';
 6031:         }
 6032:         $args = { bread_crumbs           => $brcrum,
 6033:                   bread_crumbs_component => $bread_crumbs_component};
 6034:         my $js = &usernamerequest_javascript();
 6035:         $r->print(&header(&add_script($js),$args));
 6036:         if (!exists($env{'form.state'})) {
 6037:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 6038:                                                                             $env{'request.role.domain'}));
 6039:         } elsif ($env{'form.state'} eq 'done') {
 6040:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 6041:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 6042:                                                                          $env{'request.role.domain'}));
 6043:         }
 6044:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 6045:              ($permission->{'cusr'}) &&
 6046:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 6047:         push(@{$brcrum},
 6048:                  {href => '/adm/createuser?action=processusernamereq',
 6049:                   text => 'LON-CAPA account requests',
 6050:                   help => 'Domain_Username_Approvals'});
 6051:         $bread_crumbs_component = 'Account requests';
 6052:         if ($env{'form.state'} eq 'done') {
 6053:             push(@{$brcrum},
 6054:                      {href => '/adm/createuser?action=usernamereqqueue',
 6055:                       text => 'Result',
 6056:                       help => 'Domain_Username_Approvals'});
 6057:             $bread_crumbs_component = 'LON-CAPA account request result';
 6058:         }
 6059:         $args = { bread_crumbs           => $brcrum,
 6060:                   bread_crumbs_component => $bread_crumbs_component};
 6061:         my $js = &usernamerequest_javascript();
 6062:         $r->print(&header(&add_script($js),$args));
 6063:         if (!exists($env{'form.state'})) {
 6064:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 6065:                                                                             $env{'request.role.domain'}));
 6066:         } elsif ($env{'form.state'} eq 'done') {
 6067:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 6068:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 6069:                                                                          $env{'request.role.domain'}));
 6070:         }
 6071:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 6072:              ($permission->{'cusr'})) {
 6073:         my $dom = $env{'form.domain'};
 6074:         my $uname = $env{'form.username'};
 6075:         my $warning;
 6076:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 6077:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 6078:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 6079:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 6080:                     if ($uhome eq 'no_host') {
 6081:                         my $queue = $env{'form.queue'};
 6082:                         my $reqkey = &escape($uname).'_'.$queue; 
 6083:                         my $namespace = 'usernamequeue';
 6084:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 6085:                         my %queued =
 6086:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 6087:                         unless ($queued{$reqkey}) {
 6088:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 6089:                         }
 6090:                     } else {
 6091:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 6092:                     }
 6093:                 } else {
 6094:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 6095:                 }
 6096:             } else {
 6097:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 6098:             }
 6099:         } else {
 6100:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 6101:         }
 6102:         my $args = { only_body => 1 };
 6103:         $r->print(&header(undef,$args).
 6104:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 6105:         if ($warning ne '') {
 6106:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 6107:         } else {
 6108:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 6109:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 6110:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6111:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6112:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 6113:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 6114:                         my %info =
 6115:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 6116:                         if (ref($info{$uname}) eq 'HASH') {
 6117:                             my $usertype = $info{$uname}{'inststatus'};
 6118:                             unless ($usertype) {
 6119:                                 $usertype = 'default';
 6120:                             }
 6121:                             my ($showstatus,$showemail,$pickstart);
 6122:                             my $numextras = 0;
 6123:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6124:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 6125:                                 if (ref($usertypes) eq 'HASH') {
 6126:                                     if ($usertypes->{$usertype}) {
 6127:                                         $showstatus = $usertypes->{$usertype};
 6128:                                     } else {
 6129:                                         $showstatus = $othertitle;
 6130:                                     }
 6131:                                     if ($showstatus) {
 6132:                                         $numextras ++;
 6133:                                     }
 6134:                                 }
 6135:                             }
 6136:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 6137:                                 $showemail = $info{$uname}{'email'};
 6138:                                 $numextras ++;
 6139:                             }
 6140:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 6141:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 6142:                                     $pickstart = 1;
 6143:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6144:                                     my ($num,$count);
 6145:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 6146:                                     $count += $numextras;
 6147:                                     foreach my $field (@{$infofields}) {
 6148:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 6149:                                         next unless ($infotitles->{$field});
 6150:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 6151:                                                   $info{$uname}{$field});
 6152:                                         $num ++;
 6153:                                         unless ($count == $num) {
 6154:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 6155:                                         }
 6156:                                     }
 6157:                                 }
 6158:                             }
 6159:                             if ($numextras) {
 6160:                                 unless ($pickstart) {
 6161:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6162:                                     $pickstart = 1;
 6163:                                 }
 6164:                                 if ($showemail) {
 6165:                                     my $closure = '';
 6166:                                     unless ($showstatus) {
 6167:                                         $closure = 1;
 6168:                                     }
 6169:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 6170:                                               $showemail.
 6171:                                               &Apache::lonhtmlcommon::row_closure($closure));
 6172:                                 }
 6173:                                 if ($showstatus) {
 6174:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 6175:                                               $showstatus.
 6176:                                               &Apache::lonhtmlcommon::row_closure(1));
 6177:                                 }
 6178:                             }
 6179:                             if ($pickstart) { 
 6180:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 6181:                             } else {
 6182:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 6183:                             }
 6184:                         } else {
 6185:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 6186:                         }
 6187:                     }
 6188:                 }
 6189:             }
 6190:         }
 6191:         $r->print(&close_popup_form());
 6192:     } elsif (($env{'form.action'} eq 'listusers') && 
 6193:              ($permission->{'view'} || $permission->{'cusr'})) {
 6194:         my $helpitem = 'Course_View_Class_List';
 6195:         if ($context eq 'author') {
 6196:             $helpitem = 'Author_View_Coauthor_List';
 6197:         } elsif ($context eq 'domain') {
 6198:             $helpitem = 'Domain_View_Users_List';
 6199:         }
 6200:         if ($env{'form.phase'} eq 'bulkchange') {
 6201:             push(@{$brcrum},
 6202:                     {href => '/adm/createuser?action=listusers',
 6203:                      text => "List Users"},
 6204:                     {href => "/adm/createuser",
 6205:                      text => "Result",
 6206:                      help => $helpitem});
 6207:             $bread_crumbs_component = 'Update Users';
 6208:             $args = {bread_crumbs           => $brcrum,
 6209:                      bread_crumbs_component => $bread_crumbs_component};
 6210:             $r->print(&header(undef,$args));
 6211:             my $setting = $env{'form.roletype'};
 6212:             my $choice = $env{'form.bulkaction'};
 6213:             if ($permission->{'cusr'}) {
 6214:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 6215:             } else {
 6216:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 6217:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 6218:             }
 6219:         } else {
 6220:             push(@{$brcrum},
 6221:                     {href => '/adm/createuser?action=listusers',
 6222:                      text => "List Users",
 6223:                      help => $helpitem});
 6224:             $bread_crumbs_component = 'List Users';
 6225:             $args = {bread_crumbs           => $brcrum,
 6226:                      bread_crumbs_component => $bread_crumbs_component};
 6227:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 6228:             my $formname = 'studentform';
 6229:             my $hidecall = "hide_searching();";
 6230:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 6231:                 ($env{'form.roletype'} eq 'community'))) {
 6232:                 if ($env{'form.roletype'} eq 'course') {
 6233:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 6234:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 6235:                                                                 $formname);
 6236:                 } elsif ($env{'form.roletype'} eq 'community') {
 6237:                     $cb_jscript = 
 6238:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 6239:                     my %elements = (
 6240:                                       coursepick => 'radio',
 6241:                                       coursetotal => 'text',
 6242:                                       courselist => 'text',
 6243:                                    );
 6244:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 6245:                 }
 6246:                 $jscript .= &verify_user_display($context)."\n".
 6247:                             &Apache::loncommon::check_uncheck_jscript();
 6248:                 my $js = &add_script($jscript).$cb_jscript;
 6249:                 my $loadcode = 
 6250:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 6251:                 if ($loadcode ne '') {
 6252:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 6253:                 } else {
 6254:                     $args->{add_entries} = {onload => $hidecall};
 6255:                 }
 6256:                 $r->print(&header($js,$args));
 6257:             } else {
 6258:                 $args->{add_entries} = {onload => $hidecall};
 6259:                 $jscript = &verify_user_display($context).
 6260:                            &Apache::loncommon::check_uncheck_jscript(); 
 6261:                 $r->print(&header(&add_script($jscript),$args));
 6262:             }
 6263:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 6264:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 6265:                          $showcredits);
 6266:         }
 6267:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 6268:         my $brtext;
 6269:         if ($crstype eq 'Community') {
 6270:             $brtext = 'Drop Members';
 6271:         } else {
 6272:             $brtext = 'Drop Students';
 6273:         }
 6274:         push(@{$brcrum},
 6275:                 {href => '/adm/createuser?action=drop',
 6276:                  text => $brtext,
 6277:                  help => 'Course_Drop_Student'});
 6278:         if ($env{'form.state'} eq 'done') {
 6279:             push(@{$brcrum},
 6280:                      {href=>'/adm/createuser?action=drop',
 6281:                       text=>"Result"});
 6282:         }
 6283:         $bread_crumbs_component = $brtext;
 6284:         $args = {bread_crumbs           => $brcrum,
 6285:                  bread_crumbs_component => $bread_crumbs_component}; 
 6286:         $r->print(&header(undef,$args));
 6287:         if (!exists($env{'form.state'})) {
 6288:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 6289:         } elsif ($env{'form.state'} eq 'done') {
 6290:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 6291:                                                     $env{'form.action'});
 6292:         }
 6293:     } elsif ($env{'form.action'} eq 'dateselect') {
 6294:         if ($permission->{'cusr'}) {
 6295:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6296:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 6297:                                                                    $crstype,$showcredits));
 6298:         } else {
 6299:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6300:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 6301:         }
 6302:     } elsif ($env{'form.action'} eq 'selfenroll') {
 6303:         my %currsettings;
 6304:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 6305:             %currsettings = (
 6306:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 6307:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 6308:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 6309:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 6310:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 6311:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 6312:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 6313:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 6314:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 6315:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 6316:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 6317:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 6318:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 6319:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 6320:             );
 6321:         }
 6322:         if ($permission->{selfenrolladmin}) {
 6323:             push(@{$brcrum},
 6324:                     {href => '/adm/createuser?action=selfenroll',
 6325:                      text => "Configure Self-enrollment",
 6326:                      help => 'Course_Self_Enrollment'});
 6327:             if (!exists($env{'form.state'})) {
 6328:                 $args = { bread_crumbs           => $brcrum,
 6329:                           bread_crumbs_component => 'Configure Self-enrollment'};
 6330:                 $r->print(&header(undef,$args));
 6331:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6332:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 6333:             } elsif ($env{'form.state'} eq 'done') {
 6334:                 push (@{$brcrum},
 6335:                           {href=>'/adm/createuser?action=selfenroll',
 6336:                            text=>"Result"});
 6337:                 $args = { bread_crumbs           => $brcrum,
 6338:                           bread_crumbs_component => 'Self-enrollment result'};
 6339:                 $r->print(&header(undef,$args));
 6340:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6341:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 6342:             }
 6343:         } elsif ($permission->{selfenrollview}) {
 6344:             push(@{$brcrum},
 6345:                     {href => '/adm/createuser?action=selfenroll',
 6346:                      text => "View Self-enrollment configuration",
 6347:                      help => 'Course_Self_Enrollment'});
 6348:             $args = { bread_crumbs           => $brcrum,
 6349:                       bread_crumbs_component => 'Self-enrollment Settings'};
 6350:             $r->print(&header(undef,$args));
 6351:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6352:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 6353:         } else {
 6354:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6355:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 6356:         }
 6357:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 6358:         if ($permission->{selfenrolladmin}) {
 6359:             push(@{$brcrum},
 6360:                      {href => '/adm/createuser?action=selfenrollqueue',
 6361:                       text => 'Enrollment requests',
 6362:                       help => 'Course_Approve_Selfenroll'});
 6363:             $bread_crumbs_component = 'Enrollment requests';
 6364:             if ($env{'form.state'} eq 'done') {
 6365:                 push(@{$brcrum},
 6366:                          {href => '/adm/createuser?action=selfenrollqueue',
 6367:                           text => 'Result',
 6368:                           help => 'Course_Approve_Selfenroll'});
 6369:                 $bread_crumbs_component = 'Enrollment result';
 6370:             }
 6371:             $args = { bread_crumbs           => $brcrum,
 6372:                       bread_crumbs_component => $bread_crumbs_component};
 6373:             $r->print(&header(undef,$args));
 6374:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6375:             if (!exists($env{'form.state'})) {
 6376:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 6377:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 6378:                                                                                 $cdom,$cnum));
 6379:             } elsif ($env{'form.state'} eq 'done') {
 6380:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 6381:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 6382:                               $cdom,$cnum,$coursedesc));
 6383:             }
 6384:         } else {
 6385:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6386:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 6387:         }
 6388:     } elsif ($env{'form.action'} eq 'changelogs') {
 6389:         if ($permission->{cusr} || $permission->{view}) {
 6390:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 6391:         } else {
 6392:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6393:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 6394:         }
 6395:     } elsif ($env{'form.action'} eq 'helpdesk') {
 6396:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6397:             ($permission->{'cusr'} || $permission->{'view'})) {
 6398:             if ($env{'form.state'} eq 'process') {
 6399:                 if ($permission->{'owner'}) {
 6400:                     &update_helpdeskaccess($r,$permission,$brcrum);
 6401:                 } else {
 6402:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 6403:                 }
 6404:             } else {
 6405:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 6406:             }
 6407:         } else {
 6408:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6409:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 6410:         }
 6411:     } elsif ($env{'form.action'} eq 'rolerequests') {
 6412:         if ($permission->{cusr} || $permission->{view}) {
 6413:             &print_queued_roles($r,$context,$permission,$brcrum);
 6414:         }
 6415:     } elsif ($env{'form.action'} eq 'queuedroles') {
 6416:         if (($permission->{cusr}) && ($context eq 'domain')) {
 6417:             if (&show_role_requests($context,$env{'request.role.domain'})) {
 6418:                 if ($env{'form.state'} eq 'done') {
 6419:                     &process_pendingroles($r,$context,$permission,$brcrum);
 6420:                 } else {
 6421:                     &print_pendingroles($r,$context,$permission,$brcrum);
 6422:                 }
 6423:             } else {
 6424:                 $r->print(&header(undef,{'no_nav_bar' => 1}).
 6425:                           '<span class="LC_info">'.&mt('Domain coordinator approval of requests from other domains for assignment of roles to users from this domain not in use.').'</span>');
 6426:             }
 6427:         } else {
 6428:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6429:                      '<span class="LC_error">'.&mt('You do not have permission to view queued requests from other domains for assignment of roles to users from this domain.').'</span>');
 6430:         }
 6431:     } elsif ($env{'form.action'} eq 'camanagers') {
 6432:         if (($permission->{cusr}) && ($context eq 'author')) {
 6433:             push(@{$brcrum},
 6434:                      {href => '/adm/createuser?action=camanagers',
 6435:                       text => 'Co-author Managers',
 6436:                       help => 'Author_Manage_Coauthors'});
 6437:             if ($env{'form.state'} eq 'process') {
 6438:                 push(@{$brcrum},
 6439:                          {href => '/adm/createuser?action=camanagers',
 6440:                           text => 'Result',
 6441:                           help => 'Author_Manage_Coauthors'});
 6442:             }
 6443:             $args = { bread_crumbs           => $brcrum };
 6444:             $r->print(&header(undef,$args));
 6445:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6446:             if (!exists($env{'form.state'})) {
 6447:                 $r->print('<h3>'.&mt('Co-author Management').'</h3>'."\n".
 6448:                           &display_coauthor_managers($permission));
 6449:             } elsif ($env{'form.state'} eq 'process') {
 6450:                 $r->print('<h3>'.&mt('Co-author Management Update Result').'</h3>'."\n".
 6451:                           &update_coauthor_managers($permission));
 6452:             }
 6453:         }
 6454:     } elsif (($env{'form.action'} eq 'calist') && ($context eq 'author')) {
 6455:         if ($permission->{'cusr'}) {
 6456:             my ($role,$audom,$auname,$canview,$canedit) =
 6457:                 &Apache::lonviewcoauthors::get_allowable();
 6458:             if (($canedit) && ($env{'form.forceedit'})) {
 6459:                 &Apache::lonviewcoauthors::get_editor_crumbs($brcrum,'/adm/createuser');
 6460:                 my $args = { 'bread_crumbs' => $brcrum };
 6461:                 $r->print(&Apache::loncommon::start_page('Configure co-author listing',undef,
 6462:                                                          $args).
 6463:                           &Apache::lonviewcoauthors::edit_settings($audom,$auname,$role,
 6464:                                                                    '/adm/createuser'));
 6465:             } else {
 6466:                 push(@{$brcrum},
 6467:                        {href => '/adm/createuser?action=calist',
 6468:                         text => 'Coauthor-viewable list',
 6469:                         help => 'Author_List_Coauthors'});
 6470:                 my $args = { 'bread_crumbs' => $brcrum };
 6471:                 $r->print(&Apache::loncommon::start_page('Coauthor-viewable list',undef,
 6472:                                                          $args));
 6473:                 my %viewsettings =
 6474:                     &Apache::lonviewcoauthors::retrieve_view_settings($auname,$audom,$role);
 6475:                 if ($viewsettings{'show'} eq 'none') {
 6476:                     $r->print('<h3>'.&mt('Coauthor-viewable listing').'</h3>'.
 6477:                               '<p class="LC_info">'.
 6478:                               &mt('Listing of co-authors not enabled for this Authoring Space').
 6479:                               '</p>');
 6480:                 } else {
 6481:                     &Apache::lonviewcoauthors::print_coauthors($r,$auname,$audom,$role,
 6482:                                                                '/adm/createuser',\%viewsettings);
 6483:                 }
 6484:             }
 6485:         } else {
 6486:             $r->internal_redirect('/adm/viewcoauthors');
 6487:             return OK;
 6488:         }
 6489:     } else {
 6490:         $bread_crumbs_component = 'User Management';
 6491:         $args = { bread_crumbs           => $brcrum,
 6492:                   bread_crumbs_component => $bread_crumbs_component};
 6493:         $r->print(&header(undef,$args));
 6494:         $r->print(&print_main_menu($permission,$context,$crstype));
 6495:     }
 6496:     $r->print(&Apache::loncommon::end_page());
 6497:     return OK;
 6498: }
 6499: 
 6500: sub header {
 6501:     my ($jscript,$args) = @_;
 6502:     my $start_page;
 6503:     if (ref($args) eq 'HASH') {
 6504:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 6505:     } else {
 6506:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 6507:     }
 6508:     return $start_page;
 6509: }
 6510: 
 6511: sub add_script {
 6512:     my ($js) = @_;
 6513:     return '<script type="text/javascript">'."\n"
 6514:           .'// <![CDATA['."\n"
 6515:           .$js."\n"
 6516:           .'// ]]>'."\n"
 6517:           .'</script>'."\n";
 6518: }
 6519: 
 6520: sub usernamerequest_javascript {
 6521:     my $js = <<ENDJS;
 6522: 
 6523: function openusernamereqdisplay(dom,uname,queue) {
 6524:     var url = '/adm/createuser?action=displayuserreq';
 6525:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 6526:     var title = 'Account_Request_Browser';
 6527:     var options = 'scrollbars=1,resizable=1,menubar=0';
 6528:     options += ',width=700,height=600';
 6529:     var stdeditbrowser = open(url,title,options,'1');
 6530:     stdeditbrowser.focus();
 6531:     return;
 6532: }
 6533:  
 6534: ENDJS
 6535: }
 6536: 
 6537: sub close_popup_form {
 6538:     my $close= &mt('Close Window');
 6539:     return << "END";
 6540: <p><form name="displayreq" action="" method="post">
 6541: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 6542: </form></p>
 6543: END
 6544: }
 6545: 
 6546: sub verify_user_display {
 6547:     my ($context) = @_;
 6548:     my %lt = &Apache::lonlocal::texthash (
 6549:         course    => 'course(s): description, section(s), status',
 6550:         community => 'community(s): description, section(s), status',
 6551:         author    => 'author',
 6552:     );
 6553:     my $photos;
 6554:     if (($context eq 'course') && $env{'request.course.id'}) {
 6555:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 6556:     }
 6557:     my $output = <<"END";
 6558: 
 6559: function hide_searching() {
 6560:     if (document.getElementById('searching')) {
 6561:         document.getElementById('searching').style.display = 'none';
 6562:     }
 6563:     return;
 6564: }
 6565: 
 6566: function display_update() {
 6567:     document.studentform.action.value = 'listusers';
 6568:     document.studentform.phase.value = 'display';
 6569:     document.studentform.submit();
 6570: }
 6571: 
 6572: function updateCols(caller) {
 6573:     var context = '$context';
 6574:     var photos = '$photos';
 6575:     if (caller == 'Status') {
 6576:         if ((context == 'domain') && 
 6577:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6578:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 6579:             document.getElementById('showcolstatus').checked = false;
 6580:             document.getElementById('showcolstatus').disabled = 'disabled';
 6581:             document.getElementById('showcolstart').checked = false;
 6582:             document.getElementById('showcolend').checked = false;
 6583:         } else {
 6584:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6585:                 document.getElementById('showcolstatus').checked = true;
 6586:                 document.getElementById('showcolstatus').disabled = '';
 6587:                 document.getElementById('showcolstart').checked = true;
 6588:                 document.getElementById('showcolend').checked = true;
 6589:             } else {
 6590:                 document.getElementById('showcolstatus').checked = false;
 6591:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6592:                 document.getElementById('showcolstart').checked = false;
 6593:                 document.getElementById('showcolend').checked = false;
 6594:             }
 6595:             if (context == 'author') {
 6596:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Expired') {
 6597:                     document.getElementById('showcolmanager').checked = false;
 6598:                     document.getElementById('showcolmanager').disabled = 'disabled';
 6599:                 } else if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value != 'aa') {
 6600:                     document.getElementById('showcolmanager').checked = true;
 6601:                     document.getElementById('showcolmanager').disabled = '';
 6602:                 }
 6603:             }
 6604:         }
 6605:     }
 6606:     if (caller == 'output') {
 6607:         if (photos == 1) {
 6608:             if (document.getElementById('showcolphoto')) {
 6609:                 var photoitem = document.getElementById('showcolphoto');
 6610:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 6611:                     photoitem.checked = true;
 6612:                     photoitem.disabled = '';
 6613:                 } else {
 6614:                     photoitem.checked = false;
 6615:                     photoitem.disabled = 'disabled';
 6616:                 }
 6617:             }
 6618:         }
 6619:     }
 6620:     if (caller == 'showrole') {
 6621:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 6622:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 6623:             document.getElementById('showcolrole').checked = true;
 6624:             document.getElementById('showcolrole').disabled = '';
 6625:         } else {
 6626:             document.getElementById('showcolrole').checked = false;
 6627:             document.getElementById('showcolrole').disabled = 'disabled';
 6628:         }
 6629:         if (context == 'domain') {
 6630:             var quotausageshow = 0;
 6631:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6632:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 6633:                 document.getElementById('showcolstatus').checked = false;
 6634:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6635:                 document.getElementById('showcolstart').checked = false;
 6636:                 document.getElementById('showcolend').checked = false;
 6637:             } else {
 6638:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6639:                     document.getElementById('showcolstatus').checked = true;
 6640:                     document.getElementById('showcolstatus').disabled = '';
 6641:                     document.getElementById('showcolstart').checked = true;
 6642:                     document.getElementById('showcolend').checked = true;
 6643:                 }
 6644:             }
 6645:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 6646:                 document.getElementById('showcolextent').disabled = 'disabled';
 6647:                 document.getElementById('showcolextent').checked = 'false';
 6648:                 document.getElementById('showextent').style.display='none';
 6649:                 document.getElementById('showcoltextextent').innerHTML = '';
 6650:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 6651:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 6652:                     if (document.getElementById('showcolauthorusage')) {
 6653:                         document.getElementById('showcolauthorusage').disabled = '';
 6654:                     }
 6655:                     if (document.getElementById('showcolauthorquota')) {
 6656:                         document.getElementById('showcolauthorquota').disabled = '';
 6657:                     }
 6658:                     quotausageshow = 1;
 6659:                 }
 6660:             } else {
 6661:                 document.getElementById('showextent').style.display='block';
 6662:                 document.getElementById('showextent').style.textAlign='left';
 6663:                 document.getElementById('showextent').style.textFace='normal';
 6664:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 6665:                     document.getElementById('showcolextent').disabled = '';
 6666:                     document.getElementById('showcolextent').checked = 'true';
 6667:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 6668:                 } else {
 6669:                     document.getElementById('showcolextent').disabled = '';
 6670:                     document.getElementById('showcolextent').checked = 'true';
 6671:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 6672:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 6673:                     } else {
 6674:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 6675:                     }
 6676:                 }
 6677:             }
 6678:             if (quotausageshow == 0)  {
 6679:                 if (document.getElementById('showcolauthorusage')) {
 6680:                     document.getElementById('showcolauthorusage').checked = false;
 6681:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 6682:                 }
 6683:                 if (document.getElementById('showcolauthorquota')) {
 6684:                     document.getElementById('showcolauthorquota').checked = false;
 6685:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 6686:                 }
 6687:             }
 6688:         }
 6689:         if (context == 'author') {
 6690:             if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'aa') {
 6691:                 document.getElementById('showcolmanager').checked = false;
 6692:                 document.getElementById('showcolmanager').disabled = 'disabled';
 6693:             } else if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value != 'Expired') {
 6694:                 document.getElementById('showcolmanager').checked = true;
 6695:                 document.getElementById('showcolmanager').disabled = '';
 6696:             }
 6697:         }
 6698:     }
 6699:     return;
 6700: }
 6701: 
 6702: END
 6703:     return $output;
 6704: 
 6705: }
 6706: 
 6707: ###############################################################
 6708: ###############################################################
 6709: #  Menu Phase One
 6710: sub print_main_menu {
 6711:     my ($permission,$context,$crstype) = @_;
 6712:     my $linkcontext = $context;
 6713:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 6714:     if (($context eq 'course') && ($crstype eq 'Community')) {
 6715:         $linkcontext = lc($crstype);
 6716:         $stuterm = 'Members';
 6717:     }
 6718:     my %links = (
 6719:                 domain => {
 6720:                             upload     => 'Upload a File of Users',
 6721:                             singleuser => 'Add/Modify a User',
 6722:                             listusers  => 'Manage Users',
 6723:                             },
 6724:                 author => {
 6725:                             upload     => 'Upload a File of Co-authors',
 6726:                             singleuser => 'Add/Modify a Co-author',
 6727:                             listusers  => 'Manage Co-authors',
 6728:                             },
 6729:                 course => {
 6730:                             upload     => 'Upload a File of Course Users',
 6731:                             singleuser => 'Add/Modify a Course User',
 6732:                             listusers  => 'List and Modify Multiple Course Users',
 6733:                             },
 6734:                 community => {
 6735:                             upload     => 'Upload a File of Community Users',
 6736:                             singleuser => 'Add/Modify a Community User',
 6737:                             listusers  => 'List and Modify Multiple Community Users',
 6738:                            },
 6739:                 );
 6740:      my %linktitles = (
 6741:                 domain => {
 6742:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 6743:                             listusers  => 'Show and manage users in this domain.',
 6744:                             },
 6745:                 author => {
 6746:                             singleuser => 'Add a user with a co- or assistant author role.',
 6747:                             listusers  => 'Show and manage co- or assistant authors.',
 6748:                             },
 6749:                 course => {
 6750:                             singleuser => 'Add a user with a certain role to this course.',
 6751:                             listusers  => 'Show and manage users in this course.',
 6752:                             },
 6753:                 community => {
 6754:                             singleuser => 'Add a user with a certain role to this community.',
 6755:                             listusers  => 'Show and manage users in this community.',
 6756:                            },
 6757:                 );
 6758: 
 6759:   if ($linkcontext eq 'domain') {
 6760:       unless ($permission->{'cusr'}) {
 6761:           $links{'domain'}{'singleuser'} = 'View a User';
 6762:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 6763:       }
 6764:   } elsif ($linkcontext eq 'course') {
 6765:       unless ($permission->{'cusr'}) {
 6766:           $links{'course'}{'singleuser'} = 'View a Course User';
 6767:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 6768:           $links{'course'}{'listusers'} = 'List Course Users';
 6769:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 6770:       }
 6771:   } elsif ($linkcontext eq 'community') {
 6772:       unless ($permission->{'cusr'}) {
 6773:           $links{'community'}{'singleuser'} = 'View a Community User';
 6774:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 6775:           $links{'community'}{'listusers'} = 'List Community Users';
 6776:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 6777:       }
 6778:   }
 6779:   my @menu = ( {categorytitle => 'Single Users', 
 6780:          items =>
 6781:          [
 6782:             {
 6783:              linktext => $links{$linkcontext}{'singleuser'},
 6784:              icon => 'edit-redo.png',
 6785:              #help => 'Course_Change_Privileges',
 6786:              url => '/adm/createuser?action=singleuser',
 6787:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6788:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 6789:             },
 6790:          ]},
 6791: 
 6792:          {categorytitle => 'Multiple Users',
 6793:          items => 
 6794:          [
 6795:             {
 6796:              linktext => $links{$linkcontext}{'upload'},
 6797:              icon => 'uplusr.png',
 6798:              #help => 'Course_Create_Class_List',
 6799:              url => '/adm/createuser?action=upload',
 6800:              permission => $permission->{'cusr'},
 6801:              linktitle => 'Upload a CSV or a text file containing users.',
 6802:             },
 6803:             {
 6804:              linktext => $links{$linkcontext}{'listusers'},
 6805:              icon => 'mngcu.png',
 6806:              #help => 'Course_View_Class_List',
 6807:              url => '/adm/createuser?action=listusers',
 6808:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6809:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 6810:             },
 6811: 
 6812:          ]},
 6813: 
 6814:          {categorytitle => 'Administration',
 6815:          items => [ ]},
 6816:        );
 6817: 
 6818:     if ($context eq 'domain'){
 6819:         push(@{  $menu[0]->{items} }, # Single Users
 6820:             {
 6821:              linktext => 'User Access Log',
 6822:              icon => 'document-properties.png',
 6823:              #help => 'Domain_User_Access_Logs',
 6824:              url => '/adm/createuser?action=accesslogs',
 6825:              permission => $permission->{'activity'},
 6826:              linktitle => 'View user access log.',
 6827:             }
 6828:         );
 6829:         
 6830:         push(@{ $menu[2]->{items} }, #Category: Administration
 6831:             {
 6832:              linktext => 'Custom Roles',
 6833:              icon => 'emblem-photos.png',
 6834:              #help => 'Course_Editing_Custom_Roles',
 6835:              url => '/adm/createuser?action=custom',
 6836:              permission => $permission->{'custom'},
 6837:              linktitle => 'Configure a custom role.',
 6838:             },
 6839:             {
 6840:              linktext => 'Authoring Space Requests',
 6841:              icon => 'selfenrl-queue.png',
 6842:              #help => 'Domain_Role_Approvals',
 6843:              url => '/adm/createuser?action=processauthorreq',
 6844:              permission => $permission->{'cusr'},
 6845:              linktitle => 'Approve or reject author role requests',
 6846:             },
 6847:             {
 6848:              linktext => 'LON-CAPA Account Requests',
 6849:              icon => 'list-add.png',
 6850:              #help => 'Domain_Username_Approvals',
 6851:              url => '/adm/createuser?action=processusernamereq',
 6852:              permission => $permission->{'cusr'},
 6853:              linktitle => 'Approve or reject LON-CAPA account requests',
 6854:             },
 6855:             {
 6856:              linktext => 'Change Log',
 6857:              icon => 'document-properties.png',
 6858:              #help => 'Course_User_Logs',
 6859:              url => '/adm/createuser?action=changelogs',
 6860:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 6861:              linktitle => 'View change log.',
 6862:             },
 6863:         );
 6864:         
 6865:     }elsif ($context eq 'course'){
 6866:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 6867: 
 6868:         my %linktext = (
 6869:                          'Course'    => {
 6870:                                           single => 'Add/Modify a Student', 
 6871:                                           drop   => 'Drop Students',
 6872:                                           groups => 'Course Groups',
 6873:                                         },
 6874:                          'Community' => {
 6875:                                           single => 'Add/Modify a Member', 
 6876:                                           drop   => 'Drop Members',
 6877:                                           groups => 'Community Groups',
 6878:                                         },
 6879:                        );
 6880:         $linktext{'Placement'} = $linktext{'Course'};
 6881: 
 6882:         my %linktitle = (
 6883:             'Course' => {
 6884:                   single => 'Add a user with the role of student to this course',
 6885:                   drop   => 'Remove a student from this course.',
 6886:                   groups => 'Manage course groups',
 6887:                         },
 6888:             'Community' => {
 6889:                   single => 'Add a user with the role of member to this community',
 6890:                   drop   => 'Remove a member from this community.',
 6891:                   groups => 'Manage community groups',
 6892:                            },
 6893:         );
 6894: 
 6895:         $linktitle{'Placement'} = $linktitle{'Course'};
 6896: 
 6897:         push(@{ $menu[0]->{items} }, #Category: Single Users
 6898:             {   
 6899:              linktext => $linktext{$crstype}{'single'},
 6900:              #help => 'Course_Add_Student',
 6901:              icon => 'list-add.png',
 6902:              url => '/adm/createuser?action=singlestudent',
 6903:              permission => $permission->{'cusr'},
 6904:              linktitle => $linktitle{$crstype}{'single'},
 6905:             },
 6906:         );
 6907:         
 6908:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 6909:             {
 6910:              linktext => $linktext{$crstype}{'drop'},
 6911:              icon => 'edit-undo.png',
 6912:              #help => 'Course_Drop_Student',
 6913:              url => '/adm/createuser?action=drop',
 6914:              permission => $permission->{'cusr'},
 6915:              linktitle => $linktitle{$crstype}{'drop'},
 6916:             },
 6917:         );
 6918:         push(@{ $menu[2]->{items} }, #Category: Administration
 6919:             {
 6920:              linktext => 'Helpdesk Access',
 6921:              icon => 'helpdesk-access.png',
 6922:              #help => 'Course_Helpdesk_Access',
 6923:              url => '/adm/createuser?action=helpdesk',
 6924:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6925:                             ($permission->{'view'} || $permission->{'cusr'})),
 6926:              linktitle => 'Helpdesk access options',
 6927:             },
 6928:             {
 6929:              linktext => 'Custom Roles',
 6930:              icon => 'emblem-photos.png',
 6931:              #help => 'Course_Editing_Custom_Roles',
 6932:              url => '/adm/createuser?action=custom',
 6933:              permission => $permission->{'custom'},
 6934:              linktitle => 'Configure a custom role.',
 6935:             },
 6936:             {
 6937:              linktext => $linktext{$crstype}{'groups'},
 6938:              icon => 'grps.png',
 6939:              #help => 'Course_Manage_Group',
 6940:              url => '/adm/coursegroups?refpage=cusr',
 6941:              permission => $permission->{'grp_manage'},
 6942:              linktitle => $linktitle{$crstype}{'groups'},
 6943:             },
 6944:             {
 6945:              linktext => 'Change Log',
 6946:              icon => 'document-properties.png',
 6947:              #help => 'Course_User_Logs',
 6948:              url => '/adm/createuser?action=changelogs',
 6949:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6950:              linktitle => 'View change log.',
 6951:             },
 6952:         );
 6953:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 6954:             push(@{ $menu[2]->{items} },
 6955:                     {
 6956:                      linktext => 'Enrollment Requests',
 6957:                      icon => 'selfenrl-queue.png',
 6958:                      #help => 'Course_Approve_Selfenroll',
 6959:                      url => '/adm/createuser?action=selfenrollqueue',
 6960:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6961:                      linktitle =>'Approve or reject enrollment requests.',
 6962:                     },
 6963:             );
 6964:         }
 6965:         
 6966:         if (!exists($permission->{'cusr_section'})){
 6967:             if ($crstype ne 'Community') {
 6968:                 push(@{ $menu[2]->{items} },
 6969:                     {
 6970:                      linktext => 'Automated Enrollment',
 6971:                      icon => 'roles.png',
 6972:                      #help => 'Course_Automated_Enrollment',
 6973:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 6974:                                          && (($permission->{'cusr'}) ||
 6975:                                              ($permission->{'view'}))),
 6976:                      url  => '/adm/populate',
 6977:                      linktitle => 'Automated enrollment manager.',
 6978:                     }
 6979:                 );
 6980:             }
 6981:             push(@{ $menu[2]->{items} }, 
 6982:                 {
 6983:                  linktext => 'User Self-Enrollment',
 6984:                  icon => 'self_enroll.png',
 6985:                  #help => 'Course_Self_Enrollment',
 6986:                  url => '/adm/createuser?action=selfenroll',
 6987:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6988:                  linktitle => 'Configure user self-enrollment.',
 6989:                 },
 6990:             );
 6991:         }
 6992:     } elsif ($context eq 'author') {
 6993:         push(@{ $menu[2]->{items} }, #Category: Administration
 6994:             {
 6995:              linktext => 'Change Log',
 6996:              icon => 'document-properties.png',
 6997:              #help => 'Course_User_Logs',
 6998:              url => '/adm/createuser?action=changelogs',
 6999:              permission => $permission->{'cusr'},
 7000:              linktitle => 'View change log.',
 7001:             },
 7002:             {
 7003:              linktext => 'Co-author Managers',
 7004:              icon => 'camanager.png',
 7005:              #help => 'Coauthor_Management',
 7006:              url => '/adm/createuser?action=camanagers',
 7007:              permission => $permission->{'author'},
 7008:              linktitle => 'Assign/Revoke right to manage co-author roles',
 7009:             },
 7010:             {
 7011:              linktext => 'Configure Co-author Listing',
 7012:              icon => 'coauthors.png',
 7013:              #help => 'Coauthor_Settings',
 7014:              url => '/adm/createuser?action=calist&forceedit=1',
 7015:              permission => ($permission->{'cusr'}),
 7016:              linktitle => 'Set availability of coauthor-viewable user listing',
 7017:             },
 7018:         );
 7019:     }
 7020:     push(@{ $menu[2]->{items} },
 7021:         {
 7022:          linktext => 'Role Requests (other domains)',
 7023:          icon => 'edit-find.png',
 7024:          #help => 'Role_Requests',
 7025:          url => '/adm/createuser?action=rolerequests',
 7026:          permission => $permission->{'cusr'},
 7027:          linktitle => 'Role requests for users in other domains',
 7028:         },
 7029:     );
 7030:     if (&show_role_requests($context,$env{'request.role.domain'})) {
 7031:         push(@{ $menu[2]->{items} },
 7032:             {
 7033:              linktext => 'Queued Role Assignments (this domain)',
 7034:              icon => 'edit-find.png',
 7035:              #help => 'Role_Approvals',
 7036:              url => '/adm/createuser?action=queuedroles',
 7037:              permission => $permission->{'cusr'},
 7038:              linktitle => "Role requests for this domain's users",
 7039:             },
 7040:         );
 7041:     }
 7042:     return Apache::lonhtmlcommon::generate_menu(@menu);
 7043: #               { text => 'View Log-in History',
 7044: #                 help => 'Course_User_Logins',
 7045: #                 action => 'logins',
 7046: #                 permission => $permission->{'cusr'},
 7047: #               });
 7048: }
 7049: 
 7050: sub restore_prev_selections {
 7051:     my %saveable_parameters = ('srchby'   => 'scalar',
 7052: 			       'srchin'   => 'scalar',
 7053: 			       'srchtype' => 'scalar',
 7054: 			       );
 7055:     &Apache::loncommon::store_settings('user','user_picker',
 7056: 				       \%saveable_parameters);
 7057:     &Apache::loncommon::restore_settings('user','user_picker',
 7058: 					 \%saveable_parameters);
 7059: }
 7060: 
 7061: sub print_selfenroll_menu {
 7062:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 7063:     my $crstype = &Apache::loncommon::course_type();
 7064:     my $formname = 'selfenroll';
 7065:     my $nolink = 1;
 7066:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7067:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 7068:     my $setsec_js = 
 7069:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 7070:     my %alerts = &Apache::lonlocal::texthash(
 7071:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 7072:         butn => 'but no user types have been checked.',
 7073:         wilf => "Please uncheck 'activate' or check at least one type.",
 7074:     );
 7075:     my $disabled;
 7076:     if ($readonly) {
 7077:        $disabled = ' disabled="disabled"';
 7078:     }
 7079:     &js_escape(\%alerts);
 7080:     my $selfenroll_js = <<"ENDSCRIPT";
 7081: function update_types(caller,num) {
 7082:     var delidx = getIndexByName('selfenroll_delete');
 7083:     var actidx = getIndexByName('selfenroll_activate');
 7084:     if (caller == 'selfenroll_all') {
 7085:         var selall;
 7086:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7087:             if (document.$formname.selfenroll_all[i].checked) {
 7088:                 selall = document.$formname.selfenroll_all[i].value;
 7089:             }
 7090:         }
 7091:         if (selall == 1) {
 7092:             if (delidx != -1) {
 7093:                 if (document.$formname.selfenroll_delete.length) {
 7094:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7095:                         document.$formname.selfenroll_delete[j].checked = true;
 7096:                     }
 7097:                 } else {
 7098:                     document.$formname.elements[delidx].checked = true;
 7099:                 }
 7100:             }
 7101:             if (actidx != -1) {
 7102:                 if (document.$formname.selfenroll_activate.length) {
 7103:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7104:                         document.$formname.selfenroll_activate[j].checked = false;
 7105:                     }
 7106:                 } else {
 7107:                     document.$formname.elements[actidx].checked = false;
 7108:                 }
 7109:             }
 7110:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 7111:         }
 7112:     }
 7113:     if (caller == 'selfenroll_activate') {
 7114:         if (document.$formname.selfenroll_activate.length) {
 7115:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7116:                 if (document.$formname.selfenroll_activate[j].value == num) {
 7117:                     if (document.$formname.selfenroll_activate[j].checked) {
 7118:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7119:                             if (document.$formname.selfenroll_all[i].value == '1') {
 7120:                                 document.$formname.selfenroll_all[i].checked = false;
 7121:                             }
 7122:                             if (document.$formname.selfenroll_all[i].value == '0') {
 7123:                                 document.$formname.selfenroll_all[i].checked = true;
 7124:                             }
 7125:                         }
 7126:                     }
 7127:                 }
 7128:             }
 7129:         } else {
 7130:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7131:                 if (document.$formname.selfenroll_all[i].value == '1') {
 7132:                     document.$formname.selfenroll_all[i].checked = false;
 7133:                 }
 7134:                 if (document.$formname.selfenroll_all[i].value == '0') {
 7135:                     document.$formname.selfenroll_all[i].checked = true;
 7136:                 }
 7137:             }
 7138:         }
 7139:     }
 7140:     if (caller == 'selfenroll_delete') {
 7141:         if (document.$formname.selfenroll_delete.length) {
 7142:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7143:                 if (document.$formname.selfenroll_delete[j].value == num) {
 7144:                     if (document.$formname.selfenroll_delete[j].checked) {
 7145:                         var delindex = getIndexByName('selfenroll_types_'+num);
 7146:                         if (delindex != -1) { 
 7147:                             if (document.$formname.elements[delindex].length) {
 7148:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7149:                                     document.$formname.elements[delindex][k].checked = false;
 7150:                                 }
 7151:                             } else {
 7152:                                 document.$formname.elements[delindex].checked = false;
 7153:                             }
 7154:                         }
 7155:                     }
 7156:                 }
 7157:             }
 7158:         } else {
 7159:             if (document.$formname.selfenroll_delete.checked) {
 7160:                 var delindex = getIndexByName('selfenroll_types_'+num);
 7161:                 if (delindex != -1) {
 7162:                     if (document.$formname.elements[delindex].length) {
 7163:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7164:                             document.$formname.elements[delindex][k].checked = false;
 7165:                         }
 7166:                     } else {
 7167:                         document.$formname.elements[delindex].checked = false;
 7168:                     }
 7169:                 }
 7170:             }
 7171:         }
 7172:     }
 7173:     return;
 7174: }
 7175: 
 7176: function validate_types(form) {
 7177:     var needaction = new Array();
 7178:     var countfail = 0;
 7179:     var actidx = getIndexByName('selfenroll_activate');
 7180:     if (actidx != -1) {
 7181:         if (document.$formname.selfenroll_activate.length) {
 7182:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7183:                 var num = document.$formname.selfenroll_activate[j].value;
 7184:                 if (document.$formname.selfenroll_activate[j].checked) {
 7185:                     countfail = check_types(num,countfail,needaction)
 7186:                 }
 7187:             }
 7188:         } else {
 7189:             if (document.$formname.selfenroll_activate.checked) {
 7190:                 var num = document.$formname.selfenroll_activate.value;
 7191:                 countfail = check_types(num,countfail,needaction)
 7192:             }
 7193:         }
 7194:     }
 7195:     if (countfail > 0) {
 7196:         var msg = "$alerts{'acto'}\\n";
 7197:         var loopend = needaction.length -1;
 7198:         if (loopend > 0) {
 7199:             for (var m=0; m<loopend; m++) {
 7200:                 msg += needaction[m]+", ";
 7201:             }
 7202:         }
 7203:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 7204:         alert(msg);
 7205:         return; 
 7206:     }
 7207:     setSections(form);
 7208: }
 7209: 
 7210: function check_types(num,countfail,needaction) {
 7211:     var boxname = 'selfenroll_types_'+num;
 7212:     var typeidx = getIndexByName(boxname);
 7213:     var count = 0;
 7214:     if (typeidx != -1) {
 7215:         if (document.$formname.elements[boxname].length) {
 7216:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 7217:                 if (document.$formname.elements[boxname][k].checked) {
 7218:                     count ++;
 7219:                 }
 7220:             }
 7221:         } else {
 7222:             if (document.$formname.elements[typeidx].checked) {
 7223:                 count ++;
 7224:             }
 7225:         }
 7226:         if (count == 0) {
 7227:             var domidx = getIndexByName('selfenroll_dom_'+num);
 7228:             if (domidx != -1) {
 7229:                 var domname = document.$formname.elements[domidx].value;
 7230:                 needaction[countfail] = domname;
 7231:                 countfail ++;
 7232:             }
 7233:         }
 7234:     }
 7235:     return countfail;
 7236: }
 7237: 
 7238: function toggleNotify() {
 7239:     var selfenrollApproval = 0;
 7240:     if (document.$formname.selfenroll_approval.length) {
 7241:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 7242:             if (document.$formname.selfenroll_approval[i].checked) {
 7243:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 7244:                 break;        
 7245:             }
 7246:         }
 7247:     }
 7248:     if (document.getElementById('notified')) {
 7249:         if (selfenrollApproval == 0) {
 7250:             document.getElementById('notified').style.display='none';
 7251:         } else {
 7252:             document.getElementById('notified').style.display='block';
 7253:         }
 7254:     }
 7255:     return;
 7256: }
 7257: 
 7258: function getIndexByName(item) {
 7259:     for (var i=0;i<document.$formname.elements.length;i++) {
 7260:         if (document.$formname.elements[i].name == item) {
 7261:             return i;
 7262:         }
 7263:     }
 7264:     return -1;
 7265: }
 7266: ENDSCRIPT
 7267: 
 7268:     my $output = '<script type="text/javascript">'."\n".
 7269:                  '// <![CDATA['."\n".
 7270:                  $setsec_js."\n".$selfenroll_js."\n".
 7271:                  '// ]]>'."\n".
 7272:                  '</script>'."\n".
 7273:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 7274:     my $visactions = &cat_visibility($cdom);
 7275:     my ($cathash,%cattype);
 7276:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7277:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7278:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7279:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7280:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7281:         if ($cattype{'auth'} eq '') {
 7282:             $cattype{'auth'} = 'std';
 7283:         }
 7284:         if ($cattype{'unauth'} eq '') {
 7285:             $cattype{'unauth'} = 'std';
 7286:         }
 7287:     } else {
 7288:         $cathash = {};
 7289:         $cattype{'auth'} = 'std';
 7290:         $cattype{'unauth'} = 'std';
 7291:     }
 7292:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7293:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7294:                   '<br />'.
 7295:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7296:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7297:                   '</ul>');
 7298:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7299:         if ($currsettings->{'uniquecode'}) {
 7300:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7301:         } else {
 7302:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7303:                   '<br />'.
 7304:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7305:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7306:                   '</ul><br />');
 7307:         }
 7308:     } else {
 7309:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7310:         if (ref($visactions) eq 'HASH') {
 7311:             if ($visible) {
 7312:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 7313:            } else {
 7314:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 7315:                           .$visactions->{'yous'}.
 7316:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 7317:                 if (ref($vismsgs) eq 'ARRAY') {
 7318:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 7319:                     foreach my $item (@{$vismsgs}) {
 7320:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 7321:                     }
 7322:                     $output .= '</ul>';
 7323:                 }
 7324:                 $output .= '</p>';
 7325:             }
 7326:         }
 7327:     }
 7328:     my $actionhref = '/adm/createuser';
 7329:     if ($context eq 'domain') {
 7330:         $actionhref = '/adm/modifycourse';
 7331:     }
 7332: 
 7333:     my %noedit;
 7334:     unless ($context eq 'domain') {
 7335:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7336:     }
 7337:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 7338:                &Apache::lonhtmlcommon::start_pick_box();
 7339:     if (ref($row) eq 'ARRAY') {
 7340:         foreach my $item (@{$row}) {
 7341:             my $title = $item; 
 7342:             if (ref($lt) eq 'HASH') {
 7343:                 $title = $lt->{$item};
 7344:             }
 7345:             $output .= &Apache::lonhtmlcommon::row_title($title);
 7346:             if ($item eq 'types') {
 7347:                 my $curr_types;
 7348:                 if (ref($currsettings) eq 'HASH') {
 7349:                     $curr_types = $currsettings->{'selfenroll_types'};
 7350:                 }
 7351:                 if ($noedit{$item}) {
 7352:                     if ($curr_types eq '*') {
 7353:                         $output .= &mt('Any user in any domain');   
 7354:                     } else {
 7355:                         my @entries = split(/;/,$curr_types);
 7356:                         if (@entries > 0) {
 7357:                             $output .= '<ul>'; 
 7358:                             foreach my $entry (@entries) {
 7359:                                 my ($currdom,$typestr) = split(/:/,$entry);
 7360:                                 next if ($typestr eq '');
 7361:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 7362:                                 my @currinsttypes = split(',',$typestr);
 7363:                                 my ($othertitle,$usertypes,$types) = 
 7364:                                     &Apache::loncommon::sorted_inst_types($currdom);
 7365:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7366:                                     $usertypes->{'any'} = &mt('any user'); 
 7367:                                     if (keys(%{$usertypes}) > 0) {
 7368:                                         $usertypes->{'other'} = &mt('other users');
 7369:                                     }
 7370:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 7371:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 7372:                                  }
 7373:                             }
 7374:                             $output .= '</ul>';
 7375:                         } else {
 7376:                             $output .= &mt('None');
 7377:                         }
 7378:                     }
 7379:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7380:                     next;
 7381:                 }
 7382:                 my $showdomdesc = 1;
 7383:                 my $includeempty = 1;
 7384:                 my $num = 0;
 7385:                 $output .= &Apache::loncommon::start_data_table().
 7386:                            &Apache::loncommon::start_data_table_row()
 7387:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 7388:                            .&mt('Any user in any domain:')
 7389:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 7390:                 if ($curr_types eq '*') {
 7391:                     $output .= ' checked="checked" '; 
 7392:                 }
 7393:                 $output .= 'onchange="javascript:update_types('.
 7394:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 7395:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 7396:                 if ($curr_types ne '*') {
 7397:                     $output .= ' checked="checked" ';
 7398:                 }
 7399:                 $output .= ' onchange="javascript:update_types('.
 7400:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 7401:                            &Apache::loncommon::end_data_table_row().
 7402:                            &Apache::loncommon::end_data_table().
 7403:                            &mt('Or').'<br />'.
 7404:                            &Apache::loncommon::start_data_table();
 7405:                 my %currdoms;
 7406:                 if ($curr_types eq '') {
 7407:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 7408:                 } elsif ($curr_types ne '*') {
 7409:                     my @entries = split(/;/,$curr_types);
 7410:                     if (@entries > 0) {
 7411:                         foreach my $entry (@entries) {
 7412:                             my ($currdom,$typestr) = split(/:/,$entry);
 7413:                             $currdoms{$currdom} = 1;
 7414:                             my $domdesc = &Apache::lonnet::domain($currdom);
 7415:                             my @currinsttypes = split(',',$typestr);
 7416:                             $output .= &Apache::loncommon::start_data_table_row()
 7417:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 7418:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 7419:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 7420:                                        .'" value="'.$currdom.'" /></span><br />'
 7421:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 7422:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 7423:                                        .&mt('Delete').'</label></span></td>';
 7424:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 7425:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 7426:                                        .&Apache::loncommon::end_data_table_row();
 7427:                             $num ++;
 7428:                         }
 7429:                     }
 7430:                 }
 7431:                 my $add_domtitle = &mt('Users in additional domain:');
 7432:                 if ($curr_types eq '*') { 
 7433:                     $add_domtitle = &mt('Users in specific domain:');
 7434:                 } elsif ($curr_types eq '') {
 7435:                     $add_domtitle = &mt('Users in other domain:');
 7436:                 }
 7437:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 7438:                 $output .= &Apache::loncommon::start_data_table_row()
 7439:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 7440:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 7441:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 7442:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 7443:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 7444:                            .&Apache::loncommon::end_data_table();
 7445:             } elsif ($item eq 'registered') {
 7446:                 my ($regon,$regoff);
 7447:                 my $registered;
 7448:                 if (ref($currsettings) eq 'HASH') {
 7449:                     $registered = $currsettings->{'selfenroll_registered'};
 7450:                 }
 7451:                 if ($noedit{$item}) {
 7452:                     if ($registered) {
 7453:                         $output .= &mt('Must be registered in course');
 7454:                     } else {
 7455:                         $output .= &mt('No requirement');
 7456:                     }
 7457:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7458:                     next;
 7459:                 }
 7460:                 if ($registered) {
 7461:                     $regon = ' checked="checked" ';
 7462:                     $regoff = '';
 7463:                 } else {
 7464:                     $regon = '';
 7465:                     $regoff = ' checked="checked" ';
 7466:                 }
 7467:                 $output .= '<label>'.
 7468:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 7469:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 7470:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 7471:                            &mt('No').'</label>';
 7472:             } elsif ($item eq 'enroll_dates') {
 7473:                 my ($starttime,$endtime);
 7474:                 if (ref($currsettings) eq 'HASH') {
 7475:                     $starttime = $currsettings->{'selfenroll_start_date'};
 7476:                     $endtime = $currsettings->{'selfenroll_end_date'};
 7477:                     if ($starttime eq '') {
 7478:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7479:                     }
 7480:                     if ($endtime eq '') {
 7481:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7482:                     }
 7483:                 }
 7484:                 if ($noedit{$item}) {
 7485:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7486:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7487:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7488:                     next;
 7489:                 }
 7490:                 my $startform =
 7491:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 7492:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7493:                 my $endform =
 7494:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 7495:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7496:                 $output .= &selfenroll_date_forms($startform,$endform);
 7497:             } elsif ($item eq 'access_dates') {
 7498:                 my ($starttime,$endtime);
 7499:                 if (ref($currsettings) eq 'HASH') {
 7500:                     $starttime = $currsettings->{'selfenroll_start_access'};
 7501:                     $endtime = $currsettings->{'selfenroll_end_access'};
 7502:                     if ($starttime eq '') {
 7503:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7504:                     }
 7505:                     if ($endtime eq '') {
 7506:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7507:                     }
 7508:                 }
 7509:                 if ($noedit{$item}) {
 7510:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7511:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7512:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7513:                     next;
 7514:                 }
 7515:                 my $startform =
 7516:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 7517:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7518:                 my $endform =
 7519:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 7520:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7521:                 $output .= &selfenroll_date_forms($startform,$endform);
 7522:             } elsif ($item eq 'section') {
 7523:                 my $currsec;
 7524:                 if (ref($currsettings) eq 'HASH') {
 7525:                     $currsec = $currsettings->{'selfenroll_section'};
 7526:                 }
 7527:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 7528:                 my $newsecval;
 7529:                 if ($currsec ne 'none' && $currsec ne '') {
 7530:                     if (!defined($sections_count{$currsec})) {
 7531:                         $newsecval = $currsec;
 7532:                     }
 7533:                 }
 7534:                 if ($noedit{$item}) {
 7535:                     if ($currsec ne '') {
 7536:                         $output .= $currsec;
 7537:                     } else {
 7538:                         $output .= &mt('No specific section');
 7539:                     }
 7540:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7541:                     next;
 7542:                 }
 7543:                 my $sections_select = 
 7544:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 7545:                 $output .= '<table class="LC_createuser">'."\n".
 7546:                            '<tr class="LC_section_row">'."\n".
 7547:                            '<td align="center">'.&mt('Existing sections')."\n".
 7548:                            '<br />'.$sections_select.'</td><td align="center">'.
 7549:                            &mt('New section').'<br />'."\n".
 7550:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 7551:                            '<input type="hidden" name="sections" value="" />'."\n".
 7552:                            '</td></tr></table>'."\n";
 7553:             } elsif ($item eq 'approval') {
 7554:                 my ($currnotified,$currapproval,%appchecked);
 7555:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7556:                 if (ref($currsettings) eq 'HASH') {
 7557:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 7558:                     $currapproval = $currsettings->{'selfenroll_approval'};
 7559:                 }
 7560:                 if ($currapproval !~ /^[012]$/) {
 7561:                     $currapproval = 0;
 7562:                 }
 7563:                 if ($noedit{$item}) {
 7564:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 7565:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 7566:                     next;
 7567:                 }
 7568:                 $appchecked{$currapproval} = ' checked="checked"';
 7569:                 for my $i (0..2) {
 7570:                     $output .= '<label>'.
 7571:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 7572:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 7573:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 7574:                 }
 7575:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 7576:                 my (@ccs,%notified);
 7577:                 my $ccrole = 'cc';
 7578:                 if ($crstype eq 'Community') {
 7579:                     $ccrole = 'co';
 7580:                 }
 7581:                 if ($advhash{$ccrole}) {
 7582:                     @ccs = split(/,/,$advhash{$ccrole});
 7583:                 }
 7584:                 if ($currnotified) {
 7585:                     foreach my $current (split(/,/,$currnotified)) {
 7586:                         $notified{$current} = 1;
 7587:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 7588:                             push(@ccs,$current);
 7589:                         }
 7590:                     }
 7591:                 }
 7592:                 if (@ccs) {
 7593:                     my $style;
 7594:                     unless ($currapproval) {
 7595:                         $style = ' style="display: none;"'; 
 7596:                     }
 7597:                     $output .= '<br /><div id="notified"'.$style.'>'.
 7598:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 7599:                                &Apache::loncommon::start_data_table().
 7600:                                &Apache::loncommon::start_data_table_row();
 7601:                     my $count = 0;
 7602:                     my $numcols = 4;
 7603:                     foreach my $cc (sort(@ccs)) {
 7604:                         my $notifyon;
 7605:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 7606:                         if ($notified{$cc}) {
 7607:                             $notifyon = ' checked="checked" ';
 7608:                         }
 7609:                         if ($count && !$count%$numcols) {
 7610:                             $output .= &Apache::loncommon::end_data_table_row().
 7611:                                        &Apache::loncommon::start_data_table_row()
 7612:                         }
 7613:                         $output .= '<td><span class="LC_nobreak"><label>'.
 7614:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 7615:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 7616:                                    '</label></span></td>';
 7617:                         $count ++;
 7618:                     }
 7619:                     my $rem = $count%$numcols;
 7620:                     if ($rem) {
 7621:                         my $emptycols = $numcols - $rem;
 7622:                         for (my $i=0; $i<$emptycols; $i++) { 
 7623:                             $output .= '<td>&nbsp;</td>';
 7624:                         }
 7625:                     }
 7626:                     $output .= &Apache::loncommon::end_data_table_row().
 7627:                                &Apache::loncommon::end_data_table().
 7628:                                '</div>';
 7629:                 }
 7630:             } elsif ($item eq 'limit') {
 7631:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 7632:                 if (ref($currsettings) eq 'HASH') {
 7633:                     $currlim = $currsettings->{'selfenroll_limit'};
 7634:                     $currcap = $currsettings->{'selfenroll_cap'};
 7635:                 }
 7636:                 if ($noedit{$item}) {
 7637:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 7638:                         if ($currlim eq 'allstudents') {
 7639:                             $output .= &mt('Limit by total students');
 7640:                         } elsif ($currlim eq 'selfenrolled') {
 7641:                             $output .= &mt('Limit by total self-enrolled students');
 7642:                         }
 7643:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 7644:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 7645:                     } else {
 7646:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 7647:                     }
 7648:                     next;
 7649:                 }
 7650:                 if ($currlim eq 'allstudents') {
 7651:                     $crslimit = ' checked="checked" ';
 7652:                     $selflimit = ' ';
 7653:                     $nolimit = ' ';
 7654:                 } elsif ($currlim eq 'selfenrolled') {
 7655:                     $crslimit = ' ';
 7656:                     $selflimit = ' checked="checked" ';
 7657:                     $nolimit = ' '; 
 7658:                 } else {
 7659:                     $crslimit = ' ';
 7660:                     $selflimit = ' ';
 7661:                     $nolimit = ' checked="checked" ';
 7662:                 }
 7663:                 $output .= '<table><tr><td><label>'.
 7664:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 7665:                            &mt('No limit').'</label></td><td><label>'.
 7666:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 7667:                            &mt('Limit by total students').'</label></td><td><label>'.
 7668:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 7669:                            &mt('Limit by total self-enrolled students').
 7670:                            '</td></tr><tr>'.
 7671:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 7672:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 7673:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 7674:             }
 7675:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 7676:         }
 7677:     }
 7678:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 7679:     unless ($readonly) {
 7680:         $output .= '<input type="button" name="selfenrollconf" value="'
 7681:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 7682:     }
 7683:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 7684:               .'<input type="hidden" name="state" value="done" />'."\n"
 7685:               .$additional.'</form>';
 7686:     $r->print($output);
 7687:     return;
 7688: }
 7689: 
 7690: sub get_noedit_fields {
 7691:     my ($cdom,$cnum,$crstype,$row) = @_;
 7692:     my %noedit;
 7693:     if (ref($row) eq 'ARRAY') {
 7694:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 7695:                                                            'internal.selfenrollmgrdc',
 7696:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 7697:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 7698:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 7699:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 7700:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 7701:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 7702:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 7703: 
 7704:         foreach my $item (@{$row}) {
 7705:             next if ($specific_managebycc{$item});
 7706:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 7707:                 $noedit{$item} = 1;
 7708:             }
 7709:         }
 7710:     }
 7711:     return %noedit;
 7712: }
 7713: 
 7714: sub visible_in_stdcat {
 7715:     my ($cdom,$cnum,$domconf) = @_;
 7716:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 7717:     unless (ref($domconf) eq 'HASH') {
 7718:         return ($visible,$cansetvis,\@vismsgs);
 7719:     }
 7720:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7721:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 7722:             $settable{'togglecats'} = 1;
 7723:         }
 7724:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 7725:             $settable{'categorize'} = 1;
 7726:         }
 7727:         $cathash = $domconf->{'coursecategories'}{'cats'};
 7728:     }
 7729:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 7730:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 7731:     } elsif ($settable{'togglecats'}) {
 7732:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 7733:     } elsif ($settable{'categorize'}) {
 7734:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 7735:     } else {
 7736:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 7737:     }
 7738:      
 7739:     my %currsettings =
 7740:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 7741:                              $cdom,$cnum);
 7742:     $visible = 0;
 7743:     if ($currsettings{'internal.coursecode'} ne '') {
 7744:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7745:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7746:             if (ref($cathash) eq 'HASH') {
 7747:                 if ($cathash->{'instcode::0'} eq '') {
 7748:                     push(@vismsgs,'dc_addinst'); 
 7749:                 } else {
 7750:                     $visible = 1;
 7751:                 }
 7752:             } else {
 7753:                 $visible = 1;
 7754:             }
 7755:         } else {
 7756:             $visible = 1;
 7757:         }
 7758:     } else {
 7759:         if (ref($cathash) eq 'HASH') {
 7760:             if ($cathash->{'instcode::0'} ne '') {
 7761:                 push(@vismsgs,'dc_instcode');
 7762:             }
 7763:         } else {
 7764:             push(@vismsgs,'dc_instcode');
 7765:         }
 7766:     }
 7767:     if ($currsettings{'categories'} ne '') {
 7768:         my $cathash;
 7769:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7770:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7771:             if (ref($cathash) eq 'HASH') {
 7772:                 if (keys(%{$cathash}) == 0) {
 7773:                     push(@vismsgs,'dc_catalog');
 7774:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 7775:                     push(@vismsgs,'dc_categories');
 7776:                 } else {
 7777:                     my @currcategories = split('&',$currsettings{'categories'});
 7778:                     my $matched = 0;
 7779:                     foreach my $cat (@currcategories) {
 7780:                         if ($cathash->{$cat} ne '') {
 7781:                             $visible = 1;
 7782:                             $matched = 1;
 7783:                             last;
 7784:                         }
 7785:                     }
 7786:                     if (!$matched) {
 7787:                         if ($settable{'categorize'}) { 
 7788:                             push(@vismsgs,'chgcat');
 7789:                         } else {
 7790:                             push(@vismsgs,'dc_chgcat');
 7791:                         }
 7792:                     }
 7793:                 }
 7794:             }
 7795:         }
 7796:     } else {
 7797:         if (ref($cathash) eq 'HASH') {
 7798:             if ((keys(%{$cathash}) > 1) || 
 7799:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 7800:                 if ($settable{'categorize'}) {
 7801:                     push(@vismsgs,'addcat');
 7802:                 } else {
 7803:                     push(@vismsgs,'dc_addcat');
 7804:                 }
 7805:             }
 7806:         }
 7807:     }
 7808:     if ($currsettings{'hidefromcat'} eq 'yes') {
 7809:         $visible = 0;
 7810:         if ($settable{'togglecats'}) {
 7811:             unshift(@vismsgs,'unhide');
 7812:         } else {
 7813:             unshift(@vismsgs,'dc_unhide')
 7814:         }
 7815:     }
 7816:     return ($visible,$cansetvis,\@vismsgs);
 7817: }
 7818: 
 7819: sub cat_visibility {
 7820:     my ($cdom) = @_;
 7821:     my %visactions = &Apache::lonlocal::texthash(
 7822:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 7823:                    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.',
 7824:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 7825:                    none => 'Display of a course catalog is disabled for this domain.',
 7826:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 7827:                    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.',
 7828:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 7829:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 7830:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 7831:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 7832:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 7833:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 7834:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 7835:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 7836:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 7837:                    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',
 7838:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 7839:     );
 7840:     if ($env{'request.role'} eq "dc./$cdom/") {
 7841:         $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;');
 7842:         $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;');
 7843:         $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;');
 7844:         $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;');
 7845:         $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;');
 7846:         $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;');
 7847:         $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;');
 7848:         $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;');
 7849:         $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;');
 7850:     }
 7851:     $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>"');
 7852:     $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>"');
 7853:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 7854:     return \%visactions;
 7855: }
 7856: 
 7857: sub new_selfenroll_dom_row {
 7858:     my ($newdom,$num) = @_;
 7859:     my $domdesc = &Apache::lonnet::domain($newdom);
 7860:     my $output;
 7861:     if ($domdesc ne '') {
 7862:         $output .= &Apache::loncommon::start_data_table_row()
 7863:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 7864:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 7865:                    .'" value="'.$newdom.'" /></span><br />'
 7866:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 7867:                    .'name="selfenroll_activate" value="'.$num.'" '
 7868:                    .'onchange="javascript:update_types('
 7869:                    ."'selfenroll_activate','$num'".');" />'
 7870:                    .&mt('Activate').'</label></span></td>';
 7871:         my @currinsttypes;
 7872:         $output .= '<td>'.&mt('User types:').'<br />'
 7873:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 7874:                    .&Apache::loncommon::end_data_table_row();
 7875:     }
 7876:     return $output;
 7877: }
 7878: 
 7879: sub selfenroll_inst_types {
 7880:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 7881:     my $output;
 7882:     my $numinrow = 4;
 7883:     my $count = 0;
 7884:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 7885:     my $othervalue = 'any';
 7886:     my $disabled;
 7887:     if ($readonly) {
 7888:         $disabled = ' disabled="disabled"';
 7889:     }
 7890:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7891:         if (keys(%{$usertypes}) > 0) {
 7892:             $othervalue = 'other';
 7893:         }
 7894:         $output .= '<table><tr>';
 7895:         foreach my $type (@{$types}) {
 7896:             if (($count > 0) && ($count%$numinrow == 0)) {
 7897:                 $output .= '</tr><tr>';
 7898:             }
 7899:             if (defined($usertypes->{$type})) {
 7900:                 my $esc_type = &escape($type);
 7901:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 7902:                            $esc_type.'" ';
 7903:                 if (ref($currinsttypes) eq 'ARRAY') {
 7904:                     if (@{$currinsttypes} > 0) {
 7905:                         if (grep(/^any$/,@{$currinsttypes})) {
 7906:                             $output .= 'checked="checked"';
 7907:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 7908:                             $output .= 'checked="checked"';
 7909:                         }
 7910:                     } else {
 7911:                         $output .= 'checked="checked"';
 7912:                     }
 7913:                 }
 7914:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 7915:             }
 7916:             $count ++;
 7917:         }
 7918:         if (($count > 0) && ($count%$numinrow == 0)) {
 7919:             $output .= '</tr><tr>';
 7920:         }
 7921:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 7922:         if (ref($currinsttypes) eq 'ARRAY') {
 7923:             if (@{$currinsttypes} > 0) {
 7924:                 if (grep(/^any$/,@{$currinsttypes})) { 
 7925:                     $output .= ' checked="checked"';
 7926:                 } elsif ($othervalue eq 'other') {
 7927:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 7928:                         $output .= ' checked="checked"';
 7929:                     }
 7930:                 }
 7931:             } else {
 7932:                 $output .= ' checked="checked"';
 7933:             }
 7934:         } else {
 7935:             $output .= ' checked="checked"';
 7936:         }
 7937:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 7938:     }
 7939:     return $output;
 7940: }
 7941: 
 7942: sub selfenroll_date_forms {
 7943:     my ($startform,$endform) = @_;
 7944:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 7945:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 7946:                                                     'LC_oddrow_value')."\n".
 7947:                   $startform."\n".
 7948:                   &Apache::lonhtmlcommon::row_closure(1).
 7949:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 7950:                                                    'LC_oddrow_value')."\n".
 7951:                   $endform."\n".
 7952:                   &Apache::lonhtmlcommon::row_closure(1).
 7953:                   &Apache::lonhtmlcommon::end_pick_box();
 7954:     return $output;
 7955: }
 7956: 
 7957: sub print_userchangelogs_display {
 7958:     my ($r,$context,$permission,$brcrum) = @_;
 7959:     my $formname = 'rolelog';
 7960:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 7961:     if ($context eq 'domain') {
 7962:         $domain = $env{'request.role.domain'};
 7963:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 7964:     } else {
 7965:         if ($context eq 'course') { 
 7966:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7967:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 7968:             $crstype = &Apache::loncommon::course_type();
 7969:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 7970:             my %saveable_parameters = ('show' => 'scalar',);
 7971:             &Apache::loncommon::store_course_settings('roles_log',
 7972:                                                       \%saveable_parameters);
 7973:             &Apache::loncommon::restore_course_settings('roles_log',
 7974:                                                         \%saveable_parameters);
 7975:         } elsif ($context eq 'author') {
 7976:             $domain = $env{'user.domain'};
 7977:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 7978:                 $username = $env{'user.name'};
 7979:             } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 7980:                 ($domain,$username) = ($1,$2);
 7981:             } else {
 7982:                 undef($domain);
 7983:             }
 7984:         }
 7985:         if ($domain ne '' && $username ne '') { 
 7986:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 7987:         }
 7988:     }
 7989:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 7990: 
 7991:     my $helpitem;
 7992:     if ($context eq 'course') {
 7993:         $helpitem = 'Course_User_Logs';
 7994:     } elsif ($context eq 'domain') {
 7995:         $helpitem = 'Domain_Role_Logs';
 7996:     } elsif ($context eq 'author') {
 7997:         $helpitem = 'Author_User_Logs';
 7998:     }
 7999:     push (@{$brcrum},
 8000:              {href => '/adm/createuser?action=changelogs',
 8001:               text => 'User Management Logs',
 8002:               help => $helpitem});
 8003:     my $bread_crumbs_component = 'User Changes';
 8004:     my $args = { bread_crumbs           => $brcrum,
 8005:                  bread_crumbs_component => $bread_crumbs_component};
 8006: 
 8007:     # Create navigation javascript
 8008:     my $jsnav = &userlogdisplay_js($formname);
 8009: 
 8010:     my $jscript = (<<ENDSCRIPT);
 8011: <script type="text/javascript">
 8012: // <![CDATA[
 8013: $jsnav
 8014: // ]]>
 8015: </script>
 8016: ENDSCRIPT
 8017: 
 8018:     # print page header
 8019:     $r->print(&header($jscript,$args));
 8020: 
 8021:     # set defaults
 8022:     my $now = time();
 8023:     my $defstart = $now - (7*24*3600); #7 days ago 
 8024:     my %defaults = (
 8025:                      page               => '1',
 8026:                      show               => '10',
 8027:                      role               => 'any',
 8028:                      chgcontext         => 'any',
 8029:                      rolelog_start_date => $defstart,
 8030:                      rolelog_end_date   => $now,
 8031:                      approvals          => 'any',
 8032:                    );
 8033:     my $more_records = 0;
 8034: 
 8035:     # set current
 8036:     my %curr;
 8037:     foreach my $item ('show','page','role','chgcontext','approvals') {
 8038:         $curr{$item} = $env{'form.'.$item};
 8039:     }
 8040:     my ($startdate,$enddate) = 
 8041:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 8042:     $curr{'rolelog_start_date'} = $startdate;
 8043:     $curr{'rolelog_end_date'} = $enddate;
 8044:     foreach my $key (keys(%defaults)) {
 8045:         if ($curr{$key} eq '') {
 8046:             $curr{$key} = $defaults{$key};
 8047:         }
 8048:     }
 8049:     my (%whodunit,%changed,$version);
 8050:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 8051:     my ($minshown,$maxshown);
 8052:     $minshown = 1;
 8053:     my $count = 0;
 8054:     if ($curr{'show'} =~ /\D/) {
 8055:         $curr{'page'} = 1;
 8056:     } else {
 8057:         $maxshown = $curr{'page'} * $curr{'show'};
 8058:         if ($curr{'page'} > 1) {
 8059:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8060:         }
 8061:     }
 8062: 
 8063:     # Form Header
 8064:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8065:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 8066:                                    $version,$crstype));
 8067: 
 8068:     my $showntableheader = 0;
 8069: 
 8070:     # Table Header
 8071:     my $tableheader = 
 8072:         &Apache::loncommon::start_data_table_header_row()
 8073:        .'<th>&nbsp;</th>'
 8074:        .'<th>'.&mt('When').'</th>'
 8075:        .'<th>'.&mt('Who made the change').'</th>'
 8076:        .'<th>'.&mt('Changed User').'</th>'
 8077:        .'<th>'.&mt('Role').'</th>';
 8078: 
 8079:     if ($context eq 'course') {
 8080:         $tableheader .= '<th>'.&mt('Section').'</th>';
 8081:     }
 8082:     $tableheader .=
 8083:         '<th>'.&mt('Context').'</th>'
 8084:        .'<th>'.&mt('Start').'</th>'
 8085:        .'<th>'.&mt('End').'</th>'
 8086:        .&Apache::loncommon::end_data_table_header_row();
 8087: 
 8088:     # Display user change log data
 8089:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 8090:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 8091:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 8092:         if ($curr{'show'} !~ /\D/) {
 8093:             if ($count >= $curr{'page'} * $curr{'show'}) {
 8094:                 $more_records = 1;
 8095:                 last;
 8096:             }
 8097:         }
 8098:         if ($curr{'role'} ne 'any') {
 8099:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 8100:         }
 8101:         if ($curr{'chgcontext'} ne 'any') {
 8102:             if ($curr{'chgcontext'} eq 'selfenroll') {
 8103:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 8104:             } else {
 8105:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 8106:             }
 8107:         }
 8108:         if (($context eq 'course') && ($viewablesec ne '')) {
 8109:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 8110:         }
 8111:         if ($curr{'approvals'} eq 'none') {
 8112:             next if ($roleslog{$id}{'logentry'}{'approval'});
 8113:         } elsif ($curr{'approvals'} ne 'any') { 
 8114:             next if ($roleslog{$id}{'logentry'}{'approval'} ne $curr{'approvals'});
 8115:         }
 8116:         $count ++;
 8117:         next if ($count < $minshown);
 8118:         unless ($showntableheader) {
 8119:             $r->print(&Apache::loncommon::start_data_table()
 8120:                      .$tableheader);
 8121:             $r->rflush();
 8122:             $showntableheader = 1;
 8123:         }
 8124:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 8125:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 8126:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 8127:         }
 8128:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 8129:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 8130:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 8131:         }
 8132:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 8133:         if ($sec eq '') {
 8134:             $sec = &mt('None');
 8135:         }
 8136:         my ($rolestart,$roleend);
 8137:         if ($roleslog{$id}{'delflag'}) {
 8138:             $rolestart = &mt('deleted');
 8139:             $roleend = &mt('deleted');
 8140:         } else {
 8141:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 8142:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 8143:             if ($rolestart eq '' || $rolestart == 0) {
 8144:                 $rolestart = &mt('No start date'); 
 8145:             } else {
 8146:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 8147:             }
 8148:             if ($roleend eq '' || $roleend == 0) { 
 8149:                 $roleend = &mt('No end date');
 8150:             } else {
 8151:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 8152:             }
 8153:         }
 8154:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 8155:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 8156:             $chgcontext = 'selfenroll';
 8157:         }
 8158:         my %lt = &rolechg_contexts($context,$crstype);
 8159:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 8160:             $chgcontext = $lt{$chgcontext};
 8161:         }
 8162:         my ($showreqby,%reqby);
 8163:         if (($roleslog{$id}{'logentry'}{'approval'}) &&
 8164:             ($roleslog{$id}{'logentry'}{'requester'})) {
 8165:             if ($reqby{$roleslog{$id}{'logentry'}{'requester'}} eq '') {
 8166:                 my ($requname,$requdom) = split(/:/,$roleslog{$id}{'logentry'}{'requester'});
 8167:                 $reqby{$roleslog{$id}{'logentry'}{'requester'}} =
 8168:                     &Apache::loncommon::plainname($requname,$requdom);
 8169:             }
 8170:             $showreqby = &mt('Requester').': <span class="LC_nobreak">'.$reqby{$roleslog{$id}{'logentry'}{'requester'}}.'</span><br />';
 8171:             if ($roleslog{$id}{'logentry'}{'approval'} eq 'domain') {
 8172:                 $showreqby .= &mt('Adjudicator').': <span class="LC_nobreak">'.
 8173:                               $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.
 8174:                               '</span>';
 8175:             } else {
 8176:                 $showreqby .= '<span class="LC_nobreak">'.&mt('User approved').'</span>';
 8177:             }
 8178:         } else {
 8179:             $showreqby = $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}};
 8180:         }
 8181:         $r->print(
 8182:             &Apache::loncommon::start_data_table_row()
 8183:            .'<td>'.$count.'</td>'
 8184:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 8185:            .'<td>'.$showreqby.'</td>'
 8186:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 8187:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 8188:         if ($context eq 'course') { 
 8189:             $r->print('<td>'.$sec.'</td>');
 8190:         }
 8191:         $r->print(
 8192:             '<td>'.$chgcontext.'</td>'
 8193:            .'<td>'.$rolestart.'</td>'
 8194:            .'<td>'.$roleend.'</td>'
 8195:            .&Apache::loncommon::end_data_table_row()."\n");
 8196:     }
 8197: 
 8198:     if ($showntableheader) { # Table footer, if content displayed above
 8199:         $r->print(&Apache::loncommon::end_data_table().
 8200:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8201:     } else { # No content displayed above
 8202:         $r->print('<p class="LC_info">'
 8203:                  .&mt('There are no records to display.')
 8204:                  .'</p>'
 8205:         );
 8206:     }
 8207: 
 8208:     # Form Footer
 8209:     $r->print( 
 8210:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8211:        .'<input type="hidden" name="action" value="changelogs" />'
 8212:        .'</form>');
 8213:     return;
 8214: }
 8215: 
 8216: sub print_useraccesslogs_display {
 8217:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 8218:     my $formname = 'accesslog';
 8219:     my $form = 'document.accesslog';
 8220: 
 8221: # set breadcrumbs
 8222:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 8223:     my $prevphasestr;
 8224:     if ($env{'form.popup'}) {
 8225:         $brcrum = [];
 8226:     } else {
 8227:         push (@{$brcrum},
 8228:             {href => "javascript:backPage($form)",
 8229:              text => $breadcrumb_text{'search'}});
 8230:         my @prevphases;
 8231:         if ($env{'form.prevphases'}) {
 8232:             @prevphases = split(/,/,$env{'form.prevphases'});
 8233:             $prevphasestr = $env{'form.prevphases'};
 8234:         }
 8235:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 8236:             push(@{$brcrum},
 8237:                   {href => "javascript:backPage($form,'get_user_info','select')",
 8238:                    text => $breadcrumb_text{'userpicked'}});
 8239:             if ($env{'form.phase'} eq 'userpicked') {
 8240:                 $prevphasestr = 'userpicked';
 8241:             }
 8242:         }
 8243:     }
 8244:     push(@{$brcrum},
 8245:              {href => '/adm/createuser?action=accesslogs',
 8246:               text => 'User access logs',
 8247:               help => 'Domain_User_Access_Logs'});
 8248:     my $bread_crumbs_component = 'User Access Logs';
 8249:     my $args = { bread_crumbs           => $brcrum,
 8250:                  bread_crumbs_component => 'User Management'};
 8251:     if ($env{'form.popup'}) {
 8252:         $args->{'no_nav_bar'} = 1;
 8253:         $args->{'bread_crumbs_nomenu'} = 1;
 8254:     }
 8255: 
 8256: # set javascript
 8257:     my ($jsback,$elements) = &crumb_utilities();
 8258:     my $jsnav = &userlogdisplay_js($formname);
 8259: 
 8260:     my $jscript = (<<ENDSCRIPT);
 8261: <script type="text/javascript">
 8262: // <![CDATA[
 8263: 
 8264: $jsback
 8265: $jsnav
 8266: 
 8267: // ]]>
 8268: </script>
 8269: 
 8270: ENDSCRIPT
 8271: 
 8272: # print page header
 8273:     $r->print(&header($jscript,$args));
 8274: 
 8275: # early out unless log data can be displayed.
 8276:     unless ($permission->{'activity'}) {
 8277:         $r->print('<p class="LC_warning">'
 8278:                  .&mt('You do not have rights to display user access logs.')
 8279:                  .'</p>');
 8280:         if ($env{'form.popup'}) {
 8281:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8282:         } else {
 8283:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8284:         }
 8285:         return;
 8286:     }
 8287: 
 8288:     unless ($udom eq $env{'request.role.domain'}) {
 8289:         $r->print('<p class="LC_warning">'
 8290:                  .&mt("User's domain must match role's domain")
 8291:                  .'</p>'
 8292:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8293:         return;
 8294:     }
 8295: 
 8296:     if (($uname eq '') || ($udom eq '')) {
 8297:         $r->print('<p class="LC_warning">'
 8298:                  .&mt('Invalid username or domain')
 8299:                  .'</p>'
 8300:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8301:         return;
 8302:     }
 8303: 
 8304:     if (&Apache::lonnet::privileged($uname,$udom,
 8305:                                     [$env{'request.role.domain'}],['dc','su'])) {
 8306:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 8307:                                             [$env{'request.role.domain'}],['dc','su'])) {
 8308:             $r->print('<p class="LC_warning">'
 8309:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 8310:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 8311:                                                          $uname,$udom))
 8312:                  .'</p>');
 8313:             if ($env{'form.popup'}) {
 8314:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8315:             } else {
 8316:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8317:             }
 8318:             return;
 8319:         }
 8320:     }
 8321: 
 8322: # set defaults
 8323:     my $now = time();
 8324:     my $defstart = $now - (7*24*3600);
 8325:     my %defaults = (
 8326:                      page                 => '1',
 8327:                      show                 => '10',
 8328:                      activity             => 'any',
 8329:                      accesslog_start_date => $defstart,
 8330:                      accesslog_end_date   => $now,
 8331:                    );
 8332:     my $more_records = 0;
 8333: 
 8334: # set current
 8335:     my %curr;
 8336:     foreach my $item ('show','page','activity') {
 8337:         $curr{$item} = $env{'form.'.$item};
 8338:     }
 8339:     my ($startdate,$enddate) =
 8340:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 8341:     $curr{'accesslog_start_date'} = $startdate;
 8342:     $curr{'accesslog_end_date'} = $enddate;
 8343:     foreach my $key (keys(%defaults)) {
 8344:         if ($curr{$key} eq '') {
 8345:             $curr{$key} = $defaults{$key};
 8346:         }
 8347:     }
 8348:     my ($minshown,$maxshown);
 8349:     $minshown = 1;
 8350:     my $count = 0;
 8351:     if ($curr{'show'} =~ /\D/) {
 8352:         $curr{'page'} = 1;
 8353:     } else {
 8354:         $maxshown = $curr{'page'} * $curr{'show'};
 8355:         if ($curr{'page'} > 1) {
 8356:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8357:         }
 8358:     }
 8359: 
 8360: # form header
 8361:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8362:               &activity_display_filter($formname,\%curr));
 8363: 
 8364:     my $showntableheader = 0;
 8365:     my ($nav_script,$nav_links);
 8366: 
 8367: # table header
 8368:     my $heading = '<h3>'.
 8369:         &mt('User access logs for: [_1]',
 8370:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 8371:     my $tableheader = $heading
 8372:        .&Apache::loncommon::start_data_table_header_row()
 8373:        .'<th>&nbsp;</th>'
 8374:        .'<th>'.&mt('When').'</th>'
 8375:        .'<th>'.&mt('HostID').'</th>'
 8376:        .'<th>'.&mt('Event').'</th>'
 8377:        .'<th>'.&mt('Other data').'</th>'
 8378:        .&Apache::loncommon::end_data_table_header_row();
 8379: 
 8380:     my %filters=(
 8381:         start  => $curr{'accesslog_start_date'},
 8382:         end    => $curr{'accesslog_end_date'},
 8383:         action => $curr{'activity'},
 8384:     );
 8385: 
 8386:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 8387:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8388:         my (%courses,%missing);
 8389:         my @results = split(/\&/,$reply);
 8390:         foreach my $item (reverse(@results)) {
 8391:             my ($timestamp,$host,$event) = split(/:/,$item);
 8392:             next unless ($event =~ /^(Log|Role)/);
 8393:             if ($curr{'show'} !~ /\D/) {
 8394:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 8395:                     $more_records = 1;
 8396:                     last;
 8397:                 }
 8398:             }
 8399:             $count ++;
 8400:             next if ($count < $minshown);
 8401:             unless ($showntableheader) {
 8402:                 $r->print($nav_script
 8403:                          .&Apache::loncommon::start_data_table()
 8404:                          .$tableheader);
 8405:                 $r->rflush();
 8406:                 $showntableheader = 1;
 8407:             }
 8408:             my ($shown,$extra);
 8409:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 8410:             if ($event eq 'Role') {
 8411:                 my ($rolecode,$extent) = split(/\./,$data,2);
 8412:                 next if ($extent eq '');
 8413:                 my ($crstype,$desc,$info);
 8414:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 8415:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 8416:                     my $cid = $cdom.'_'.$cnum;
 8417:                     if (exists($courses{$cid})) {
 8418:                         $crstype = $courses{$cid}{'type'};
 8419:                         $desc = $courses{$cid}{'description'};
 8420:                     } elsif ($missing{$cid}) {
 8421:                         $crstype = 'Course';
 8422:                         $desc = 'Course/Community';
 8423:                     } else {
 8424:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8425:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 8426:                             $courses{$cid} = $crsinfo{$cid};
 8427:                             $crstype = $crsinfo{$cid}{'type'};
 8428:                             $desc = $crsinfo{$cid}{'description'};
 8429:                         } else {
 8430:                             $missing{$cid} = 1;
 8431:                         }
 8432:                     }
 8433:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 8434:                     if ($sec ne '') {
 8435:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 8436:                     }
 8437:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 8438:                     my ($dom,$name) = ($1,$2);
 8439:                     if ($rolecode eq 'au') {
 8440:                         $extra = '';
 8441:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 8442:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 8443:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 8444:                         $extra = &mt('Domain: [_1]',$dom);
 8445:                     }
 8446:                 }
 8447:                 my $rolename;
 8448:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 8449:                     my $role = $3;
 8450:                     my $owner = "($2:$1)";
 8451:                     if ($2 eq $1.'-domainconfig') {
 8452:                         $owner = '(ad hoc)';
 8453:                     }
 8454:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 8455:                 } else {
 8456:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 8457:                 }
 8458:                 $shown = &mt('Role selection: [_1]',$rolename);
 8459:             } else {
 8460:                 $shown = &mt($event);
 8461:                 if ($data =~ /^webdav/) {
 8462:                     my ($path,$clientip) = split(/\s+/,$data,2);
 8463:                     $path =~ s/^webdav//;
 8464:                     if ($clientip ne '') {
 8465:                         $extra = &mt('Client IP address: [_1]',$clientip);
 8466:                     }
 8467:                     if ($path ne '') {
 8468:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 8469:                     }
 8470:                 } elsif ($data ne '') {
 8471:                     $extra = &mt('Client IP address: [_1]',$data);
 8472:                 }
 8473:             }
 8474:             $r->print(
 8475:             &Apache::loncommon::start_data_table_row()
 8476:            .'<td>'.$count.'</td>'
 8477:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 8478:            .'<td>'.$host.'</td>'
 8479:            .'<td>'.$shown.'</td>'
 8480:            .'<td>'.$extra.'</td>'
 8481:            .&Apache::loncommon::end_data_table_row()."\n");
 8482:         }
 8483:     }
 8484: 
 8485:     if ($showntableheader) { # Table footer, if content displayed above
 8486:         $r->print(&Apache::loncommon::end_data_table().
 8487:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8488:     } else { # No content displayed above
 8489:         $r->print($heading.'<p class="LC_info">'
 8490:                  .&mt('There are no records to display.')
 8491:                  .'</p>');
 8492:     }
 8493: 
 8494:     if ($env{'form.popup'} == 1) {
 8495:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 8496:     }
 8497: 
 8498:     # Form Footer
 8499:     $r->print(
 8500:         '<input type="hidden" name="currstate" value="" />'
 8501:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 8502:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 8503:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8504:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 8505:        .'<input type="hidden" name="phase" value="activity" />'
 8506:        .'<input type="hidden" name="action" value="accesslogs" />'
 8507:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 8508:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 8509:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 8510:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 8511:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 8512:        .'</form>');
 8513:     return;
 8514: }
 8515: 
 8516: sub earlyout_accesslog_form {
 8517:     my ($formname,$prevphasestr,$udom) = @_;
 8518:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 8519:    return <<"END";
 8520: <form action="/adm/createuser" method="post" name="$formname">
 8521: <input type="hidden" name="currstate" value="" />
 8522: <input type="hidden" name="prevphases" value="$prevphasestr" />
 8523: <input type="hidden" name="phase" value="activity" />
 8524: <input type="hidden" name="action" value="accesslogs" />
 8525: <input type="hidden" name="srchdomain" value="$udom" />
 8526: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 8527: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 8528: <input type="hidden" name="srchterm" value="$srchterm" />
 8529: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 8530: </form>
 8531: END
 8532: }
 8533: 
 8534: sub activity_display_filter {
 8535:     my ($formname,$curr) = @_;
 8536:     my $nolink = 1;
 8537:     my $output = '<table><tr><td valign="top">'.
 8538:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 8539:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8540:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8541:                  '</td><td>&nbsp;&nbsp;</td>';
 8542:     my $startform =
 8543:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 8544:                                             $curr->{'accesslog_start_date'},undef,
 8545:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8546:     my $endform =
 8547:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 8548:                                             $curr->{'accesslog_end_date'},undef,
 8549:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8550:     my %lt = &Apache::lonlocal::texthash (
 8551:                                           activity => 'Activity',
 8552:                                           Role     => 'Role selection',
 8553:                                           log      => 'Log-in or Logout',
 8554:     );
 8555:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 8556:                '<table><tr><td>'.&mt('After:').
 8557:                '</td><td>'.$startform.'</td></tr>'.
 8558:                '<tr><td>'.&mt('Before:').'</td>'.
 8559:                '<td>'.$endform.'</td></tr></table>'.
 8560:                '</td>'.
 8561:                '<td>&nbsp;&nbsp;</td>'.
 8562:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 8563:                '<select name="activity"><option value="any"';
 8564:     if ($curr->{'activity'} eq 'any') {
 8565:         $output .= ' selected="selected"';
 8566:     }
 8567:     $output .= '>'.&mt('Any').'</option>'."\n";
 8568:     foreach my $activity ('Role','log') {
 8569:         my $selstr = '';
 8570:         if ($activity eq $curr->{'activity'}) {
 8571:             $selstr = ' selected="selected"';
 8572:         }
 8573:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 8574:     }
 8575:     $output .= '</select></td>'.
 8576:                '</tr></table>';
 8577:     # Update Display button
 8578:     $output .= '<p>'
 8579:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8580:               .'</p><hr />';
 8581:     return $output;
 8582: }
 8583: 
 8584: sub userlogdisplay_js {
 8585:     my ($formname) = @_;
 8586:     return <<"ENDSCRIPT";
 8587: 
 8588: function chgPage(caller) {
 8589:     if (caller == 'previous') {
 8590:         document.$formname.page.value --;
 8591:     }
 8592:     if (caller == 'next') {
 8593:         document.$formname.page.value ++;
 8594:     }
 8595:     document.$formname.submit();
 8596:     return;
 8597: }
 8598: ENDSCRIPT
 8599: }
 8600: 
 8601: sub userlogdisplay_navlinks {
 8602:     my ($curr,$more_records) = @_;
 8603:     return unless(ref($curr) eq 'HASH');
 8604:     # Navigation Buttons
 8605:     my $nav_links = '<p>';
 8606:     if (($curr->{'page'} > 1) || ($more_records)) {
 8607:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 8608:             $nav_links .= '<input type="button"'
 8609:                          .' onclick="javascript:chgPage('."'previous'".');"'
 8610:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 8611:                          .'" /> ';
 8612:         }
 8613:         if ($more_records) {
 8614:             $nav_links .= '<input type="button"'
 8615:                          .' onclick="javascript:chgPage('."'next'".');"'
 8616:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 8617:                          .'" />';
 8618:         }
 8619:     }
 8620:     $nav_links .= '</p>';
 8621:     return $nav_links;
 8622: }
 8623: 
 8624: sub role_display_filter {
 8625:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 8626:     my $nolink = 1;
 8627:     my $output = '<table><tr><td valign="top">'.
 8628:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 8629:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8630:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8631:                  '</td><td>&nbsp;&nbsp;</td>';
 8632:     my $startform =
 8633:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 8634:                                             $curr->{'rolelog_start_date'},undef,
 8635:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8636:     my $endform =
 8637:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 8638:                                             $curr->{'rolelog_end_date'},undef,
 8639:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8640:     my %lt = &rolechg_contexts($context,$crstype);
 8641:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 8642:                '<table><tr><td>'.&mt('After:').
 8643:                '</td><td>'.$startform.'</td></tr>'.
 8644:                '<tr><td>'.&mt('Before:').'</td>'.
 8645:                '<td>'.$endform.'</td></tr></table>'.
 8646:                '</td>'.
 8647:                '<td>&nbsp;&nbsp;</td>'.
 8648:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 8649:                '<select name="role"><option value="any"';
 8650:     if ($curr->{'role'} eq 'any') {
 8651:         $output .= ' selected="selected"';
 8652:     }
 8653:     $output .= '>'.&mt('Any').'</option>'."\n";
 8654:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 8655:     foreach my $role (@roles) {
 8656:         my $plrole;
 8657:         if ($role eq 'cr') {
 8658:             $plrole = &mt('Custom Role');
 8659:         } else {
 8660:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8661:         }
 8662:         my $selstr = '';
 8663:         if ($role eq $curr->{'role'}) {
 8664:             $selstr = ' selected="selected"';
 8665:         }
 8666:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 8667:     }
 8668:     $output .= '</select></td>'.
 8669:                '<td>&nbsp;&nbsp;</td>'.
 8670:                '<td valign="top"><b>'.
 8671:                &mt('Context:').'</b><br /><select name="chgcontext">';
 8672:     my @posscontexts;
 8673:     if ($context eq 'course') {
 8674:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype','ltienroll');
 8675:     } elsif ($context eq 'domain') {
 8676:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 8677:     } else {
 8678:         @posscontexts = ('any','author','coauthor','domain');
 8679:     }
 8680:     foreach my $chgtype (@posscontexts) {
 8681:         my $selstr = '';
 8682:         if ($curr->{'chgcontext'} eq $chgtype) {
 8683:             $selstr = ' selected="selected"';
 8684:         }
 8685:         if ($context eq 'course') {
 8686:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 8687:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 8688:             }
 8689:         }
 8690:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 8691:     }
 8692:     my @possapprovals = ('any','none','domain','user');
 8693:     my %apptxt = &approval_types();
 8694:     $output .= '</select></td>'.
 8695:                '<td>&nbsp;&nbsp;</td>'.
 8696:                '<td valign="top"><b>'.
 8697:                &mt('Approvals:').'</b><br /><select name="approvals">';
 8698:     foreach my $approval (@possapprovals) {
 8699:         my $selstr = '';
 8700:         if ($curr->{'approvals'} eq $approval) {
 8701:             $selstr = ' selected="selected"';
 8702:         }    
 8703:         $output .= '<option value="'.$approval.'"'.$selstr.'>'.$apptxt{$approval}.'</option>';
 8704:     }
 8705:     $output .= '</select></td></tr></table>';
 8706: 
 8707:     # Update Display button
 8708:     $output .= '<p>'
 8709:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8710:               .'</p>';
 8711: 
 8712:     # Server version info
 8713:     my $needsrev = '2.11.0';
 8714:     if ($context eq 'course') {
 8715:         $needsrev = '2.7.0';
 8716:     }
 8717:     
 8718:     $output .= '<p class="LC_info">'
 8719:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 8720:                   ,$needsrev);
 8721:     if ($version) {
 8722:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 8723:     }
 8724:     $output .= '</p><hr />';
 8725:     return $output;
 8726: }
 8727: 
 8728: sub rolechg_contexts {
 8729:     my ($context,$crstype) = @_;
 8730:     my %lt;
 8731:     if ($context eq 'course') {
 8732:         %lt = &Apache::lonlocal::texthash (
 8733:                                              any          => 'Any',
 8734:                                              automated    => 'Automated Enrollment',
 8735:                                              chgtype      => 'Enrollment Type/Lock Change',
 8736:                                              updatenow    => 'Roster Update',
 8737:                                              createcourse => 'Course Creation',
 8738:                                              course       => 'User Management in course',
 8739:                                              domain       => 'User Management in domain',
 8740:                                              selfenroll   => 'Self-enrolled',
 8741:                                              requestcourses => 'Course Request',
 8742:                                              ltienroll    => 'Enrollment via LTI',
 8743:                                          );
 8744:         if ($crstype eq 'Community') {
 8745:             $lt{'createcourse'} = &mt('Community Creation');
 8746:             $lt{'course'} = &mt('User Management in community');
 8747:             $lt{'requestcourses'} = &mt('Community Request');
 8748:         }
 8749:     } elsif ($context eq 'domain') {
 8750:         %lt = &Apache::lonlocal::texthash (
 8751:                                              any           => 'Any',
 8752:                                              domain        => 'User Management in domain',
 8753:                                              requestauthor => 'Authoring Request',
 8754:                                              server        => 'Command line script (DC role)',
 8755:                                              domconfig     => 'Self-enrolled',
 8756:                                          );
 8757:     } else {
 8758:         %lt = &Apache::lonlocal::texthash (
 8759:                                              any    => 'Any',
 8760:                                              domain => 'User Management in domain',
 8761:                                              author => 'User Management by author',
 8762:                                              coauthor => 'User Management by coauthor',
 8763:                                          );
 8764:     } 
 8765:     return %lt;
 8766: }
 8767: 
 8768: sub approval_types {
 8769:     return &Apache::lonlocal::texthash (
 8770:                                           any => 'Any',
 8771:                                           none => 'No approval needed',
 8772:                                           user => 'Role recipient approval',
 8773:                                           domain => 'Domain coordinator approval',
 8774:                                        );
 8775: }
 8776: 
 8777: sub print_helpdeskaccess_display {
 8778:     my ($r,$permission,$brcrum) = @_;
 8779:     my $formname = 'helpdeskaccess';
 8780:     my $helpitem = 'Course_Helpdesk_Access';
 8781:     push (@{$brcrum},
 8782:              {href => '/adm/createuser?action=helpdesk',
 8783:               text => 'Helpdesk Access',
 8784:               help => $helpitem});
 8785:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8786:     my $args = { bread_crumbs           => $brcrum,
 8787:                  bread_crumbs_component => $bread_crumbs_component};
 8788: 
 8789:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8790:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8791:     my $confname = $cdom.'-domainconfig';
 8792:     my $crstype = &Apache::loncommon::course_type();
 8793: 
 8794:     my @accesstypes = ('all','dh','da','none');
 8795:     my ($numstatustypes,@jsarray);
 8796:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8797:     if (ref($types) eq 'ARRAY') {
 8798:         if (@{$types} > 0) {
 8799:             $numstatustypes = scalar(@{$types});
 8800:             push(@accesstypes,'status');
 8801:             @jsarray = ('bystatus');
 8802:         }
 8803:     }
 8804:     my %customroles = &get_domain_customroles($cdom,$confname);
 8805:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8806:     if (keys(%domhelpdesk)) {
 8807:        push(@accesstypes,('inc','exc'));
 8808:        push(@jsarray,('notinc','notexc'));
 8809:     }
 8810:     push(@jsarray,'privs');
 8811:     my $hiddenstr = join("','",@jsarray);
 8812:     my $rolestr = join("','",sort(keys(%customroles)));
 8813: 
 8814:     my $jscript;
 8815:     my (%settings,%overridden);
 8816:     if (keys(%customroles)) {
 8817:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8818:                                 $types,\%customroles,\%settings,\%overridden);
 8819:         my %jsfull=();
 8820:         my %jslevels= (
 8821:                      course => {},
 8822:                      domain => {},
 8823:                      system => {},
 8824:                     );
 8825:         my %jslevelscurrent=(
 8826:                            course => {},
 8827:                            domain => {},
 8828:                            system => {},
 8829:                           );
 8830:         my (%privs,%jsprivs);
 8831:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 8832:         foreach my $priv (keys(%jsfull)) {
 8833:             if ($jslevels{'course'}{$priv}) {
 8834:                 $jsprivs{$priv} = 1;
 8835:             }
 8836:         }
 8837:         my (%elements,%stored);
 8838:         foreach my $role (keys(%customroles)) {
 8839:             $elements{$role.'_access'} = 'radio';
 8840:             $elements{$role.'_incrs'} = 'radio';
 8841:             if ($numstatustypes) {
 8842:                 $elements{$role.'_status'} = 'checkbox';
 8843:             }
 8844:             if (keys(%domhelpdesk) > 0) {
 8845:                 $elements{$role.'_staff_inc'} = 'checkbox';
 8846:                 $elements{$role.'_staff_exc'} = 'checkbox';
 8847:             }
 8848:             $elements{$role.'_override'} = 'checkbox';
 8849:             if (ref($settings{$role}) eq 'HASH') {
 8850:                 if ($settings{$role}{'access'} ne '') {
 8851:                     my $curraccess = $settings{$role}{'access'};
 8852:                     $stored{$role.'_access'} = $curraccess;
 8853:                     $stored{$role.'_incrs'} = 1;
 8854:                     if ($curraccess eq 'status') {
 8855:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 8856:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 8857:                         }
 8858:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8859:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 8860:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 8861:                         }
 8862:                     }
 8863:                 } else {
 8864:                     $stored{$role.'_incrs'} = 0;
 8865:                 }
 8866:                 $stored{$role.'_override'} = [];
 8867:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 8868:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 8869:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 8870:                             push(@{$stored{$role.'_override'}},$priv);
 8871:                         }
 8872:                     }
 8873:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 8874:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 8875:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 8876:                                 push(@{$stored{$role.'_override'}},$priv);
 8877:                             }
 8878:                         }
 8879:                     }
 8880:                 }
 8881:             } else {
 8882:                 $stored{$role.'_incrs'} = 0;
 8883:             }
 8884:         }
 8885:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 8886:     }
 8887: 
 8888:     my $js = <<"ENDJS";
 8889: <script type="text/javascript">
 8890: // <![CDATA[
 8891: $jscript;
 8892: 
 8893: function switchRoleTab(caller,role) {
 8894:     if (document.getElementById(role+'_maindiv')) {
 8895:         if (caller.id != 'LC_current_minitab') {
 8896:             if (document.getElementById('LC_current_minitab')) {
 8897:                 document.getElementById('LC_current_minitab').id=null;
 8898:             }
 8899:             var roledivs = Array('$rolestr');
 8900:             if (roledivs.length > 0) {
 8901:                 for (var i=0; i<roledivs.length; i++) {
 8902:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 8903:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 8904:                     }
 8905:                 }
 8906:             }
 8907:             caller.id = 'LC_current_minitab';
 8908:             document.getElementById(role+'_maindiv').style.display='block';
 8909:         }
 8910:     }
 8911:     return false;
 8912: }
 8913: 
 8914: function helpdeskAccess(role) {
 8915:     var curraccess = null;
 8916:     if (document.$formname.elements[role+'_access'].length) {
 8917:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 8918:             if (document.$formname.elements[role+'_access'][i].checked) {
 8919:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 8920:             }
 8921:         }
 8922:     }
 8923:     var shown = Array();
 8924:     var hidden = Array();
 8925:     if (curraccess == 'none') {
 8926:         hidden = Array ('$hiddenstr');
 8927:     } else {
 8928:         if (curraccess == 'status') {
 8929:             shown = Array ('bystatus','privs');
 8930:             hidden = Array ('notinc','notexc');
 8931:         } else {
 8932:             if (curraccess == 'exc') {
 8933:                 shown = Array ('notexc','privs');
 8934:                 hidden = Array ('notinc','bystatus');
 8935:             }
 8936:             if (curraccess == 'inc') {
 8937:                 shown = Array ('notinc','privs');
 8938:                 hidden = Array ('notexc','bystatus');
 8939:             }
 8940:             if (curraccess == 'all') {
 8941:                 shown = Array ('privs');
 8942:                 hidden = Array ('notinc','notexc','bystatus');
 8943:             }
 8944:         }
 8945:     }
 8946:     if (hidden.length > 0) {
 8947:         for (var i=0; i<hidden.length; i++) {
 8948:             if (document.getElementById(role+'_'+hidden[i])) {
 8949:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 8950:             }
 8951:         }
 8952:     }
 8953:     if (shown.length > 0) {
 8954:         for (var i=0; i<shown.length; i++) {
 8955:             if (document.getElementById(role+'_'+shown[i])) {
 8956:                 if (shown[i] == 'privs') {
 8957:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 8958:                 } else {
 8959:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 8960:                 }
 8961:             }
 8962:         }
 8963:     }
 8964:     return;
 8965: }
 8966: 
 8967: function toggleAccess(role) {
 8968:     if ((document.getElementById(role+'_setincrs')) &&
 8969:         (document.getElementById(role+'_setindom'))) {
 8970:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 8971:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 8972:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 8973:                     document.getElementById(role+'_setindom').style.display = 'none';
 8974:                     document.getElementById(role+'_setincrs').style.display = 'block';
 8975:                 } else {
 8976:                     document.getElementById(role+'_setincrs').style.display = 'none';
 8977:                     document.getElementById(role+'_setindom').style.display = 'block';
 8978:                 }
 8979:                 break;
 8980:             }
 8981:         }
 8982:     }
 8983:     return;
 8984: }
 8985: 
 8986: // ]]>
 8987: </script>
 8988: ENDJS
 8989: 
 8990:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 8991: 
 8992:     # print page header
 8993:     $r->print(&header($js,$args));
 8994:     # print form header
 8995:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 8996: 
 8997:     if (keys(%customroles)) {
 8998:         my %lt = &Apache::lonlocal::texthash(
 8999:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 9000:                     'rou'    => 'Role usage',
 9001:                     'whi'    => 'Which helpdesk personnel may use this role?',
 9002:                     'udd'    => 'Use domain default',
 9003:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 9004:                     'dh'     => 'All with domain helpdesk role',
 9005:                     'da'     => 'All with domain helpdesk assistant role',
 9006:                     'none'   => 'None',
 9007:                     'status' => 'Determined based on institutional status',
 9008:                     'inc'    => 'Include all, but exclude specific personnel',
 9009:                     'exc'    => 'Exclude all, but include specific personnel',
 9010:                     'hel'    => 'Helpdesk',
 9011:                     'rpr'    => 'Role privileges',
 9012:                  );
 9013:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 9014:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9015:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 9016:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9017:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9018:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9019:             }
 9020:         }
 9021:         my $count = 0;
 9022:         foreach my $role (sort(keys(%customroles))) {
 9023:             my ($order,$desc,$access_in_dom);
 9024:             if (ref($domcurrent{$role}) eq 'HASH') {
 9025:                 $order = $domcurrent{$role}{'order'};
 9026:                 $desc = $domcurrent{$role}{'desc'};
 9027:                 $access_in_dom = $domcurrent{$role}{'access'};
 9028:             }
 9029:             if ($order eq '') {
 9030:                 $order = $count;
 9031:             }
 9032:             $ordered{$order} = $role;
 9033:             if ($desc ne '') {
 9034:                 $description{$role} = $desc;
 9035:             } else {
 9036:                 $description{$role}= $role;
 9037:             }
 9038:             $count++;
 9039:         }
 9040:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9041:         my @roles_by_num = ();
 9042:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9043:             push(@roles_by_num,$ordered{$item});
 9044:         }
 9045:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 9046:         if ($permission->{'owner'}) {
 9047:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 9048:             $r->print('<input type="hidden" name="state" value="process" />'.
 9049:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 9050:         } else {
 9051:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 9052:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 9053:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 9054:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 9055:             }
 9056:             $disabled = ' disabled="disabled"';
 9057:         }
 9058:         $r->print('</p>');
 9059: 
 9060:         $r->print('<div id="LC_minitab_header"><ul>');
 9061:         my $count = 0;
 9062:         my %visibility;
 9063:         foreach my $role (@roles_by_num) {
 9064:             my $id;
 9065:             if ($count == 0) {
 9066:                 $id=' id="LC_current_minitab"';
 9067:                 $visibility{$role} = ' style="display:block"';
 9068:             } else {
 9069:                 $visibility{$role} = ' style="display:none"';
 9070:             }
 9071:             $count ++;
 9072:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 9073:         }
 9074:         $r->print('</ul></div>');
 9075: 
 9076:         foreach my $role (@roles_by_num) {
 9077:             my %usecheck = (
 9078:                              all => ' checked="checked"',
 9079:                            );
 9080:             my %displaydiv = (
 9081:                                 status => 'none',
 9082:                                 inc    => 'none',
 9083:                                 exc    => 'none',
 9084:                                 priv   => 'block',
 9085:                              );
 9086:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 9087:             if (ref($settings{$role}) eq 'HASH') {
 9088:                 if ($settings{$role}{'access'} ne '') {
 9089:                     $indomvis = ' style="display:none"';
 9090:                     $incrsvis = ' style="display:block"';
 9091:                     $incrscheck = ' checked="checked"';
 9092:                     if ($settings{$role}{'access'} ne 'all') {
 9093:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 9094:                         delete($usecheck{'all'});
 9095:                         if ($settings{$role}{'access'} eq 'status') {
 9096:                             my $access = 'status';
 9097:                             $displaydiv{$access} = 'inline';
 9098:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9099:                                 $selected{$access} = $settings{$role}{$access};
 9100:                             }
 9101:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 9102:                             my $access = $1;
 9103:                             $displaydiv{$access} = 'inline';
 9104:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9105:                                 $selected{$access} = $settings{$role}{$access};
 9106:                             }
 9107:                         } elsif ($settings{$role}{'access'} eq 'none') {
 9108:                             $displaydiv{'priv'} = 'none';
 9109:                         }
 9110:                     }
 9111:                 } else {
 9112:                     $indomcheck = ' checked="checked"';
 9113:                     $indomvis = ' style="display:block"';
 9114:                     $incrsvis = ' style="display:none"';
 9115:                 }
 9116:             } else {
 9117:                 $indomcheck = ' checked="checked"';
 9118:                 $indomvis = ' style="display:block"';
 9119:                 $incrsvis = ' style="display:none"';
 9120:             }
 9121:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 9122:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 9123:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 9124:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9125:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 9126:                       '<span>'.('&nbsp;'x2).
 9127:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9128:                       $lt{'udd'}.'</label><span></p>'.
 9129:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 9130:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 9131:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 9132:             foreach my $access (@accesstypes) {
 9133:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 9134:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 9135:                 if ($access eq 'status') {
 9136:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 9137:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 9138:                                                                         $othertitle,$usertypes,$types,$disabled).
 9139:                               '</div>');
 9140:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 9141:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 9142:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9143:                                                                  \%domhelpdesk,$disabled).
 9144:                               '</div>');
 9145:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 9146:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 9147:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9148:                                                                  \%domhelpdesk,$disabled).
 9149:                               '</div>');
 9150:                 }
 9151:                 $r->print('</p>');
 9152:             }
 9153:             $r->print('</div></fieldset>');
 9154:             my %full=();
 9155:             my %levels= (
 9156:                          course => {},
 9157:                          domain => {},
 9158:                          system => {},
 9159:                         );
 9160:             my %levelscurrent=(
 9161:                                course => {},
 9162:                                domain => {},
 9163:                                system => {},
 9164:                               );
 9165:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9166:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 9167:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 9168:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 9169:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 9170:         }
 9171:         if ($permission->{'owner'}) {
 9172:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 9173:         }
 9174:     } else {
 9175:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 9176:     }
 9177:     # Form Footer
 9178:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 9179:              .'</form>');
 9180:     return;
 9181: }
 9182: 
 9183: sub print_queued_roles {
 9184:     my ($r,$context,$permission,$brcrum) = @_;
 9185:     push (@{$brcrum},
 9186:              {href => '/adm/createuser?action=rolerequests',
 9187:               text => 'Role Requests (other domains)',
 9188:               help => ''});
 9189:     my $bread_crumbs_component = 'Role Requests';
 9190:     my $args = { bread_crumbs           => $brcrum,
 9191:                  bread_crumbs_component => $bread_crumbs_component};
 9192:     # print page header
 9193:     $r->print(&header('',$args));
 9194:     my ($dom,$cnum);
 9195:     $dom = $env{'request.role.domain'};
 9196:     if ($context eq 'course') {
 9197:         if ($env{'request.course.id'}) {
 9198:             if (&Apache::loncommon::course_type() eq 'Community') {
 9199:                 $context = 'community';
 9200:             }
 9201:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9202:         }
 9203:     } elsif ($context eq 'author') {
 9204:         $cnum = $env{'user.name'};
 9205:     }
 9206:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomqueue',$dom,$cnum,$context));
 9207:     return;
 9208: }
 9209: 
 9210: sub print_pendingroles {
 9211:     my ($r,$context,$permission,$brcrum) = @_;
 9212:     push (@{$brcrum},
 9213:              {href => '/adm/createuser?action=queuedroles',
 9214:               text => 'Queued Role Assignments (users in this domain)',
 9215:               help => ''});
 9216:     my $bread_crumbs_component = 'Queued Role Assignments';
 9217:     my $args = { bread_crumbs           => $brcrum,
 9218:                  bread_crumbs_component => $bread_crumbs_component};
 9219:     # print page header
 9220:     $r->print(&header('',$args));
 9221:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomaction',$env{'request.role.domain'},'','domain'));
 9222:     return;
 9223: }
 9224: 
 9225: sub process_pendingroles {
 9226:     my ($r,$context,$permission,$brcrum) = @_;
 9227:     push (@{$brcrum},
 9228:              {href => '/adm/createuser?action=queuedroles',
 9229:               text => 'Queued Role Assignments (users in this domain)',
 9230:               help => ''},
 9231:              {href => '/adm/createuser?action=processrolereq',
 9232:               text => 'Process Queue',
 9233:               help => ''});
 9234:     my $bread_crumbs_component = 'Queued Role Assignments';
 9235:     my $args = { bread_crumbs           => $brcrum,
 9236:                  bread_crumbs_component => $bread_crumbs_component};
 9237:     # print page header
 9238:     $r->print(&header('',$args));
 9239:     $r->print(&Apache::loncoursequeueadmin::update_request_queue('othdombydc',
 9240:                                                                  $env{'request.role.domain'}));
 9241:     return;
 9242: }
 9243: 
 9244: sub domain_adhoc_access {
 9245:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 9246:     my %domusage;
 9247:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 9248:     foreach my $role (keys(%{$roles})) {
 9249:         if (ref($domcurrent->{$role}) eq 'HASH') {
 9250:             my $access = $domcurrent->{$role}{'access'};
 9251:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 9252:                 $access = 'all';
 9253:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 9254:                                                                                           &Apache::lonnet::plaintext('da'));
 9255:             } elsif ($access eq 'status') {
 9256:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 9257:                     my @shown;
 9258:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 9259:                         unless ($type eq 'default') {
 9260:                             if ($usertypes->{$type}) {
 9261:                                 push(@shown,$usertypes->{$type});
 9262:                             }
 9263:                         }
 9264:                     }
 9265:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 9266:                         push(@shown,$othertitle);
 9267:                     }
 9268:                     if (@shown) {
 9269:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 9270:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 9271:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 9272:                     } else {
 9273:                         $domusage{$role} = &mt('No one in the domain');
 9274:                     }
 9275:                 }
 9276:             } elsif ($access eq 'inc') {
 9277:                 my @dominc = ();
 9278:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 9279:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 9280:                         my ($uname,$udom) = split(/:/,$user);
 9281:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9282:                     }
 9283:                     my $showninc = join(', ',@dominc);
 9284:                     if ($showninc ne '') {
 9285:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 9286:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 9287:                     } else {
 9288:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9289:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9290:                     }
 9291:                 }
 9292:             } elsif ($access eq 'exc') {
 9293:                 my @domexc = ();
 9294:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 9295:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 9296:                         my ($uname,$udom) = split(/:/,$user);
 9297:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9298:                     }
 9299:                 }
 9300:                 my $shownexc = join(', ',@domexc);
 9301:                 if ($shownexc ne '') {
 9302:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 9303:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 9304:                 } else {
 9305:                     $domusage{$role} = &mt('No one in the domain');
 9306:                 }
 9307:             } elsif ($access eq 'none') {
 9308:                 $domusage{$role} = &mt('No one in the domain');
 9309:             } elsif ($access eq 'dh') {
 9310:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 9311:             } elsif ($access eq 'da') {
 9312:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 9313:             } elsif ($access eq 'all') {
 9314:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9315:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9316:             }
 9317:         } else {
 9318:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9319:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9320:         }
 9321:     }
 9322:     return %domusage;
 9323: }
 9324: 
 9325: sub get_domain_customroles {
 9326:     my ($cdom,$confname) = @_;
 9327:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 9328:     my %customroles;
 9329:     foreach my $key (keys(%existing)) {
 9330:         if ($key=~/^rolesdef\_(\w+)$/) {
 9331:             my $rolename = $1;
 9332:             my %privs;
 9333:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 9334:             $customroles{$rolename} = \%privs;
 9335:         }
 9336:     }
 9337:     return %customroles;
 9338: }
 9339: 
 9340: sub role_priv_table {
 9341:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 9342:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 9343:                    (ref($levelscurrent) eq 'HASH'));
 9344:     my %lt=&Apache::lonlocal::texthash (
 9345:                     'crl'  => 'Course Level Privilege',
 9346:                     'def'  => 'Domain Defaults',
 9347:                     'ove'  => 'Override in Course',
 9348:                     'ine'  => 'In effect',
 9349:                     'dis'  => 'Disabled',
 9350:                     'ena'  => 'Enabled',
 9351:                    );
 9352:     if ($crstype eq 'Community') {
 9353:         $lt{'ove'} = 'Override in Community',
 9354:     }
 9355:     my @status = ('Disabled','Enabled');
 9356:     my (%on,%off);
 9357:     if (ref($overridden) eq 'HASH') {
 9358:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 9359:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 9360:         }
 9361:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 9362:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 9363:         }
 9364:     }
 9365:     my $output=&Apache::loncommon::start_data_table().
 9366:                &Apache::loncommon::start_data_table_header_row().
 9367:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 9368:                '</th><th>'.$lt{'ine'}.'</th>'.
 9369:                &Apache::loncommon::end_data_table_header_row();
 9370:     foreach my $priv (sort(keys(%{$full}))) {
 9371:         next unless ($levels->{'course'}{$priv});
 9372:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 9373:         my ($default,$ineffect);
 9374:         if ($levelscurrent->{'course'}{$priv}) {
 9375:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9376:             $ineffect = $default;
 9377:         }
 9378:         my ($customstatus,$checked);
 9379:         $output .= &Apache::loncommon::start_data_table_row().
 9380:                    '<td>'.$privtext.'</td>'.
 9381:                    '<td>'.$default.'</td><td>';
 9382:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 9383:             if ($permission->{'owner'}) {
 9384:                 $checked = ' checked="checked"';
 9385:             }
 9386:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 9387:             $ineffect = $customstatus;
 9388:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 9389:             if ($permission->{'owner'}) {
 9390:                 $checked = ' checked="checked"';
 9391:             }
 9392:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9393:             $ineffect = $customstatus;
 9394:         }
 9395:         if ($permission->{'owner'}) {
 9396:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 9397:         } else {
 9398:             $output .= $customstatus;
 9399:         }
 9400:         $output .= '</td><td>'.$ineffect.'</td>'.
 9401:                    &Apache::loncommon::end_data_table_row();
 9402:     }
 9403:     $output .= &Apache::loncommon::end_data_table();
 9404:     return $output;
 9405: }
 9406: 
 9407: sub get_adhocrole_settings {
 9408:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 9409:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 9410:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 9411:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 9412:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 9413:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 9414:             $settings->{$role}{'access'} = $curraccess;
 9415:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 9416:                 my @status = split(/,/,$rest);
 9417:                 my @currstatus;
 9418:                 foreach my $type (@status) {
 9419:                     if ($type eq 'default') {
 9420:                         push(@currstatus,$type);
 9421:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9422:                         push(@currstatus,$type);
 9423:                     }
 9424:                 }
 9425:                 if (@currstatus) {
 9426:                     $settings->{$role}{$curraccess} = \@currstatus;
 9427:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 9428:                     my @personnel = split(/,/,$rest);
 9429:                     $settings->{$role}{$curraccess} = \@personnel;
 9430:                 }
 9431:             }
 9432:         }
 9433:     }
 9434:     foreach my $role (keys(%{$customroles})) {
 9435:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 9436:             my %currentprivs;
 9437:             if (ref($customroles->{$role}) eq 'HASH') {
 9438:                 if (exists($customroles->{$role}{'course'})) {
 9439:                     my %full=();
 9440:                     my %levels= (
 9441:                                   course => {},
 9442:                                   domain => {},
 9443:                                   system => {},
 9444:                                 );
 9445:                     my %levelscurrent=(
 9446:                                         course => {},
 9447:                                         domain => {},
 9448:                                         system => {},
 9449:                                       );
 9450:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 9451:                     %currentprivs = %{$levelscurrent{'course'}};
 9452:                 }
 9453:             }
 9454:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 9455:                 next if ($item eq '');
 9456:                 my ($rule,$rest) = split(/=/,$item);
 9457:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 9458:                 foreach my $priv (split(/:/,$rest)) {
 9459:                     if ($priv ne '') {
 9460:                         if ($rule eq 'off') {
 9461:                             push(@{$overridden->{$role}{'off'}},$priv);
 9462:                             if ($currentprivs{$priv}) {
 9463:                                 push(@{$settings->{$role}{'off'}},$priv);
 9464:                             }
 9465:                         } else {
 9466:                             push(@{$overridden->{$role}{'on'}},$priv);
 9467:                             unless ($currentprivs{$priv}) {
 9468:                                 push(@{$settings->{$role}{'on'}},$priv);
 9469:                             }
 9470:                         }
 9471:                     }
 9472:                 }
 9473:             }
 9474:         }
 9475:     }
 9476:     return;
 9477: }
 9478: 
 9479: sub update_helpdeskaccess {
 9480:     my ($r,$permission,$brcrum) = @_;
 9481:     my $helpitem = 'Course_Helpdesk_Access';
 9482:     push (@{$brcrum},
 9483:              {href => '/adm/createuser?action=helpdesk',
 9484:               text => 'Helpdesk Access',
 9485:               help => $helpitem},
 9486:              {href => '/adm/createuser?action=helpdesk',
 9487:               text => 'Result',
 9488:               help => $helpitem}
 9489:          );
 9490:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 9491:     my $args = { bread_crumbs           => $brcrum,
 9492:                  bread_crumbs_component => $bread_crumbs_component};
 9493: 
 9494:     # print page header
 9495:     $r->print(&header('',$args));
 9496:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 9497:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 9498:         return;
 9499:     }
 9500:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 9501:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9502:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9503:     my $confname = $cdom.'-domainconfig';
 9504:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 9505:     my $crstype = &Apache::loncommon::course_type();
 9506:     my %customroles = &get_domain_customroles($cdom,$confname);
 9507:     my (%settings,%overridden);
 9508:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 9509:                             $types,\%customroles,\%settings,\%overridden);
 9510:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 9511:     my (%changed,%storehash,@todelete);
 9512: 
 9513:     if (keys(%customroles)) {
 9514:         my (%newsettings,@incrs);
 9515:         foreach my $role (keys(%customroles)) {
 9516:             $newsettings{$role} = {
 9517:                                     access => '',
 9518:                                     status => '',
 9519:                                     exc    => '',
 9520:                                     inc    => '',
 9521:                                     on     => '',
 9522:                                     off    => '',
 9523:                                   };
 9524:             my %current;
 9525:             if (ref($settings{$role}) eq 'HASH') {
 9526:                 %current = %{$settings{$role}};
 9527:             }
 9528:             if (ref($overridden{$role}) eq 'HASH') {
 9529:                 $current{'overridden'} = $overridden{$role};
 9530:             }
 9531:             if ($env{'form.'.$role.'_incrs'}) {
 9532:                 my $access = $env{'form.'.$role.'_access'};
 9533:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 9534:                     push(@incrs,$role);
 9535:                     unless ($current{'access'} eq $access) {
 9536:                         $changed{$role}{'access'} = 1;
 9537:                         $storehash{'internal.adhoc.'.$role} = $access;
 9538:                     }
 9539:                     if ($access eq 'status') {
 9540:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 9541:                         my @stored;
 9542:                         my @shownstatus;
 9543:                         if (ref($types) eq 'ARRAY') {
 9544:                             foreach my $type (sort(@statuses)) {
 9545:                                 if ($type eq 'default') {
 9546:                                     push(@stored,$type);
 9547:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9548:                                     push(@stored,$type);
 9549:                                     push(@shownstatus,$usertypes->{$type});
 9550:                                 }
 9551:                             }
 9552:                             if (grep(/^default$/,@statuses)) {
 9553:                                 push(@shownstatus,$othertitle);
 9554:                             }
 9555:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9556:                         }
 9557:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 9558:                         if (ref($current{'status'}) eq 'ARRAY') {
 9559:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 9560:                             if (@diffs) {
 9561:                                 $changed{$role}{'status'} = 1;
 9562:                             }
 9563:                         } elsif (@stored) {
 9564:                             $changed{$role}{'status'} = 1;
 9565:                         }
 9566:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 9567:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 9568:                         my @newspecstaff;
 9569:                         my @stored;
 9570:                         my @currstaff;
 9571:                         foreach my $person (sort(@personnel)) {
 9572:                             if ($domhelpdesk{$person}) {
 9573:                                 push(@stored,$person);
 9574:                             }
 9575:                         }
 9576:                         if (ref($current{$access}) eq 'ARRAY') {
 9577:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 9578:                             if (@diffs) {
 9579:                                 $changed{$role}{$access} = 1;
 9580:                             }
 9581:                         } elsif (@stored) {
 9582:                             $changed{$role}{$access} = 1;
 9583:                         }
 9584:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9585:                         foreach my $person (@stored) {
 9586:                             my ($uname,$udom) = split(/:/,$person);
 9587:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 9588:                         }
 9589:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 9590:                     }
 9591:                     $newsettings{$role}{'access'} = $access;
 9592:                 }
 9593:             } else {
 9594:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 9595:                     $changed{$role}{'access'} = 1;
 9596:                     $newsettings{$role} = {};
 9597:                     push(@todelete,'internal.adhoc.'.$role);
 9598:                 }
 9599:             }
 9600:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 9601:                 if (ref($current{'overridden'}) eq 'HASH') {
 9602:                     push(@todelete,'internal.adhocpriv.'.$role);
 9603:                 }
 9604:             } else {
 9605:                 my %full=();
 9606:                 my %levels= (
 9607:                              course => {},
 9608:                              domain => {},
 9609:                              system => {},
 9610:                             );
 9611:                 my %levelscurrent=(
 9612:                                    course => {},
 9613:                                    domain => {},
 9614:                                    system => {},
 9615:                                   );
 9616:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9617:                 my (@updatedon,@updatedoff,@override);
 9618:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 9619:                 if (@override) {
 9620:                     foreach my $priv (sort(keys(%full))) {
 9621:                         next unless ($levels{'course'}{$priv});
 9622:                         if (grep(/^\Q$priv\E$/,@override)) {
 9623:                             if ($levelscurrent{'course'}{$priv}) {
 9624:                                 push(@updatedoff,$priv);
 9625:                             } else {
 9626:                                 push(@updatedon,$priv);
 9627:                             }
 9628:                         }
 9629:                     }
 9630:                 }
 9631:                 if (@updatedon) {
 9632:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 9633:                 }
 9634:                 if (@updatedoff) {
 9635:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 9636:                 }
 9637:                 if (ref($current{'overridden'}) eq 'HASH') {
 9638:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 9639:                         if (@updatedon) {
 9640:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 9641:                             if (@diffs) {
 9642:                                 $changed{$role}{'on'} = 1;
 9643:                             }
 9644:                         } else {
 9645:                             $changed{$role}{'on'} = 1;
 9646:                         }
 9647:                     } elsif (@updatedon) {
 9648:                         $changed{$role}{'on'} = 1;
 9649:                     }
 9650:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 9651:                         if (@updatedoff) {
 9652:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 9653:                             if (@diffs) {
 9654:                                 $changed{$role}{'off'} = 1;
 9655:                             }
 9656:                         } else {
 9657:                             $changed{$role}{'off'} = 1;
 9658:                         }
 9659:                     } elsif (@updatedoff) {
 9660:                         $changed{$role}{'off'} = 1;
 9661:                     }
 9662:                 } else {
 9663:                     if (@updatedon) {
 9664:                         $changed{$role}{'on'} = 1;
 9665:                     }
 9666:                     if (@updatedoff) {
 9667:                         $changed{$role}{'off'} = 1;
 9668:                     }
 9669:                 }
 9670:                 if (ref($changed{$role}) eq 'HASH') {
 9671:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 9672:                         my $newpriv;
 9673:                         if (@updatedon) {
 9674:                             $newpriv = 'on='.join(':',@updatedon);
 9675:                         }
 9676:                         if (@updatedoff) {
 9677:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 9678:                         }
 9679:                         if ($newpriv eq '') {
 9680:                             push(@todelete,'internal.adhocpriv.'.$role);
 9681:                         } else {
 9682:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 9683:                         }
 9684:                     }
 9685:                 }
 9686:             }
 9687:         }
 9688:         if (@incrs) {
 9689:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 9690:         } elsif (@todelete) {
 9691:             push(@todelete,'internal.adhocaccess');
 9692:         }
 9693:         if (keys(%changed)) {
 9694:             my ($putres,$delres);
 9695:             if (keys(%storehash)) {
 9696:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 9697:                 my %newenvhash;
 9698:                 foreach my $key (keys(%storehash)) {
 9699:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 9700:                 }
 9701:                 &Apache::lonnet::appenv(\%newenvhash);
 9702:             }
 9703:             if (@todelete) {
 9704:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 9705:                 foreach my $key (@todelete) {
 9706:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 9707:                 }
 9708:             }
 9709:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 9710:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9711:                 my (%domcurrent,%ordered,%description,%domusage);
 9712:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9713:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9714:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9715:                     }
 9716:                 }
 9717:                 my $count = 0;
 9718:                 foreach my $role (sort(keys(%customroles))) {
 9719:                     my ($order,$desc);
 9720:                     if (ref($domcurrent{$role}) eq 'HASH') {
 9721:                         $order = $domcurrent{$role}{'order'};
 9722:                         $desc = $domcurrent{$role}{'desc'};
 9723:                     }
 9724:                     if ($order eq '') {
 9725:                         $order = $count;
 9726:                     }
 9727:                     $ordered{$order} = $role;
 9728:                     if ($desc ne '') {
 9729:                         $description{$role} = $desc;
 9730:                     } else {
 9731:                         $description{$role}= $role;
 9732:                     }
 9733:                     $count++;
 9734:                 }
 9735:                 my @roles_by_num = ();
 9736:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9737:                     push(@roles_by_num,$ordered{$item});
 9738:                 }
 9739:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9740:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 9741:                 $r->print('<ul>');
 9742:                 foreach my $role (@roles_by_num) {
 9743:                     next unless (ref($changed{$role}) eq 'HASH');
 9744:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 9745:                               '<ul>');
 9746:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 9747:                         $r->print('<li>');
 9748:                         if ($env{'form.'.$role.'_incrs'}) {
 9749:                             if ($newsettings{$role}{'access'} eq 'all') {
 9750:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 9751:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 9752:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9753:                                               &Apache::lonnet::plaintext('dh')));
 9754:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 9755:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9756:                                               &Apache::lonnet::plaintext('da')));
 9757:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 9758:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9759:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 9760:                                 if ($newsettings{$role}{'status'}) {
 9761:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 9762:                                     if (split(/,/,$rest) > 1) {
 9763:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 9764:                                                       $newsettings{$role}{'status'}));
 9765:                                     } else {
 9766:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 9767:                                                       $newsettings{$role}{'status'}));
 9768:                                     }
 9769:                                 } else {
 9770:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9771:                                 }
 9772:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 9773:                                 if ($newsettings{$role}{'exc'}) {
 9774:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 9775:                                 } else {
 9776:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9777:                                 }
 9778:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 9779:                                 if ($newsettings{$role}{'inc'}) {
 9780:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 9781:                                 } else {
 9782:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 9783:                                 }
 9784:                             }
 9785:                         } else {
 9786:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 9787:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 9788:                         }
 9789:                         $r->print('</li>');
 9790:                     }
 9791:                     unless ($newsettings{$role}{'access'} eq 'none') {
 9792:                         if ($changed{$role}{'off'}) {
 9793:                             if ($newsettings{$role}{'off'}) {
 9794:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 9795:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 9796:                             } else {
 9797:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 9798:                             }
 9799:                         }
 9800:                         if ($changed{$role}{'on'}) {
 9801:                             if ($newsettings{$role}{'on'}) {
 9802:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 9803:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 9804:                             } else {
 9805:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 9806:                             }
 9807:                         }
 9808:                     }
 9809:                     $r->print('</ul></li>');
 9810:                 }
 9811:                 $r->print('</ul>');
 9812:             }
 9813:         } else {
 9814:             $r->print(&mt('No changes made to helpdesk access settings.'));
 9815:         }
 9816:     }
 9817:     return;
 9818: }
 9819: 
 9820: #-------------------------------------------------- functions for &phase_two
 9821: sub user_search_result {
 9822:     my ($context,$srch) = @_;
 9823:     my %allhomes;
 9824:     my %inst_matches;
 9825:     my %srch_results;
 9826:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 9827:     $srch->{'srchterm'} =~ s/\s+/ /g;
 9828:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 9829:         $response = &mt('Invalid search.');
 9830:     }
 9831:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 9832:         $response = &mt('Invalid search.');
 9833:     }
 9834:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 9835:         $response = &mt('Invalid search.');
 9836:     }
 9837:     if ($srch->{'srchterm'} eq '') {
 9838:         $response = &mt('You must enter a search term.');
 9839:     }
 9840:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 9841:         $response = &mt('Your search term must contain more than just spaces.');
 9842:     }
 9843:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 9844:         if (($srch->{'srchdomain'} eq '') || 
 9845: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 9846:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 9847:         }
 9848:     }
 9849:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 9850:         ($srch->{'srchin'} eq 'alc')) {
 9851:         if ($srch->{'srchby'} eq 'uname') {
 9852:             my $unamecheck = $srch->{'srchterm'};
 9853:             if ($srch->{'srchtype'} eq 'contains') {
 9854:                 if ($unamecheck !~ /^\w/) {
 9855:                     $unamecheck = 'a'.$unamecheck; 
 9856:                 }
 9857:             }
 9858:             if ($unamecheck !~ /^$match_username$/) {
 9859:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 9860:             }
 9861:         }
 9862:     }
 9863:     if ($response ne '') {
 9864:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 9865:     }
 9866:     if ($srch->{'srchin'} eq 'instd') {
 9867:         my $instd_chk = &instdirectorysrch_check($srch);
 9868:         if ($instd_chk ne 'ok') {
 9869:             my $domd_chk = &domdirectorysrch_check($srch);
 9870:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 9871:             if ($domd_chk eq 'ok') {
 9872:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 9873:             }
 9874:             $response .= '<br />';
 9875:         }
 9876:     } else {
 9877:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 9878:             my $domd_chk = &domdirectorysrch_check($srch);
 9879:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 9880:                 my $instd_chk = &instdirectorysrch_check($srch);
 9881:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 9882:                 if ($instd_chk eq 'ok') {
 9883:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 9884:                 }
 9885:                 $response .= '<br />';
 9886:             }
 9887:         }
 9888:     }
 9889:     if ($response ne '') {
 9890:         return ($currstate,$response);
 9891:     }
 9892:     if ($srch->{'srchby'} eq 'uname') {
 9893:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 9894:             if ($env{'form.forcenew'}) {
 9895:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 9896:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9897:                     if ($uhome eq 'no_host') {
 9898:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 9899:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 9900:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 9901:                     } else {
 9902:                         $currstate = 'modify';
 9903:                     }
 9904:                 } else {
 9905:                     $currstate = 'modify';
 9906:                 }
 9907:             } else {
 9908:                 if ($srch->{'srchin'} eq 'dom') {
 9909:                     if ($srch->{'srchtype'} eq 'exact') {
 9910:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9911:                         if ($uhome eq 'no_host') {
 9912:                             ($currstate,$response,$forcenewuser) =
 9913:                                 &build_search_response($context,$srch,%srch_results);
 9914:                         } else {
 9915:                             $currstate = 'modify';
 9916:                             if ($env{'form.action'} eq 'accesslogs') {
 9917:                                 $currstate = 'activity';
 9918:                             }
 9919:                             my $uname = $srch->{'srchterm'};
 9920:                             my $udom = $srch->{'srchdomain'};
 9921:                             $srch_results{$uname.':'.$udom} =
 9922:                                 { &Apache::lonnet::get('environment',
 9923:                                                        ['firstname',
 9924:                                                         'lastname',
 9925:                                                         'permanentemail'],
 9926:                                                          $udom,$uname)
 9927:                                 };
 9928:                         }
 9929:                     } else {
 9930:                         %srch_results = &Apache::lonnet::usersearch($srch);
 9931:                         ($currstate,$response,$forcenewuser) =
 9932:                             &build_search_response($context,$srch,%srch_results);
 9933:                     }
 9934:                 } else {
 9935:                     my $courseusers = &get_courseusers();
 9936:                     if ($srch->{'srchtype'} eq 'exact') {
 9937:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 9938:                             $currstate = 'modify';
 9939:                         } else {
 9940:                             ($currstate,$response,$forcenewuser) =
 9941:                                 &build_search_response($context,$srch,%srch_results);
 9942:                         }
 9943:                     } else {
 9944:                         foreach my $user (keys(%$courseusers)) {
 9945:                             my ($cuname,$cudomain) = split(/:/,$user);
 9946:                             if ($cudomain eq $srch->{'srchdomain'}) {
 9947:                                 my $matched = 0;
 9948:                                 if ($srch->{'srchtype'} eq 'begins') {
 9949:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 9950:                                         $matched = 1;
 9951:                                     }
 9952:                                 } else {
 9953:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 9954:                                         $matched = 1;
 9955:                                     }
 9956:                                 }
 9957:                                 if ($matched) {
 9958:                                     $srch_results{$user} = 
 9959: 					{&Apache::lonnet::get('environment',
 9960: 							     ['firstname',
 9961: 							      'lastname',
 9962: 							      'permanentemail'],
 9963: 							      $cudomain,$cuname)};
 9964:                                 }
 9965:                             }
 9966:                         }
 9967:                         ($currstate,$response,$forcenewuser) =
 9968:                             &build_search_response($context,$srch,%srch_results);
 9969:                     }
 9970:                 }
 9971:             }
 9972:         } elsif ($srch->{'srchin'} eq 'alc') {
 9973:             $currstate = 'query';
 9974:         } elsif ($srch->{'srchin'} eq 'instd') {
 9975:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 9976:             if ($dirsrchres eq 'ok') {
 9977:                 ($currstate,$response,$forcenewuser) = 
 9978:                     &build_search_response($context,$srch,%srch_results);
 9979:             } else {
 9980:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9981:                 $response = '<span class="LC_warning">'.
 9982:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9983:                     '</span><br />'.
 9984:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 9985:                     '<br />'; 
 9986:             }
 9987:         }
 9988:     } else {
 9989:         if ($srch->{'srchin'} eq 'dom') {
 9990:             %srch_results = &Apache::lonnet::usersearch($srch);
 9991:             ($currstate,$response,$forcenewuser) = 
 9992:                 &build_search_response($context,$srch,%srch_results); 
 9993:         } elsif ($srch->{'srchin'} eq 'crs') {
 9994:             my $courseusers = &get_courseusers(); 
 9995:             foreach my $user (keys(%$courseusers)) {
 9996:                 my ($uname,$udom) = split(/:/,$user);
 9997:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 9998:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 9999:                 if ($srch->{'srchby'} eq 'lastname') {
10000:                     if ((($srch->{'srchtype'} eq 'exact') && 
10001:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
10002:                         (($srch->{'srchtype'} eq 'begins') &&
10003:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
10004:                         (($srch->{'srchtype'} eq 'contains') &&
10005:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
10006:                         $srch_results{$user} = {firstname => $names{'firstname'},
10007:                                             lastname => $names{'lastname'},
10008:                                             permanentemail => $emails{'permanentemail'},
10009:                                            };
10010:                     }
10011:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
10012:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
10013:                     $srchlast =~ s/\s+$//;
10014:                     $srchfirst =~ s/^\s+//;
10015:                     if ($srch->{'srchtype'} eq 'exact') {
10016:                         if (($names{'lastname'} eq $srchlast) &&
10017:                             ($names{'firstname'} eq $srchfirst)) {
10018:                             $srch_results{$user} = {firstname => $names{'firstname'},
10019:                                                 lastname => $names{'lastname'},
10020:                                                 permanentemail => $emails{'permanentemail'},
10021: 
10022:                                            };
10023:                         }
10024:                     } elsif ($srch->{'srchtype'} eq 'begins') {
10025:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
10026:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
10027:                             $srch_results{$user} = {firstname => $names{'firstname'},
10028:                                                 lastname => $names{'lastname'},
10029:                                                 permanentemail => $emails{'permanentemail'},
10030:                                                };
10031:                         }
10032:                     } else {
10033:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
10034:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
10035:                             $srch_results{$user} = {firstname => $names{'firstname'},
10036:                                                 lastname => $names{'lastname'},
10037:                                                 permanentemail => $emails{'permanentemail'},
10038:                                                };
10039:                         }
10040:                     }
10041:                 }
10042:             }
10043:             ($currstate,$response,$forcenewuser) = 
10044:                 &build_search_response($context,$srch,%srch_results); 
10045:         } elsif ($srch->{'srchin'} eq 'alc') {
10046:             $currstate = 'query';
10047:         } elsif ($srch->{'srchin'} eq 'instd') {
10048:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
10049:             if ($dirsrchres eq 'ok') {
10050:                 ($currstate,$response,$forcenewuser) = 
10051:                     &build_search_response($context,$srch,%srch_results);
10052:             } else {
10053:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
10054:                 $response = '<span class="LC_warning">'.
10055:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
10056:                     '</span><br />'.
10057:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
10058:                     '<br />';
10059:             }
10060:         }
10061:     }
10062:     return ($currstate,$response,$forcenewuser,\%srch_results);
10063: }
10064: 
10065: sub domdirectorysrch_check {
10066:     my ($srch) = @_;
10067:     my $response;
10068:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10069:                                              ['directorysrch'],$srch->{'srchdomain'});
10070:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10071:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10072:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
10073:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
10074:         }
10075:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
10076:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10077:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
10078:             }
10079:         }
10080:     }
10081:     return 'ok';
10082: }
10083: 
10084: sub instdirectorysrch_check {
10085:     my ($srch) = @_;
10086:     my $can_search = 0;
10087:     my $response;
10088:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10089:                                              ['directorysrch'],$srch->{'srchdomain'});
10090:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10091:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10092:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
10093:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
10094:         }
10095:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
10096:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10097:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
10098:             }
10099:             my @usertypes = split(/:/,$env{'environment.inststatus'});
10100:             if (!@usertypes) {
10101:                 push(@usertypes,'default');
10102:             }
10103:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
10104:                 foreach my $type (@usertypes) {
10105:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
10106:                         $can_search = 1;
10107:                         last;
10108:                     }
10109:                 }
10110:             }
10111:             if (!$can_search) {
10112:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
10113:                 my @longtypes; 
10114:                 foreach my $item (@usertypes) {
10115:                     if (defined($insttypes->{$item})) { 
10116:                         push (@longtypes,$insttypes->{$item});
10117:                     } elsif ($item eq 'default') {
10118:                         push (@longtypes,&mt('other')); 
10119:                     }
10120:                 }
10121:                 my $insttype_str = join(', ',@longtypes); 
10122:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
10123:             }
10124:         } else {
10125:             $can_search = 1;
10126:         }
10127:     } else {
10128:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
10129:     }
10130:     my %longtext = &Apache::lonlocal::texthash (
10131:                        uname     => 'username',
10132:                        lastfirst => 'last name, first name',
10133:                        lastname  => 'last name',
10134:                        contains  => 'contains',
10135:                        exact     => 'as exact match to',
10136:                        begins    => 'begins with',
10137:                    );
10138:     if ($can_search) {
10139:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
10140:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
10141:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
10142:             }
10143:         } else {
10144:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
10145:         }
10146:     }
10147:     if ($can_search) {
10148:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
10149:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
10150:                 return 'ok';
10151:             } else {
10152:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10153:             }
10154:         } else {
10155:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
10156:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
10157:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
10158:                 return 'ok';
10159:             } else {
10160:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10161:             }
10162:         }
10163:     }
10164: }
10165: 
10166: sub get_courseusers {
10167:     my %advhash;
10168:     my $classlist = &Apache::loncoursedata::get_classlist();
10169:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
10170:     foreach my $role (sort(keys(%coursepersonnel))) {
10171:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
10172: 	    if (!exists($classlist->{$user})) {
10173: 		$classlist->{$user} = [];
10174: 	    }
10175:         }
10176:     }
10177:     return $classlist;
10178: }
10179: 
10180: sub build_search_response {
10181:     my ($context,$srch,%srch_results) = @_;
10182:     my ($currstate,$response,$forcenewuser);
10183:     my %names = (
10184:           'uname'     => 'username',
10185:           'lastname'  => 'last name',
10186:           'lastfirst' => 'last name, first name',
10187:           'crs'       => 'this course',
10188:           'dom'       => 'LON-CAPA domain',
10189:           'instd'     => 'the institutional directory for domain',
10190:     );
10191: 
10192:     my %single = (
10193:                    begins   => 'A match',
10194:                    contains => 'A match',
10195:                    exact    => 'An exact match',
10196:                  );
10197:     my %nomatch = (
10198:                    begins   => 'No match',
10199:                    contains => 'No match',
10200:                    exact    => 'No exact match',
10201:                   );
10202:     if (keys(%srch_results) > 1) {
10203:         $currstate = 'select';
10204:     } else {
10205:         if (keys(%srch_results) == 1) {
10206:             if ($env{'form.action'} eq 'accesslogs') {
10207:                 $currstate = 'activity';
10208:             } else {
10209:                 $currstate = 'modify';
10210:             }
10211:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
10212:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10213:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
10214:             }
10215:         } else { # Search has nothing found. Prepare message to user.
10216:             $response = '<span class="LC_warning">';
10217:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10218:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
10219:                                  '<b>'.$srch->{'srchterm'}.'</b>',
10220:                                  &display_domain_info($srch->{'srchdomain'}));
10221:             } else {
10222:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
10223:                                  '<b>'.$srch->{'srchterm'}.'</b>');
10224:             }
10225:             $response .= '</span>';
10226: 
10227:             if ($srch->{'srchin'} ne 'alc') {
10228:                 $forcenewuser = 1;
10229:                 my $cansrchinst = 0; 
10230:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
10231:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
10232:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
10233:                         if ($domconfig{'directorysrch'}{'available'}) {
10234:                             $cansrchinst = 1;
10235:                         } 
10236:                     }
10237:                 }
10238:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
10239:                      ($srch->{'srchby'} eq 'lastname')) &&
10240:                     ($srch->{'srchin'} eq 'dom')) {
10241:                     if ($cansrchinst) {
10242:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
10243:                     }
10244:                 }
10245:                 if ($srch->{'srchin'} eq 'crs') {
10246:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
10247:                 }
10248:             }
10249:             my $createdom = $env{'request.role.domain'};
10250:             if ($context eq 'requestcrs') {
10251:                 if ($env{'form.coursedom'} ne '') {
10252:                     $createdom = $env{'form.coursedom'};
10253:                 }
10254:             }
10255:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
10256:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
10257:                 my $cancreate =
10258:                     &Apache::lonuserutils::can_create_user($createdom,$context);
10259:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
10260:                 if ($cancreate) {
10261:                     my $showdom = &display_domain_info($createdom); 
10262:                     $response .= '<br /><br />'
10263:                                 .'<b>'.&mt('To add a new user:').'</b>'
10264:                                 .'<br />';
10265:                     if ($context eq 'requestcrs') {
10266:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
10267:                     } else {
10268:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
10269:                     }
10270:                     $response .='<ul><li>'
10271:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
10272:                                 .'</li><li>'
10273:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
10274:                                 .'</li><li>'
10275:                                 .&mt('Provide the proposed username')
10276:                                 .'</li><li>'
10277:                                 .&mt("Click 'Search'")
10278:                                 .'</li></ul><br />';
10279:                 } else {
10280:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
10281:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
10282:                         $response .= '<br /><br />';
10283:                         if ($context eq 'requestcrs') {
10284:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
10285:                         } else {
10286:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
10287:                         }
10288:                         $response .= '<br />'
10289:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
10290:                                         ,' <a'.$helplink.'>'
10291:                                         ,'</a>')
10292:                                      .'<br />';
10293:                     }
10294:                 }
10295:             }
10296:         }
10297:     }
10298:     return ($currstate,$response,$forcenewuser);
10299: }
10300: 
10301: sub display_domain_info {
10302:     my ($dom) = @_;
10303:     my $output = $dom;
10304:     if ($dom ne '') { 
10305:         my $domdesc = &Apache::lonnet::domain($dom,'description');
10306:         if ($domdesc ne '') {
10307:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
10308:         }
10309:     }
10310:     return $output;
10311: }
10312: 
10313: sub crumb_utilities {
10314:     my %elements = (
10315:        crtuser => {
10316:            srchterm => 'text',
10317:            srchin => 'selectbox',
10318:            srchby => 'selectbox',
10319:            srchtype => 'selectbox',
10320:            srchdomain => 'selectbox',
10321:        },
10322:        crtusername => {
10323:            srchterm => 'text',
10324:            srchdomain => 'selectbox',
10325:        },
10326:        docustom => {
10327:            rolename => 'selectbox',
10328:            newrolename => 'textbox',
10329:        },
10330:        studentform => {
10331:            srchterm => 'text',
10332:            srchin => 'selectbox',
10333:            srchby => 'selectbox',
10334:            srchtype => 'selectbox',
10335:            srchdomain => 'selectbox',
10336:        },
10337:     );
10338: 
10339:     my $jsback .= qq|
10340: function backPage(formname,prevphase,prevstate) {
10341:     if (typeof prevphase == 'undefined') {
10342:         formname.phase.value = '';
10343:     }
10344:     else {  
10345:         formname.phase.value = prevphase;
10346:     }
10347:     if (typeof prevstate == 'undefined') {
10348:         formname.currstate.value = '';
10349:     }
10350:     else {
10351:         formname.currstate.value = prevstate;
10352:     }
10353:     formname.submit();
10354: }
10355: |;
10356:     return ($jsback,\%elements);
10357: }
10358: 
10359: sub course_level_table {
10360:     my ($inccourses,$showcredits,$defaultcredits) = @_;
10361:     return unless (ref($inccourses) eq 'HASH');
10362:     my $table = '';
10363: # Custom Roles?
10364: 
10365:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10366:     my %lt=&Apache::lonlocal::texthash(
10367:             'exs'  => "Existing sections",
10368:             'new'  => "Define new section",
10369:             'ssd'  => "Set Start Date",
10370:             'sed'  => "Set End Date",
10371:             'crl'  => "Course Level",
10372:             'act'  => "Activate",
10373:             'rol'  => "Role",
10374:             'ext'  => "Extent",
10375:             'grs'  => "Section",
10376:             'crd'  => "Credits",
10377:             'sta'  => "Start",
10378:             'end'  => "End"
10379:     );
10380: 
10381:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
10382: 	my $thiscourse=$protectedcourse;
10383: 	$thiscourse=~s:_:/:g;
10384: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
10385:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
10386: 	my $area=$coursedata{'description'};
10387:         my $crstype=$coursedata{'type'};
10388: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
10389: 	my ($domain,$cnum)=split(/\//,$thiscourse);
10390:         my %sections_count;
10391:         if (defined($env{'request.course.id'})) {
10392:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
10393:                 %sections_count = 
10394: 		    &Apache::loncommon::get_sections($domain,$cnum);
10395:             }
10396:         }
10397:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
10398: 	foreach my $role (@roles) {
10399:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
10400: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
10401:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
10402:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10403:                                             $plrole,\%sections_count,\%lt,
10404:                                             $showcredits,$defaultcredits,$crstype);
10405:             } elsif ($env{'request.course.sec'} ne '') {
10406:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
10407:                                              $env{'request.course.sec'})) {
10408:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10409:                                                 $plrole,\%sections_count,\%lt,
10410:                                                 $showcredits,$defaultcredits,$crstype);
10411:                 }
10412:             }
10413:         }
10414:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
10415:             foreach my $cust (sort(keys(%customroles))) {
10416:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
10417:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
10418:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10419:                                             $cust,\%sections_count,\%lt,
10420:                                             $showcredits,$defaultcredits,$crstype);
10421:             }
10422: 	}
10423:     }
10424:     return '' if ($table eq ''); # return nothing if there is nothing 
10425:                                  # in the table
10426:     my $result;
10427:     if (!$env{'request.course.id'}) {
10428:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
10429:     }
10430:     $result .= 
10431: &Apache::loncommon::start_data_table().
10432: &Apache::loncommon::start_data_table_header_row().
10433: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10434: '<th>'.$lt{'ext'}.'</th><th>'."\n";
10435:     if ($showcredits) {
10436:         $result .= $lt{'crd'}.'</th>';
10437:     }
10438:     $result .=
10439: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
10440: '<th>'.$lt{'end'}.'</th>'.
10441: &Apache::loncommon::end_data_table_header_row().
10442: $table.
10443: &Apache::loncommon::end_data_table();
10444:     return $result;
10445: }
10446: 
10447: sub course_level_row {
10448:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
10449:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
10450:     my $creditem;
10451:     my $row = &Apache::loncommon::start_data_table_row().
10452:               ' <td><input type="checkbox" name="act_'.
10453:               $protectedcourse.'_'.$role.'" /></td>'."\n".
10454:               ' <td>'.$plrole.'</td>'."\n".
10455:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
10456:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
10457:         $row .= 
10458:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
10459:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
10460:     } else {
10461:         $row .= '<td>&nbsp;</td>';
10462:     }
10463:     if (($role eq 'cc') || ($role eq 'co')) {
10464:         $row .= '<td>&nbsp;</td>';
10465:     } elsif ($env{'request.course.sec'} ne '') {
10466:         $row .= ' <td><input type="hidden" value="'.
10467:                 $env{'request.course.sec'}.'" '.
10468:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
10469:                 $env{'request.course.sec'}.'</td>';
10470:     } else {
10471:         if (ref($sections_count) eq 'HASH') {
10472:             my $currsec = 
10473:                 &Apache::lonuserutils::course_sections($sections_count,
10474:                                                        $protectedcourse.'_'.$role);
10475:             $row .= '<td><table class="LC_createuser">'."\n".
10476:                     '<tr class="LC_section_row">'."\n".
10477:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
10478:                        $currsec.'</td>'."\n".
10479:                      ' <td>&nbsp;&nbsp;</td>'."\n".
10480:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
10481:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
10482:                      '" value="" />'.
10483:                      '<input type="hidden" '.
10484:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
10485:                      '</tr></table></td>'."\n";
10486:         } else {
10487:             $row .= '<td><input type="text" size="10" '.
10488:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
10489:         }
10490:     }
10491:     $row .= <<ENDTIMEENTRY;
10492: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
10493: <a href=
10494: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
10495: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
10496: <a href=
10497: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
10498: ENDTIMEENTRY
10499:     $row .= &Apache::loncommon::end_data_table_row();
10500:     return $row;
10501: }
10502: 
10503: sub course_level_dc {
10504:     my ($dcdom,$showcredits) = @_;
10505:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10506:     my @roles = &Apache::lonuserutils::roles_by_context('course');
10507:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
10508:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
10509:                       '<input type="hidden" name="dccourse" value="" />';
10510:     my $courseform=&Apache::loncommon::selectcourse_link
10511:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
10512:     my $credit_elem;
10513:     if ($showcredits) {
10514:         $credit_elem = 'credits';
10515:     }
10516:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
10517:     my %lt=&Apache::lonlocal::texthash(
10518:                     'rol'  => "Role",
10519:                     'grs'  => "Section",
10520:                     'exs'  => "Existing sections",
10521:                     'new'  => "Define new section", 
10522:                     'sta'  => "Start",
10523:                     'end'  => "End",
10524:                     'ssd'  => "Set Start Date",
10525:                     'sed'  => "Set End Date",
10526:                     'scc'  => "Course/Community",
10527:                     'crd'  => "Credits",
10528:                   );
10529:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
10530:                  &Apache::loncommon::start_data_table().
10531:                  &Apache::loncommon::start_data_table_header_row().
10532:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10533:                  '<th>'.$lt{'grs'}.'</th>'."\n";
10534:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
10535:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
10536:                  &Apache::loncommon::end_data_table_header_row();
10537:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
10538:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
10539:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
10540:                      '<td valign="top"><br /><select name="role">'."\n";
10541:     foreach my $role (@roles) {
10542:         my $plrole=&Apache::lonnet::plaintext($role);
10543:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
10544:     }
10545:     if ( keys(%customroles) > 0) {
10546:         foreach my $cust (sort(keys(%customroles))) {
10547:             my $custrole='cr_cr_'.$env{'user.domain'}.
10548:                     '_'.$env{'user.name'}.'_'.$cust;
10549:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
10550:         }
10551:     }
10552:     $otheritems .= '</select></td><td>'.
10553:                      '<table border="0" cellspacing="0" cellpadding="0">'.
10554:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
10555:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
10556:                      '<td>&nbsp;&nbsp;</td>'.
10557:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
10558:                      '<input type="text" name="newsec" value="" />'.
10559:                      '<input type="hidden" name="section" value="" />'.
10560:                      '<input type="hidden" name="groups" value="" />'.
10561:                      '<input type="hidden" name="crstype" value="" /></td>'.
10562:                      '</tr></table></td>'."\n";
10563:     if ($showcredits) {
10564:         $otheritems .= '<td><br />'."\n".
10565:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
10566:     }
10567:     $otheritems .= <<ENDTIMEENTRY;
10568: <td><br /><input type="hidden" name="start" value='' />
10569: <a href=
10570: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
10571: <td><br /><input type="hidden" name="end" value='' />
10572: <a href=
10573: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
10574: ENDTIMEENTRY
10575:     $otheritems .= &Apache::loncommon::end_data_table_row().
10576:                    &Apache::loncommon::end_data_table()."\n";
10577:     return $cb_jscript.$hiddenitems.$header.$otheritems;
10578: }
10579: 
10580: sub update_selfenroll_config {
10581:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
10582:     return unless (ref($currsettings) eq 'HASH');
10583:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
10584:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10585:     my (%changes,%warning);
10586:     my $curr_types;
10587:     my %noedit;
10588:     unless ($context eq 'domain') {
10589:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
10590:     }
10591:     if (ref($row) eq 'ARRAY') {
10592:         foreach my $item (@{$row}) {
10593:             next if ($noedit{$item});
10594:             if ($item eq 'enroll_dates') {
10595:                 my (%currenrolldate,%newenrolldate);
10596:                 foreach my $type ('start','end') {
10597:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
10598:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
10599:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
10600:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
10601:                     }
10602:                 }
10603:             } elsif ($item eq 'access_dates') {
10604:                 my (%currdate,%newdate);
10605:                 foreach my $type ('start','end') {
10606:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
10607:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
10608:                     if ($newdate{$type} ne $currdate{$type}) {
10609:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
10610:                     }
10611:                 }
10612:             } elsif ($item eq 'types') {
10613:                 $curr_types = $currsettings->{'selfenroll_'.$item};
10614:                 if ($env{'form.selfenroll_all'}) {
10615:                     if ($curr_types ne '*') {
10616:                         $changes{'internal.selfenroll_types'} = '*';
10617:                     } else {
10618:                         next;
10619:                     }
10620:                 } else {
10621:                     my %currdoms;
10622:                     my @entries = split(/;/,$curr_types);
10623:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
10624:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
10625:                     my $newnum = 0;
10626:                     my @latesttypes;
10627:                     foreach my $num (@activations) {
10628:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
10629:                         if (@types > 0) {
10630:                             @types = sort(@types);
10631:                             my $typestr = join(',',@types);
10632:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
10633:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10634:                             $currdoms{$typedom} = 1;
10635:                             $newnum ++;
10636:                         }
10637:                     }
10638:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
10639:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
10640:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
10641:                             if (@types > 0) {
10642:                                 @types = sort(@types);
10643:                                 my $typestr = join(',',@types);
10644:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
10645:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
10646:                                 $currdoms{$typedom} = 1;
10647:                                 $newnum ++;
10648:                             }
10649:                         }
10650:                     }
10651:                     if ($env{'form.selfenroll_newdom'} ne '') {
10652:                         my $typedom = $env{'form.selfenroll_newdom'};
10653:                         if ((!defined($currdoms{$typedom})) && 
10654:                             (&Apache::lonnet::domain($typedom) ne '')) {
10655:                             my $typestr;
10656:                             my ($othertitle,$usertypes,$types) = 
10657:                                 &Apache::loncommon::sorted_inst_types($typedom);
10658:                             my $othervalue = 'any';
10659:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
10660:                                 if (@{$types} > 0) {
10661:                                     my @esc_types = map { &escape($_); } @{$types};
10662:                                     $othervalue = 'other';
10663:                                     $typestr = join(',',(@esc_types,$othervalue));
10664:                                 }
10665:                                 $typestr = $othervalue;
10666:                             } else {
10667:                                 $typestr = $othervalue;
10668:                             } 
10669:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10670:                             $newnum ++ ;
10671:                         }
10672:                     }
10673:                     my $selfenroll_types = join(';',@latesttypes);
10674:                     if ($selfenroll_types ne $curr_types) {
10675:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
10676:                     }
10677:                 }
10678:             } elsif ($item eq 'limit') {
10679:                 my $newlimit = $env{'form.selfenroll_limit'};
10680:                 my $newcap = $env{'form.selfenroll_cap'};
10681:                 $newcap =~s/\s+//g;
10682:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10683:                 $currlimit = 'none' if ($currlimit eq '');
10684:                 my $currcap = $currsettings->{'selfenroll_cap'};
10685:                 if ($newlimit ne $currlimit) {
10686:                     if ($newlimit ne 'none') {
10687:                         if ($newcap =~ /^\d+$/) {
10688:                             if ($newcap ne $currcap) {
10689:                                 $changes{'internal.selfenroll_cap'} = $newcap;
10690:                             }
10691:                             $changes{'internal.selfenroll_limit'} = $newlimit;
10692:                         } else {
10693:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10694:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
10695:                         }
10696:                     } elsif ($currcap ne '') {
10697:                         $changes{'internal.selfenroll_cap'} = '';
10698:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
10699:                     }
10700:                 } elsif ($currlimit ne 'none') {
10701:                     if ($newcap =~ /^\d+$/) {
10702:                         if ($newcap ne $currcap) {
10703:                             $changes{'internal.selfenroll_cap'} = $newcap;
10704:                         }
10705:                     } else {
10706:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10707:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
10708:                     }
10709:                 }
10710:             } elsif ($item eq 'approval') {
10711:                 my (@currnotified,@newnotified);
10712:                 my $currapproval = $currsettings->{'selfenroll_approval'};
10713:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
10714:                 if ($currnotifylist ne '') {
10715:                     @currnotified = split(/,/,$currnotifylist);
10716:                     @currnotified = sort(@currnotified);
10717:                 }
10718:                 my $newapproval = $env{'form.selfenroll_approval'};
10719:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
10720:                 @newnotified = sort(@newnotified);
10721:                 if ($newapproval ne $currapproval) {
10722:                     $changes{'internal.selfenroll_approval'} = $newapproval;
10723:                     if (!$newapproval) {
10724:                         if ($currnotifylist ne '') {
10725:                             $changes{'internal.selfenroll_notifylist'} = '';
10726:                         }
10727:                     } else {
10728:                         my @differences =  
10729:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10730:                         if (@differences > 0) {
10731:                             if (@newnotified > 0) {
10732:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10733:                             } else {
10734:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10735:                             }
10736:                         }
10737:                     }
10738:                 } else {
10739:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10740:                     if (@differences > 0) {
10741:                         if (@newnotified > 0) {
10742:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10743:                         } else {
10744:                             $changes{'internal.selfenroll_notifylist'} = '';
10745:                         }
10746:                     }
10747:                 }
10748:             } else {
10749:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
10750:                 my $newval = $env{'form.selfenroll_'.$item};
10751:                 if ($item eq 'section') {
10752:                     $newval = $env{'form.sections'};
10753:                     if (defined($curr_groups{$newval})) {
10754:                         $newval = $curr_val;
10755:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
10756:                                           &mt('Group names and section names must be distinct');
10757:                     } elsif ($newval eq 'all') {
10758:                         $newval = $curr_val;
10759:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
10760:                     }
10761:                     if ($newval eq '') {
10762:                         $newval = 'none';
10763:                     }
10764:                 }
10765:                 if ($newval ne $curr_val) {
10766:                     $changes{'internal.selfenroll_'.$item} = $newval;
10767:                 }
10768:             }
10769:         }
10770:         if (keys(%warning) > 0) {
10771:             foreach my $item (@{$row}) {
10772:                 if (exists($warning{$item})) {
10773:                     $r->print($warning{$item}.'<br />');
10774:                 }
10775:             } 
10776:         }
10777:         if (keys(%changes) > 0) {
10778:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
10779:             if ($putresult eq 'ok') {
10780:                 if ((exists($changes{'internal.selfenroll_types'})) ||
10781:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
10782:                     (exists($changes{'internal.selfenroll_end_date'}))) {
10783:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
10784:                                                                 $cnum,undef,undef,'Course');
10785:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
10786:                     if (ref($crsinfo{$cid}) eq 'HASH') {
10787:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
10788:                             if (exists($changes{'internal.'.$item})) {
10789:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
10790:                             }
10791:                         }
10792:                         my $crsputresult =
10793:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
10794:                                                          $chome,'notime');
10795:                     }
10796:                 }
10797:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
10798:                 foreach my $item (@{$row}) {
10799:                     my $title = $item;
10800:                     if (ref($lt) eq 'HASH') {
10801:                         $title = $lt->{$item};
10802:                     }
10803:                     if ($item eq 'enroll_dates') {
10804:                         foreach my $type ('start','end') {
10805:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
10806:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
10807:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10808:                                           $title,$type,$newdate).'</li>');
10809:                             }
10810:                         }
10811:                     } elsif ($item eq 'access_dates') {
10812:                         foreach my $type ('start','end') {
10813:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
10814:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
10815:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10816:                                           $title,$type,$newdate).'</li>');
10817:                             }
10818:                         }
10819:                     } elsif ($item eq 'limit') {
10820:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
10821:                             (exists($changes{'internal.selfenroll_cap'}))) {
10822:                             my ($newval,$newcap);
10823:                             if ($changes{'internal.selfenroll_cap'} ne '') {
10824:                                 $newcap = $changes{'internal.selfenroll_cap'}
10825:                             } else {
10826:                                 $newcap = $currsettings->{'selfenroll_cap'};
10827:                             }
10828:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
10829:                                 $newval = &mt('No limit');
10830:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
10831:                                      'allstudents') {
10832:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10833:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10834:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10835:                             } else {
10836:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10837:                                 if ($currlimit eq 'allstudents') {
10838:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10839:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10840:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10841:                                 }
10842:                             }
10843:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10844:                         }
10845:                     } elsif ($item eq 'approval') {
10846:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
10847:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
10848:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
10849:                             my ($newval,$newnotify);
10850:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
10851:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
10852:                             } else {   
10853:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
10854:                             }
10855:                             if (exists($changes{'internal.selfenroll_approval'})) {
10856:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
10857:                                     $changes{'internal.selfenroll_approval'} = '0';
10858:                                 }
10859:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
10860:                             } else {
10861:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
10862:                                 if ($currapproval !~ /^[012]$/) {
10863:                                     $currapproval = 0;
10864:                                 }
10865:                                 $newval = $selfdescs{'approval'}{$currapproval};
10866:                             }
10867:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
10868:                             if ($newnotify) {
10869:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
10870:                             } else {
10871:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
10872:                             }
10873:                             $r->print('</li>'."\n");
10874:                         }
10875:                     } else {
10876:                         if (exists($changes{'internal.selfenroll_'.$item})) {
10877:                             my $newval = $changes{'internal.selfenroll_'.$item};
10878:                             if ($item eq 'types') {
10879:                                 if ($newval eq '') {
10880:                                     $newval = &mt('None');
10881:                                 } elsif ($newval eq '*') {
10882:                                     $newval = &mt('Any user in any domain');
10883:                                 }
10884:                             } elsif ($item eq 'registered') {
10885:                                 if ($newval eq '1') {
10886:                                     $newval = &mt('Yes');
10887:                                 } elsif ($newval eq '0') {
10888:                                     $newval = &mt('No');
10889:                                 }
10890:                             }
10891:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10892:                         }
10893:                     }
10894:                 }
10895:                 $r->print('</ul>');
10896:                 if ($env{'course.'.$cid.'.description'} ne '') {
10897:                     my %newenvhash;
10898:                     foreach my $key (keys(%changes)) {
10899:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
10900:                     }
10901:                     &Apache::lonnet::appenv(\%newenvhash);
10902:                 }
10903:             } else {
10904:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
10905:                           &mt('The error was: [_1].',$putresult));
10906:             }
10907:         } else {
10908:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10909:         }
10910:     } else {
10911:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10912:     }
10913:     my $visactions = &cat_visibility($cdom);
10914:     my ($cathash,%cattype);
10915:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
10916:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10917:         $cathash = $domconfig{'coursecategories'}{'cats'};
10918:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
10919:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
10920:     } else {
10921:         $cathash = {};
10922:         $cattype{'auth'} = 'std';
10923:         $cattype{'unauth'} = 'std';
10924:     }
10925:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
10926:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10927:                   '<br />'.
10928:                   '<br />'.$visactions->{'take'}.'<ul>'.
10929:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
10930:                   '</ul>');
10931:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
10932:         if ($currsettings->{'uniquecode'}) {
10933:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
10934:         } else {
10935:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10936:                   '<br />'.
10937:                   '<br />'.$visactions->{'take'}.'<ul>'.
10938:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
10939:                   '</ul><br />');
10940:         }
10941:     } else {
10942:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
10943:         if (ref($visactions) eq 'HASH') {
10944:             if (!$visible) {
10945:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10946:                           '<br />');
10947:                 if (ref($vismsgs) eq 'ARRAY') {
10948:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
10949:                     foreach my $item (@{$vismsgs}) {
10950:                         $r->print('<li>'.$visactions->{$item}.'</li>');
10951:                     }
10952:                     $r->print('</ul>');
10953:                 }
10954:                 $r->print($cansetvis);
10955:             }
10956:         }
10957:     } 
10958:     return;
10959: }
10960: 
10961: #---------------------------------------------- end functions for &phase_two
10962: 
10963: #--------------------------------- functions for &phase_two and &phase_three
10964: 
10965: #--------------------------end of functions for &phase_two and &phase_three
10966: 
10967: 1;
10968: __END__
10969: 
10970: 

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