File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.485: download - view: text, annotated - select for diffs
Tue Mar 18 18:57:28 2025 UTC (3 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- WCAG 2 compliance.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.485 2025/03/18 18:57:28 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:                     $curr_access = $userenv{'tools.'.$item};
  379:                 } else {
  380:                     $curr_access =
  381:                         &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,'reload',
  382:                                                           undef,\%userenv,'',
  383:                                                           {'is_adv' => $isadv});
  384:                 }
  385:             }
  386:         } elsif ($userenv{$context.'.'.$item} ne '') {
  387:             $cust_on = ' checked="checked" ';
  388:             $cust_off = '';
  389:         }
  390:         if ($context eq 'requestcourses') {
  391:             if ($userenv{$context.'.'.$item} eq '') {
  392:                 $custom_access = &mt('Currently from default setting.');
  393:                 $customsty = ' style="display:none;"';
  394:             } else {
  395:                 $custom_access = &mt('Currently from custom setting.');
  396:                 $customsty = ' style="display:block;"';
  397:             }
  398:         } elsif ($context eq 'requestauthor') {
  399:             if ($userenv{$context} eq '') {
  400:                 $custom_access = &mt('Currently from default setting.');
  401:                 $customsty = ' style="display:none;"';
  402:             } else {
  403:                 $custom_access = &mt('Currently from custom setting.');
  404:                 $customsty = ' style="display:block;"';
  405:             }
  406:         } elsif ($item eq 'editors') {
  407:             if ($userenv{'author'.$item} eq '') {
  408:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
  409:                     @defaulteditors = @{$domconfig{'authordefaults'}{'editors'}};
  410:                 } else {
  411:                     @defaulteditors = ('edit','xml');
  412:                 }
  413:                 $custom_access = &mt('Can use: [_1]',
  414:                                                join(', ', map { $lt{$_} } @defaulteditors));
  415:                 $editorsty = ' style="display:none;"';
  416:             } else {
  417:                 $custom_access = &mt('Currently from custom setting.');
  418:                 foreach my $editor (split(/,/,$userenv{'author'.$item})) {
  419:                     if ($editor =~ /^(edit|daxe|xml)$/) {
  420:                         push(@customeditors,$editor);
  421:                     }
  422:                 }
  423:                 if (@customeditors) {
  424:                     if (@customeditors > 1) {
  425:                         $custom_access .= '<br /><span>';
  426:                     } else {
  427:                         $custom_access .= ' <span class="LC_nobreak">';
  428:                     }
  429:                     $custom_access .= &mt('Can use: [_1]',
  430:                                           join(', ', map { $lt{$_} } @customeditors)).
  431:                                       '</span>';
  432:                 } else {
  433:                     $custom_access .= ' '.&mt('No available editors');
  434:                 }
  435:                 $editorsty = ' style="display:block;"';
  436:             }
  437:         } elsif ($item eq 'managers') {
  438:             my %ca_roles = &Apache::lonnet::get_my_roles($ccuname,$ccdomain,undef,
  439:                                                          ['active','future'],['ca']);
  440:             if (keys(%ca_roles)) {
  441:                 foreach my $entry (sort(keys(%ca_roles))) {
  442:                     if ($entry =~ /^($match_username\:$match_domain):ca$/) {
  443:                         my $user = $1;
  444:                         unless ($user eq "$ccuname:$ccdomain") {
  445:                             push(@possmanagers,$user);
  446:                         }
  447:                     }
  448:                 }
  449:             }
  450:             if ($userenv{'author'.$item} eq '') {
  451:                 $custom_access = &mt('Currently author manages co-author roles');
  452:             } else {
  453:                 if (keys(%ca_roles)) {
  454:                     foreach my $user (split(/,/,$userenv{'author'.$item})) {
  455:                         if ($user =~ /^($match_username):($match_domain)$/) {
  456:                             if (exists($ca_roles{$user.':ca'})) {
  457:                                 unless ($user eq "$ccuname:$ccdomain") {
  458:                                     push(@custommanagers,$user);
  459:                                 }
  460:                             }
  461:                         }
  462:                     }
  463:                 }
  464:                 if (@custommanagers) {
  465:                     $custom_access = &mt('Co-authors who manage co-author roles: [_1]',
  466:                                          join(', ',@custommanagers));
  467:                 } else {
  468:                     $custom_access = &mt('Currently author manages co-author roles');
  469:                 }
  470:             }
  471:         } else {
  472:             my $current = $userenv{$context.'.'.$item};
  473:             if ($item eq 'webdav') {
  474:                 $current = $userenv{'tools.webdav'};
  475:             } elsif ($item eq 'archive') {
  476:                 $current = $userenv{'author'.$item};
  477:             }
  478:             if ($current eq '') {
  479:                 $custom_access =
  480:                     &mt('Availability determined currently from default setting.');
  481:                 if (!$curr_access) {
  482:                     $tool_off = 'checked="checked" ';
  483:                     $tool_on = '';
  484:                 }
  485:                 $customsty = ' style="display:none;"';
  486:             } else {
  487:                 $custom_access =
  488:                     &mt('Availability determined currently from custom setting.');
  489:                 if ($current == 0) {
  490:                     $tool_off = 'checked="checked" ';
  491:                     $tool_on = '';
  492:                 }
  493:                 $customsty = ' style="display:inline;"';
  494:             }
  495:         }
  496:         $output .= '  <tr class="LC_info_row">'."\n".
  497:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  498:                    '  </tr>'."\n".
  499:                    &Apache::loncommon::start_data_table_row()."\n";
  500:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  501:             my ($curroption,$currlimit);
  502:             my $envkey = $context.'.'.$item;
  503:             if ($context eq 'requestauthor') {
  504:                 $envkey = $context;
  505:             }
  506:             if ($userenv{$envkey} ne '') {
  507:                 $curroption = $userenv{$envkey};
  508:             } else {
  509:                 my (@inststatuses);
  510:                 if ($context eq 'requestcourses') {
  511:                     $curroption =
  512:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  513:                                                                       $isadv,$ccdomain,$item,
  514:                                                                       \@inststatuses,\%domconfig);
  515:                 } else {
  516:                      $curroption = 
  517:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  518:                                                                        $isadv,$ccdomain,undef,
  519:                                                                        \@inststatuses,\%domconfig);
  520:                 }
  521:             }
  522:             if (!$curroption) {
  523:                 $curroption = 'norequest';
  524:             }
  525:             my $name = 'crsreq_'.$item;
  526:             if ($context eq 'requestauthor') {
  527:                 $name = $item;
  528:             }
  529:             $onclick = ' onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');"';
  530:             if ($curroption =~ /^autolimit=(\d*)$/) {
  531:                 $currlimit = $1;
  532:                 if ($currlimit eq '') {
  533:                     $currdisp = &mt('Yes, automatic creation');
  534:                 } else {
  535:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  536:                 }
  537:             } else {
  538:                 $currdisp = $reqdisplay{$curroption};
  539:             }
  540:             $custdisp = '<fieldset id="customtext_'.$item.'"'.$customsty.'>';
  541:             foreach my $option (@options) {
  542:                 my $val = $option;
  543:                 if ($option eq 'norequest') {
  544:                     $val = 0;
  545:                 }
  546:                 if ($option eq 'validate') {
  547:                     my $canvalidate = 0;
  548:                     if (ref($validations{$item}) eq 'HASH') {
  549:                         if ($validations{$item}{'_custom_'}) {
  550:                             $canvalidate = 1;
  551:                         }
  552:                     }
  553:                     next if (!$canvalidate);
  554:                 }
  555:                 my $checked = '';
  556:                 if ($option eq $curroption) {
  557:                     $checked = ' checked="checked"';
  558:                 } elsif ($option eq 'autolimit') {
  559:                     if ($curroption =~ /^autolimit/) {
  560:                         $checked = ' checked="checked"';
  561:                     }
  562:                 }
  563:                 if ($option eq 'autolimit') {
  564:                     $custdisp .= '<br />';
  565:                 }
  566:                 $custdisp .= '<span class="LC_nobreak"><label>'.
  567:                              '<input type="radio" name="'.$name.'" '.
  568:                              'value="'.$val.'"'.$checked.' />'.
  569:                              $reqtitles{$option}.'</label>&nbsp;';
  570:                 if ($option eq 'autolimit') {
  571:                     $custdisp .= '<input type="text" name="'.$name.
  572:                                  '_limit" size="1" '.
  573:                                  'value="'.$currlimit.'" />&nbsp;'.
  574:                                  $reqtitles{'unlimited'}.'</span>';
  575:                 } else {
  576:                     $custdisp .= '</span>';
  577:                 }
  578:                 $custdisp .= ' ';
  579:             }
  580:             $custdisp .= '</fieldset>';
  581:             $custradio = '<br />'.$custdisp;
  582:         } elsif ($item eq 'editors') {
  583:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  584:                        &Apache::loncommon::end_data_table_row()."\n";
  585:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  586:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  587:                           '<td'.$colspan.'><span class="LC_nobreak">'.
  588:                           $lt{'chse'}.': <label>'.
  589:                           '<input type="radio" name="custom'.$item.'" value="0" '.
  590:                           $cust_off.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  591:                           $lt{'usde'}.'</label>'.('&nbsp;' x3).
  592:                           '<label><input type="radio" name="custom'.$item.'" value="1" '.
  593:                           $cust_on.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  594:                           $lt{'uscu'}.'</label></span><br />'.
  595:                           '<fieldset id="customtext_'.$item.'"'.$editorsty.'>';
  596:                 foreach my $editor ('edit','xml','daxe') {
  597:                     my $checked;
  598:                     if ($userenv{'author'.$item} eq '') {
  599:                         if (grep(/^\Q$editor\E$/,@defaulteditors)) {
  600:                             $checked = ' checked="checked"';
  601:                         }
  602:                     } elsif (grep(/^\Q$editor\E$/,@customeditors)) {
  603:                         $checked = ' checked="checked"';
  604:                     }
  605:                     $output .= '<span style="LC_nobreak"><label>'.
  606:                                '<input type="checkbox" name="custom_editor" '.
  607:                                'value="'.$editor.'"'.$checked.' />'.
  608:                                $lt{$editor}.'</label></span> ';
  609:                 }
  610:                 $output .= '</fieldset></td>'.
  611:                            &Apache::loncommon::end_data_table_row()."\n";
  612:             }
  613:         } elsif ($item eq 'managers') {
  614:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  615:                        &Apache::loncommon::end_data_table_row()."\n";
  616:             unless ((&Apache::lonnet::allowed('udp',$ccdomain)) ||
  617:                     (($userenv{'domcoord.author'} eq 'blocked') &&
  618:                      (($env{'user.name'} ne $ccuname) || ($env{'user.domain'} ne $ccdomain)))) {
  619:                 $output .=
  620:                     &Apache::loncommon::start_data_table_row()."\n".
  621:                     '<td'.$colspan.'>';
  622:                 if (@possmanagers) {
  623:                     $output .= &mt('Select manager(s)').': ';
  624:                     foreach my $user (@possmanagers) {
  625:                         my $checked;
  626:                         if (grep(/^\Q$user\E$/,@custommanagers)) {
  627:                             $checked = ' checked="checked"';
  628:                         }
  629:                         $output .= '<span style="LC_nobreak"><label>'.
  630:                                    '<input type="checkbox" name="custommanagers" '.
  631:                                    'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
  632:                                    $user.'</label></span> ';
  633:                     }
  634:                 } else {
  635:                     $output .= &mt('No co-author roles assignable as manager');
  636:                 }
  637:                 $output .= '</td>'.
  638:                            &Apache::loncommon::end_data_table_row()."\n";
  639:             }
  640:         } else {
  641:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  642:             my $name = $context.'_'.$item;
  643:             $onclick = 'onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');" ';
  644:             $custdisp = '<span class="LC_nobreak"><label>'.
  645:                         '<input type="radio" name="'.$name.'"'.
  646:                         ' value="1" '.$tool_on.$onclick.'/>'.&mt('On').'</label>&nbsp;<label>'.
  647:                         '<input type="radio" name="'.$name.'" value="0" '.
  648:                         $tool_off.$onclick.'/>'.&mt('Off').'</label></span>';
  649:             $custradio = '<span id="customtext_'.$item.'"'.$customsty.' class="LC_nobreak">'.
  650:                          '--'.$lt{'cusa'}.':&nbsp;'.$custdisp.'</span>';
  651:         }
  652:         unless (($item eq 'editors') || ($item eq 'managers')) {
  653:             $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  654:                        $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  655:                        &Apache::loncommon::end_data_table_row()."\n";
  656:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  657:                 $output .=
  658:                    &Apache::loncommon::start_data_table_row()."\n".
  659:                    '<td><span class="LC_nobreak">'.
  660:                    $lt{'chse'}.': <label>'.
  661:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  662:                    $cust_off.$onclick.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  663:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  664:                    $cust_on.$onclick.'/>'.$lt{'uscu'}.'</label></span>';
  665:                 if ($colspan) {
  666:                     $output .= '</td><td>';
  667:                 }
  668:                 $output .= $custradio.'</td>'.
  669:                            &Apache::loncommon::end_data_table_row()."\n";
  670:             }
  671:         }
  672:     }
  673:     return $output;
  674: }
  675: 
  676: sub coursereq_externaluser {
  677:     my ($ccuname,$ccdomain,$cdom) = @_;
  678:     my (@usertools,@options,%validations,%userenv,$output);
  679:     my %lt = &Apache::lonlocal::texthash (
  680:                    'official'   => 'Can request creation of official courses',
  681:                    'unofficial' => 'Can request creation of unofficial courses',
  682:                    'community'  => 'Can request creation of communities',
  683:                    'textbook'   => 'Can request creation of textbook courses',
  684:                    'placement'  => 'Can request creation of placement tests',
  685:     );
  686: 
  687:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  688:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  689:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  690:                       'reqcrsotherdom.placement');
  691:     @usertools = ('official','unofficial','community','textbook','placement');
  692:     @options = ('approval','validate','autolimit');
  693:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  694:     my $optregex = join('|',@options);
  695:     my %reqtitles = &courserequest_titles();
  696:     foreach my $item (@usertools) {
  697:         my ($curroption,$currlimit,$tooloff);
  698:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  699:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  700:             foreach my $req (@curr) {
  701:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  702:                     $curroption = $1;
  703:                     $currlimit = $2;
  704:                     last;
  705:                 }
  706:             }
  707:             if (!$curroption) {
  708:                 $curroption = 'norequest';
  709:                 $tooloff = ' checked="checked"';
  710:             }
  711:         } else {
  712:             $curroption = 'norequest';
  713:             $tooloff = ' checked="checked"';
  714:         }
  715:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  716:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  717:                   '<table><tr><td valign="top">'."\n".
  718:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  719:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  720:                   '</label></td>';
  721:         foreach my $option (@options) {
  722:             if ($option eq 'validate') {
  723:                 my $canvalidate = 0;
  724:                 if (ref($validations{$item}) eq 'HASH') {
  725:                     if ($validations{$item}{'_external_'}) {
  726:                         $canvalidate = 1;
  727:                     }
  728:                 }
  729:                 next if (!$canvalidate);
  730:             }
  731:             my $checked = '';
  732:             if ($option eq $curroption) {
  733:                 $checked = ' checked="checked"';
  734:             }
  735:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  736:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  737:                        '" value="'.$option.'"'.$checked.' />'.
  738:                        $reqtitles{$option}.'</label>';
  739:             if ($option eq 'autolimit') {
  740:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  741:                            $item.'_limit" size="1" '.
  742:                            'value="'.$currlimit.'" /></span>'.
  743:                            '<br />'.$reqtitles{'unlimited'};
  744:             } else {
  745:                 $output .= '</span>';
  746:             }
  747:             $output .= '</td>';
  748:         }
  749:         $output .= '</td></tr></table></td>'."\n".
  750:                    &Apache::loncommon::end_data_table_row()."\n";
  751:     }
  752:     return $output;
  753: }
  754: 
  755: sub domainrole_req {
  756:     my ($ccuname,$ccdomain) = @_;
  757:     return '<br /><h3>'.
  758:            &mt('Can Request Assignment of Domain Roles?').
  759:            '</h3>'."\n".
  760:            &Apache::loncommon::start_data_table().
  761:            &build_tools_display($ccuname,$ccdomain,
  762:                                 'requestauthor').
  763:            &Apache::loncommon::end_data_table();
  764: }
  765: 
  766: sub authoring_defaults {
  767:     my ($ccuname,$ccdomain) = @_;
  768:     return '<br /><h3>'.
  769:            &mt('Authoring Space defaults (if role assigned)').
  770:            '</h3>'."\n".
  771:            &Apache::loncommon::start_data_table().
  772:            &build_tools_display($ccuname,$ccdomain,
  773:                                 'authordefaults').
  774:            &user_quotas($ccuname,$ccdomain,'author').
  775:            &Apache::loncommon::end_data_table();
  776: }
  777: 
  778: sub courserequest_titles {
  779:     my %titles = &Apache::lonlocal::texthash (
  780:                                    official   => 'Official',
  781:                                    unofficial => 'Unofficial',
  782:                                    community  => 'Communities',
  783:                                    textbook   => 'Textbook',
  784:                                    placement  => 'Placement Tests',
  785:                                    lti        => 'LTI Provider',
  786:                                    norequest  => 'Not allowed',
  787:                                    approval   => 'Approval by Dom. Coord.',
  788:                                    validate   => 'With validation',
  789:                                    autolimit  => 'Numerical limit',
  790:                                    unlimited  => '(blank for unlimited)',
  791:                  );
  792:     return %titles;
  793: }
  794: 
  795: sub courserequest_display {
  796:     my %titles = &Apache::lonlocal::texthash (
  797:                                    approval   => 'Yes, need approval',
  798:                                    validate   => 'Yes, with validation',
  799:                                    norequest  => 'No',
  800:    );
  801:    return %titles;
  802: }
  803: 
  804: sub requestauthor_titles {
  805:     my %titles = &Apache::lonlocal::texthash (
  806:                                    norequest  => 'Not allowed',
  807:                                    approval   => 'Approval by Dom. Coord.',
  808:                                    automatic  => 'Automatic approval',
  809:                  );
  810:     return %titles;
  811: 
  812: }
  813: 
  814: sub requestauthor_display {
  815:     my %titles = &Apache::lonlocal::texthash (
  816:                                    approval   => 'Yes, need approval',
  817:                                    automatic  => 'Yes, automatic approval',
  818:                                    norequest  => 'No',
  819:    );
  820:    return %titles;
  821: }
  822: 
  823: sub requestchange_display {
  824:     my %titles = &Apache::lonlocal::texthash (
  825:                                    approval   => "availability set to 'on' (approval required)", 
  826:                                    automatic  => "availability set to 'on' (automatic approval)",
  827:                                    norequest  => "availability set to 'off'",
  828:    );
  829:    return %titles;
  830: }
  831: 
  832: sub curr_requestauthor {
  833:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  834:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  835:     if ($uname eq '' || $udom eq '') {
  836:         $uname = $env{'user.name'};
  837:         $udom = $env{'user.domain'};
  838:         $isadv = $env{'user.adv'};
  839:     }
  840:     my (%userenv,%settings,$val);
  841:     my @options = ('automatic','approval');
  842:     %userenv =
  843:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  844:     if ($userenv{'requestauthor'}) {
  845:         $val = $userenv{'requestauthor'};
  846:         @{$inststatuses} = ('_custom_');
  847:     } else {
  848:         my %alltasks;
  849:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  850:             %settings = %{$domconfig->{'requestauthor'}};
  851:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  852:                 $val = $settings{'_LC_adv'};
  853:                 @{$inststatuses} = ('_LC_adv_');
  854:             } else {
  855:                 if ($userenv{'inststatus'} ne '') {
  856:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  857:                 } else {
  858:                     @{$inststatuses} = ('default');
  859:                 }
  860:                 foreach my $status (@{$inststatuses}) {
  861:                     if (exists($settings{$status})) {
  862:                         my $value = $settings{$status};
  863:                         next unless ($value);
  864:                         unless (exists($alltasks{$value})) {
  865:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  866:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  867:                                     push(@{$alltasks{$value}},$status);
  868:                                 }
  869:                             } else {
  870:                                 @{$alltasks{$value}} = ($status);
  871:                             }
  872:                         }
  873:                     }
  874:                 }
  875:                 foreach my $option (@options) {
  876:                     if ($alltasks{$option}) {
  877:                         $val = $option;
  878:                         last;
  879:                     }
  880:                 }
  881:             }
  882:         }
  883:     }
  884:     return $val;
  885: }
  886: 
  887: # =================================================================== Phase one
  888: 
  889: sub print_username_entry_form {
  890:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  891:         $permission) = @_;
  892:     my $defdom=$env{'request.role.domain'};
  893:     my $formtoset = 'crtuser';
  894:     if (exists($env{'form.startrolename'})) {
  895:         $formtoset = 'docustom';
  896:         $env{'form.rolename'} = $env{'form.startrolename'};
  897:     } elsif ($env{'form.origform'} eq 'crtusername') {
  898:         $formtoset =  $env{'form.origform'};
  899:     }
  900: 
  901:     my ($jsback,$elements) = &crumb_utilities();
  902: 
  903:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  904:         '<script type="text/javascript">'."\n".
  905:         '// <![CDATA['."\n".
  906:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  907:         '// ]]>'."\n".
  908:         '</script>'."\n";
  909: 
  910:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  911:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  912:         && (&Apache::lonnet::allowed('mcr','/'))) {
  913:         $jscript .= &customrole_javascript();
  914:     }
  915:     my $helpitem = 'Course_Change_Privileges';
  916:     if ($env{'form.action'} eq 'custom') {
  917:         if ($context eq 'course') {
  918:             $helpitem = 'Course_Editing_Custom_Roles';
  919:         } elsif ($context eq 'domain') {
  920:             $helpitem = 'Domain_Editing_Custom_Roles';
  921:         }
  922:     } elsif ($env{'form.action'} eq 'singlestudent') {
  923:         $helpitem = 'Course_Add_Student';
  924:     } elsif ($env{'form.action'} eq 'accesslogs') {
  925:         $helpitem = 'Domain_User_Access_Logs';
  926:     } elsif ($context eq 'author') {
  927:         $helpitem = 'Author_Change_Privileges';
  928:     } elsif ($context eq 'domain') {
  929:         if ($permission->{'cusr'}) {
  930:             $helpitem = 'Domain_Change_Privileges';
  931:         } elsif ($permission->{'view'}) {
  932:             $helpitem = 'Domain_View_Privileges';
  933:         } else {
  934:             undef($helpitem);
  935:         }
  936:     }
  937:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  938:     if ($env{'form.action'} eq 'custom') {
  939:         push(@{$brcrum},
  940:                  {href=>"javascript:backPage(document.crtuser)",       
  941:                   text=>"Pick custom role",
  942:                   help => $helpitem,}
  943:                  );
  944:     } else {
  945:         push (@{$brcrum},
  946:                   {href => "javascript:backPage(document.crtuser)",
  947:                    text => $breadcrumb_text{'search'},
  948:                    help => $helpitem,
  949:                    faq  => 282,
  950:                    bug  => 'Instructor Interface',}
  951:                   );
  952:     }
  953:     my %loaditems = (
  954:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  955:                     );
  956:     my $args = {bread_crumbs           => $brcrum,
  957:                 bread_crumbs_component => 'User Management',
  958:                 add_entries            => \%loaditems,};
  959:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  960: 
  961:     my %lt=&Apache::lonlocal::texthash(
  962:                     'srst' => 'Search for a user and enroll as a student',
  963:                     'srme' => 'Search for a user and enroll as a member',
  964:                     'srad' => 'Search for a user and modify/add user information or roles',
  965:                     'srvu' => 'Search for a user and view user information and roles',
  966:                     'srva' => 'Search for a user and view access log information',
  967: 		    'usr'  => "Username",
  968:                     'dom'  => "Domain",
  969:                     'ecrp' => "Define or Edit Custom Role",
  970:                     'nr'   => "role name",
  971:                     'cre'  => "Next",
  972: 				       );
  973: 
  974:     if ($env{'form.action'} eq 'custom') {
  975:         if (&Apache::lonnet::allowed('mcr','/')) {
  976:             my $newroletext = &mt('Define new custom role:');
  977:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  978:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  979:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  980:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  981:                       &Apache::loncommon::start_data_table().
  982:                       &Apache::loncommon::start_data_table_row().
  983:                       '<td>');
  984:             if (keys(%existingroles) > 0) {
  985:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  986:             } else {
  987:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  988:             }
  989:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  990:                       &Apache::loncommon::end_data_table_row());
  991:             if (keys(%existingroles) > 0) {
  992:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  993:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  994:                           &mt('View/Modify existing role:').'</b></label></td>'.
  995:                           '<td align="center"><br />'.
  996:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  997:                           '<option value="" selected="selected">'.
  998:                           &mt('Select'));
  999:                 foreach my $role (sort(keys(%existingroles))) {
 1000:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
 1001:                 }
 1002:                 $r->print('</select>'.
 1003:                           '</td>'.
 1004:                           &Apache::loncommon::end_data_table_row());
 1005:             }
 1006:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
 1007:                       '<input name="customeditor" type="submit" value="'.
 1008:                       $lt{'cre'}.'" /></p>'.
 1009:                       '</form>');
 1010:         }
 1011:     } else {
 1012:         my $actiontext = $lt{'srad'};
 1013:         my $fixeddom;
 1014:         if ($env{'form.action'} eq 'singlestudent') {
 1015:             if ($crstype eq 'Community') {
 1016:                 $actiontext = $lt{'srme'};
 1017:             } else {
 1018:                 $actiontext = $lt{'srst'};
 1019:             }
 1020:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1021:             $actiontext = $lt{'srva'};
 1022:             $fixeddom = 1;
 1023:         } elsif (($env{'form.action'} eq 'singleuser') &&
 1024:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
 1025:             $actiontext = $lt{'srvu'};
 1026:             $fixeddom = 1;
 1027:         }
 1028:         $r->print("<h3>$actiontext</h3>");
 1029:         if ($env{'form.origform'} ne 'crtusername') {
 1030:             if ($response) {
 1031:                $r->print("\n<div>$response</div>".
 1032:                          '<br clear="all" />');
 1033:             }
 1034:         }
 1035:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
 1036:     }
 1037: }
 1038: 
 1039: sub customrole_javascript {
 1040:     my $js = <<"END";
 1041: <script type="text/javascript">
 1042: // <![CDATA[
 1043: 
 1044: function setCustomFields() {
 1045:     if (document.docustom.customroleaction.length > 0) {
 1046:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1047:             if (document.docustom.customroleaction[i].checked) {
 1048:                 if (document.docustom.customroleaction[i].value == 'new') {
 1049:                     document.docustom.rolename.selectedIndex = 0;
 1050:                 } else {
 1051:                     document.docustom.newrolename.value = '';
 1052:                 }
 1053:             }
 1054:         }
 1055:     }
 1056:     return;
 1057: }
 1058: 
 1059: function setCustomAction(caller) {
 1060:     if (document.docustom.customroleaction.length > 0) {
 1061:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1062:             if (document.docustom.customroleaction[i].value == caller) {
 1063:                 document.docustom.customroleaction[i].checked = true;
 1064:             }
 1065:         }
 1066:     }
 1067:     setCustomFields();
 1068:     return;
 1069: }
 1070: 
 1071: // ]]>
 1072: </script>
 1073: END
 1074:     return $js;
 1075: }
 1076: 
 1077: sub entry_form {
 1078:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
 1079:     my ($usertype,$inexact);
 1080:     if (ref($srch) eq 'HASH') {
 1081:         if (($srch->{'srchin'} eq 'dom') &&
 1082:             ($srch->{'srchby'} eq 'uname') &&
 1083:             ($srch->{'srchtype'} eq 'exact') &&
 1084:             ($srch->{'srchdomain'} ne '') &&
 1085:             ($srch->{'srchterm'} ne '')) {
 1086:             my (%curr_rules,%got_rules);
 1087:             my ($rules,$ruleorder) =
 1088:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
 1089:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
 1090:         } else {
 1091:             $inexact = 1;
 1092:         }
 1093:     }
 1094:     my ($cancreate,$noinstd);
 1095:     if ($env{'form.action'} eq 'accesslogs') {
 1096:         $noinstd = 1;
 1097:     } else {
 1098:         $cancreate =
 1099:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
 1100:     }
 1101:     my ($userpicker,$cansearch) = 
 1102:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
 1103:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
 1104:     my $srchbutton = &mt('Search');
 1105:     if ($env{'form.action'} eq 'singlestudent') {
 1106:         $srchbutton = &mt('Search and Enroll');
 1107:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1108:         $srchbutton = &mt('Search');
 1109:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
 1110:         $srchbutton = &mt('Search or Add New User');
 1111:     }
 1112:     my $output;
 1113:     if ($cansearch) {
 1114:         $output = <<"ENDBLOCK";
 1115: <form action="/adm/createuser" method="post" name="crtuser">
 1116: <input type="hidden" name="action" value="$env{'form.action'}" />
 1117: <input type="hidden" name="phase" value="get_user_info" />
 1118: $userpicker
 1119: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 1120: </form>
 1121: ENDBLOCK
 1122:     } else {
 1123:         $output = '<p>'.$userpicker.'</p>';
 1124:     }
 1125:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
 1126:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1127:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
 1128:         my $defdom=$env{'request.role.domain'};
 1129:         my ($trusted,$untrusted);
 1130:         if ($context eq 'course') {
 1131:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
 1132:         } elsif ($context eq 'author') {
 1133:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
 1134:         } elsif ($context eq 'domain') {
 1135:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
 1136:         }
 1137:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
 1138:         my %lt=&Apache::lonlocal::texthash(
 1139:                   'enro' => 'Enroll one student',
 1140:                   'enrm' => 'Enroll one member',
 1141:                   'admo' => 'Add/modify a single user',
 1142:                   'crea' => 'create new user if required',
 1143:                   'uskn' => "username is known",
 1144:                   'crnu' => 'Create a new user',
 1145:                   'usr'  => 'Username',
 1146:                   'dom'  => 'in domain',
 1147:                   'enrl' => 'Enroll',
 1148:                   'cram'  => 'Create/Modify user',
 1149:         );
 1150:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
 1151:         my ($title,$buttontext,$showresponse);
 1152:         if ($env{'form.action'} eq 'singlestudent') {
 1153:             if ($crstype eq 'Community') {
 1154:                 $title = $lt{'enrm'};
 1155:             } else {
 1156:                 $title = $lt{'enro'};
 1157:             }
 1158:             $buttontext = $lt{'enrl'};
 1159:         } else {
 1160:             $title = $lt{'admo'};
 1161:             $buttontext = $lt{'cram'};
 1162:         }
 1163:         if ($cancreate) {
 1164:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
 1165:         } else {
 1166:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
 1167:         }
 1168:         if ($env{'form.origform'} eq 'crtusername') {
 1169:             $showresponse = $responsemsg;
 1170:         }
 1171:         $output .= <<"ENDDOCUMENT";
 1172: <br />
 1173: <form action="/adm/createuser" method="post" name="crtusername">
 1174: <input type="hidden" name="action" value="$env{'form.action'}" />
 1175: <input type="hidden" name="phase" value="createnewuser" />
 1176: <input type="hidden" name="srchtype" value="exact" />
 1177: <input type="hidden" name="srchby" value="uname" />
 1178: <input type="hidden" name="srchin" value="dom" />
 1179: <input type="hidden" name="forcenewuser" value="1" />
 1180: <input type="hidden" name="origform" value="crtusername" />
 1181: <h3>$title</h3>
 1182: $showresponse
 1183: <table>
 1184:  <tr>
 1185:   <td>$lt{'usr'}:</td>
 1186:   <td><input type="text" size="15" name="srchterm" /></td>
 1187:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
 1188:   <td>&nbsp;$sellink&nbsp;</td>
 1189:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
 1190:  </tr>
 1191: </table>
 1192: </form>
 1193: ENDDOCUMENT
 1194:     }
 1195:     return $output;
 1196: }
 1197: 
 1198: sub user_modification_js {
 1199:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1200:     
 1201:     return <<END;
 1202: <script type="text/javascript" language="Javascript">
 1203: // <![CDATA[
 1204: 
 1205:     $pjump_def
 1206:     $dc_setcourse_code
 1207: 
 1208:     function dateset() {
 1209:         eval("document.cu."+document.cu.pres_marker.value+
 1210:             ".value=document.cu.pres_value.value");
 1211:         modalWindow.close();
 1212:     }
 1213: 
 1214:     $nondc_setsection_code
 1215: // ]]>
 1216: </script>
 1217: END
 1218: }
 1219: 
 1220: # =================================================================== Phase two
 1221: sub print_user_selection_page {
 1222:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1223:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1224:     my $sortby = $env{'form.sortby'};
 1225: 
 1226:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1227:         $sortby = 'lastname';
 1228:     }
 1229: 
 1230:     my ($jsback,$elements) = &crumb_utilities();
 1231: 
 1232:     my $jscript = (<<ENDSCRIPT);
 1233: <script type="text/javascript">
 1234: // <![CDATA[
 1235: function pickuser(uname,udom) {
 1236:     document.usersrchform.seluname.value=uname;
 1237:     document.usersrchform.seludom.value=udom;
 1238:     document.usersrchform.phase.value="userpicked";
 1239:     document.usersrchform.submit();
 1240: }
 1241: 
 1242: $jsback
 1243: // ]]>
 1244: </script>
 1245: ENDSCRIPT
 1246: 
 1247:     my %lt=&Apache::lonlocal::texthash(
 1248:                                        'usrch'          => "User Search to add/modify roles",
 1249:                                        'stusrch'        => "User Search to enroll student",
 1250:                                        'memsrch'        => "User Search to enroll member",
 1251:                                        'srcva'          => "Search for a user and view access log information",
 1252:                                        'usrvu'          => "User Search to view user roles",
 1253:                                        'usel'           => "Select a user to add/modify roles",
 1254:                                        'suvr'           => "Select a user to view roles",
 1255:                                        'stusel'         => "Select a user to enroll as a student",
 1256:                                        'memsel'         => "Select a user to enroll as a member",
 1257:                                        'vacsel'         => "Select a user to view access log",
 1258:                                        'username'       => "username",
 1259:                                        'domain'         => "domain",
 1260:                                        'lastname'       => "last name",
 1261:                                        'firstname'      => "first name",
 1262:                                        'permanentemail' => "permanent e-mail",
 1263:                                       );
 1264:     if ($context eq 'requestcrs') {
 1265:         $r->print('<div>');
 1266:     } else {
 1267:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1268:         my $helpitem;
 1269:         if ($env{'form.action'} eq 'singleuser') {
 1270:             $helpitem = 'Course_Change_Privileges';
 1271:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1272:             $helpitem = 'Course_Add_Student';
 1273:         } elsif ($context eq 'author') {
 1274:             $helpitem = 'Author_Change_Privileges';
 1275:         } elsif ($context eq 'domain') {
 1276:             $helpitem = 'Domain_Change_Privileges';
 1277:         }
 1278:         push (@{$brcrum},
 1279:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1280:                    text => $breadcrumb_text{'search'},
 1281:                    faq  => 282,
 1282:                    bug  => 'Instructor Interface',},
 1283:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1284:                    text => $breadcrumb_text{'userpicked'},
 1285:                    faq  => 282,
 1286:                    bug  => 'Instructor Interface',
 1287:                    help => $helpitem}
 1288:                   );
 1289:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1290:         if ($env{'form.action'} eq 'singleuser') {
 1291:             my $readonly;
 1292:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1293:                 $readonly = 1;
 1294:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1295:             } else {
 1296:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1297:             }
 1298:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1299:             if ($readonly) {
 1300:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1301:             } else {
 1302:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1303:             }
 1304:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1305:             $r->print($jscript."<b>");
 1306:             if ($crstype eq 'Community') {
 1307:                 $r->print($lt{'memsrch'});
 1308:             } else {
 1309:                 $r->print($lt{'stusrch'});
 1310:             }
 1311:             $r->print("</b><br />");
 1312:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1313:             $r->print('</form><h3>');
 1314:             if ($crstype eq 'Community') {
 1315:                 $r->print($lt{'memsel'});
 1316:             } else {
 1317:                 $r->print($lt{'stusel'});
 1318:             }
 1319:             $r->print('</h3>');
 1320:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1321:             $r->print("<b>$lt{'srcva'}</b><br />");
 1322:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1323:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1324:         }
 1325:     }
 1326:     $r->print('<form name="usersrchform" method="post" action="">'.
 1327:               &Apache::loncommon::start_data_table()."\n".
 1328:               &Apache::loncommon::start_data_table_header_row()."\n".
 1329:               ' <th> </th>'."\n");
 1330:     foreach my $field (@fields) {
 1331:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1332:                   "'".$field."'".';document.usersrchform.submit();">'.
 1333:                   $lt{$field}.'</a></th>'."\n");
 1334:     }
 1335:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1336: 
 1337:     my @sorted_users = sort {
 1338:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1339:             ||
 1340:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1341:             ||
 1342:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1343: 	    ||
 1344: 	lc($a) cmp lc($b)
 1345:         } (keys(%$srch_results));
 1346: 
 1347:     foreach my $user (@sorted_users) {
 1348:         my ($uname,$udom) = split(/:/,$user);
 1349:         my $onclick;
 1350:         if ($context eq 'requestcrs') {
 1351:             $onclick =
 1352:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1353:                                                "'$srch_results->{$user}->{firstname}',".
 1354:                                                "'$srch_results->{$user}->{lastname}',".
 1355:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1356:         } else {
 1357:             $onclick =
 1358:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1359:         }
 1360:         $r->print(&Apache::loncommon::start_data_table_row().
 1361:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1362:                   $onclick.' /></td>'.
 1363:                   '<td><tt>'.$uname.'</tt></td>'.
 1364:                   '<td><tt>'.$udom.'</tt></td>');
 1365:         foreach my $field ('lastname','firstname','permanentemail') {
 1366:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1367:         }
 1368:         $r->print(&Apache::loncommon::end_data_table_row());
 1369:     }
 1370:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1371:     if (ref($srcharray) eq 'ARRAY') {
 1372:         foreach my $item (@{$srcharray}) {
 1373:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1374:         }
 1375:     }
 1376:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1377:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1378:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1379:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1380:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1381:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1382:     if ($context eq 'requestcrs') {
 1383:         $r->print($opener_elements.'</form></div>');
 1384:     } else {
 1385:         $r->print($response.'</form>');
 1386:     }
 1387: }
 1388: 
 1389: sub print_user_query_page {
 1390:     my ($r,$caller,$brcrum) = @_;
 1391: # FIXME - this is for a network-wide name search (similar to catalog search)
 1392: # To use frames with similar behavior to catalog/portfolio search.
 1393: # To be implemented. 
 1394:     return;
 1395: }
 1396: 
 1397: sub print_user_modification_page {
 1398:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1399:         $brcrum,$showcredits) = @_;
 1400:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1401:         my $usermsg = &mt('No username and/or domain provided.');
 1402:         $env{'form.phase'} = '';
 1403: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1404:                                    $permission);
 1405:         return;
 1406:     }
 1407:     my ($form,$formname);
 1408:     if ($env{'form.action'} eq 'singlestudent') {
 1409:         $form = 'document.enrollstudent';
 1410:         $formname = 'enrollstudent';
 1411:     } else {
 1412:         $form = 'document.cu';
 1413:         $formname = 'cu';
 1414:     }
 1415:     my %abv_auth = &auth_abbrev();
 1416:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1417:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1418:     if ($uhome eq 'no_host') {
 1419:         my $usertype;
 1420:         my ($rules,$ruleorder) =
 1421:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1422:             $usertype =
 1423:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1424:                                                       \%curr_rules,\%got_rules);
 1425:         my $cancreate =
 1426:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1427:                                                    $usertype);
 1428:         if (!$cancreate) {
 1429:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1430:             my %usertypetext = (
 1431:                 official   => 'institutional',
 1432:                 unofficial => 'non-institutional',
 1433:             );
 1434:             my $response;
 1435:             if ($env{'form.origform'} eq 'crtusername') {
 1436:                 $response = '<span class="LC_warning">'.
 1437:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1438:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1439:                             '</span><br />';
 1440:             }
 1441:             $response .= '<p class="LC_warning">'
 1442:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1443:                         .' ';
 1444:             if ($context eq 'domain') {
 1445:                 $response .= &mt('Please contact a [_1] for assistance.',
 1446:                                  &Apache::lonnet::plaintext('dc'));
 1447:             } else {
 1448:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1449:                                 ,'<a href="'.$helplink.'">','</a>');
 1450:             }
 1451:             $response .= '</p><br />';
 1452:             $env{'form.phase'} = '';
 1453:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1454:                                        $permission);
 1455:             return;
 1456:         }
 1457:         $newuser = 1;
 1458:         my $checkhash;
 1459:         my $checks = { 'username' => 1 };
 1460:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1461:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1462:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1463:         if (ref($alerts{'username'}) eq 'HASH') {
 1464:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1465:                 my $domdesc =
 1466:                     &Apache::lonnet::domain($ccdomain,'description');
 1467:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1468:                     my $userchkmsg;
 1469:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1470:                         $userchkmsg = 
 1471:                             &Apache::loncommon::instrule_disallow_msg('username',
 1472:                                                                  $domdesc,1).
 1473:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1474:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1475:                             'username');
 1476:                     }
 1477:                     $env{'form.phase'} = '';
 1478:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1479:                                                $permission);
 1480:                     return;
 1481:                 }
 1482:             }
 1483:         }
 1484:     } else {
 1485:         $newuser = 0;
 1486:     }
 1487:     if ($response) {
 1488:         $response = '<br />'.$response;
 1489:     }
 1490: 
 1491:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1492:     my $dc_setcourse_code = '';
 1493:     my $nondc_setsection_code = '';                                        
 1494:     my %loaditem;
 1495: 
 1496:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1497: 
 1498:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1499:                                     $crstype,$groupslist,$newuser,
 1500:                                     $formname,\%loaditem,$permission);
 1501:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1502:     my $helpitem = 'Course_Change_Privileges';
 1503:     if ($env{'form.action'} eq 'singlestudent') {
 1504:         $helpitem = 'Course_Add_Student';
 1505:     } elsif ($context eq 'author') {
 1506:         $helpitem = 'Author_Change_Privileges';
 1507:     } elsif ($context eq 'domain') {
 1508:         $helpitem = 'Domain_Change_Privileges';
 1509:         $js .= &set_custom_js();
 1510:     }
 1511:     push (@{$brcrum},
 1512:         {href => "javascript:backPage($form)",
 1513:          text => $breadcrumb_text{'search'},
 1514:          faq  => 282,
 1515:          bug  => 'Instructor Interface',});
 1516:     if ($env{'form.phase'} eq 'userpicked') {
 1517:        push(@{$brcrum},
 1518:               {href => "javascript:backPage($form,'get_user_info','select')",
 1519:                text => $breadcrumb_text{'userpicked'},
 1520:                faq  => 282,
 1521:                bug  => 'Instructor Interface',});
 1522:     }
 1523:     push(@{$brcrum},
 1524:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1525:              text => $breadcrumb_text{'modify'},
 1526:              faq  => 282,
 1527:              bug  => 'Instructor Interface',
 1528:              help => $helpitem});
 1529:     my $args = {'add_entries'           => \%loaditem,
 1530:                 'bread_crumbs'          => $brcrum,
 1531:                 'bread_crumbs_component' => 'User Management'};
 1532:     if ($env{'form.popup'}) {
 1533:         $args->{'no_nav_bar'} = 1;
 1534:         $args->{'add_modal'} = 1;
 1535:     }
 1536:     if (($context eq 'domain') && ($env{'request.role.domain'} eq $ccdomain)) {
 1537:         my @toggles;
 1538:         if (&Apache::lonnet::allowed('cau',$ccdomain)) {
 1539:             my ($isadv,$isauthor) =
 1540:                 &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1541:             unless ($isauthor) {
 1542:                 push(@toggles,'requestauthor');
 1543:             }
 1544:             push(@toggles,('webdav','editors','archive'));
 1545:         }
 1546:         if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1547:             push(@toggles,('aboutme','blog','portfolio','portaccess','timezone'));
 1548:         }
 1549:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1550:             push(@toggles,('official','unofficial','community','textbook','placement','lti'));
 1551:         }
 1552:         if (@toggles) {
 1553:             my $onload;
 1554:             foreach my $item (@toggles) {
 1555:                 $onload .= "toggleCustom(document.cu,'customtext_$item','custom$item');";
 1556:             }
 1557:             $args->{'add_entries'} = {
 1558:                                        'onload' => $onload,
 1559:                                      };
 1560:         }
 1561:     }
 1562:     my $start_page =
 1563:         &Apache::loncommon::start_page('User Management',$js,$args);
 1564: 
 1565:     my $forminfo =<<"ENDFORMINFO";
 1566: <form action="/adm/createuser" method="post" name="$formname">
 1567: <input type="hidden" name="phase" value="update_user_data" />
 1568: <input type="hidden" name="ccuname" value="$ccuname" />
 1569: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1570: <input type="hidden" name="pres_value"  value="" />
 1571: <input type="hidden" name="pres_type"   value="" />
 1572: <input type="hidden" name="pres_marker" value="" />
 1573: ENDFORMINFO
 1574:     my (%inccourses,$roledom,$defaultcredits);
 1575:     if ($context eq 'course') {
 1576:         $inccourses{$env{'request.course.id'}}=1;
 1577:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1578:         if ($showcredits) {
 1579:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1580:         }
 1581:     } elsif ($context eq 'author') {
 1582:         $roledom = $env{'request.role.domain'};
 1583:     } elsif ($context eq 'domain') {
 1584:         foreach my $key (keys(%env)) {
 1585:             $roledom = $env{'request.role.domain'};
 1586:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1587:                 $inccourses{$1.'_'.$2}=1;
 1588:             }
 1589:         }
 1590:     } else {
 1591:         foreach my $key (keys(%env)) {
 1592: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1593: 	        $inccourses{$1.'_'.$2}=1;
 1594:             }
 1595:         }
 1596:     }
 1597:     my $title = '';
 1598:     my $need_quota_js;
 1599:     if ($newuser) {
 1600:         my ($portfolioform,$domroleform);
 1601:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1602:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1603:             # Current user has quota or user tools modification privileges
 1604:             $portfolioform = '<br /><h3>'.
 1605:                              &mt('User Tools').
 1606:                              '</h3>'."\n".
 1607:                              &Apache::loncommon::start_data_table();
 1608:             if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1609:                 $portfolioform .= &build_tools_display($ccuname,$ccdomain,'tools');
 1610:             }
 1611:             if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1612:                 $portfolioform .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1613:                 $need_quota_js = 1;
 1614:             }
 1615:             $portfolioform .= &Apache::loncommon::end_data_table();
 1616:         }
 1617:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1618:             ($ccdomain eq $env{'request.role.domain'})) {
 1619:             $domroleform = &domainrole_req($ccuname,$ccdomain).
 1620:                            &authoring_defaults($ccuname,$ccdomain);
 1621:             $need_quota_js = 1;
 1622:         }
 1623:         my $readonly;
 1624:         unless ($permission->{'cusr'}) {
 1625:             $readonly = 1;
 1626:         }
 1627:         &initialize_authen_forms($ccdomain,$formname,'','',$readonly);
 1628:         my %lt=&Apache::lonlocal::texthash(
 1629:                 'lg'             => 'Login Data',
 1630:                 'hs'             => "Home Server",
 1631:         );
 1632: 	$r->print(<<ENDTITLE);
 1633: $start_page
 1634: $response
 1635: $forminfo
 1636: <script type="text/javascript" language="Javascript">
 1637: // <![CDATA[
 1638: $loginscript
 1639: // ]]>
 1640: </script>
 1641: <input type='hidden' name='makeuser' value='1' />
 1642: ENDTITLE
 1643:         if ($env{'form.action'} eq 'singlestudent') {
 1644:             if ($crstype eq 'Community') {
 1645:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1646:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1647:             } else {
 1648:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1649:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1650:             }
 1651:         } else {
 1652:                 $title = &mt('Create New User [_1] in domain [_2]',
 1653:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1654:         }
 1655:         $r->print('<h2>'.$title.'</h2>'."\n");
 1656:         $r->print('<div class="LC_left_float">');
 1657:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1658:                                          $inst_results{$ccuname.':'.$ccdomain},$readonly));
 1659:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1660:         my ($home_server_pick,$numlib) = 
 1661:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1662:                                                       'default','hide');
 1663:         if ($numlib > 1) {
 1664:             $r->print("
 1665: <br />
 1666: $lt{'hs'}: $home_server_pick
 1667: <br />");
 1668:         } else {
 1669:             $r->print($home_server_pick);
 1670:         }
 1671:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1672:             $r->print('<br /><h3>'.
 1673:                       &mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1674:                       &Apache::loncommon::start_data_table().
 1675:                       &build_tools_display($ccuname,$ccdomain,
 1676:                                            'requestcourses').
 1677:                       &Apache::loncommon::end_data_table());
 1678:         }
 1679:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1680:                   $lt{'lg'}.'</h3>');
 1681:         my ($fixedauth,$varauth,$authmsg); 
 1682:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1683:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1684:             my ($rules,$ruleorder) = 
 1685:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1686:             if (ref($rules) eq 'HASH') {
 1687:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1688:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1689:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1690:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1691:                     } else { 
 1692:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1693:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1694:                         if ($authtype =~ /^krb(4|5)$/) {
 1695:                             my $ver = $1;
 1696:                             if ($authparm ne '') {
 1697:                                 $fixedauth = <<"KERB"; 
 1698: <input type="hidden" name="login" value="krb" />
 1699: <input type="hidden" name="krbver" value="$ver" />
 1700: <input type="hidden" name="krbarg" value="$authparm" />
 1701: KERB
 1702:                             }
 1703:                         } else {
 1704:                             $fixedauth = 
 1705: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1706:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1707:                                 $fixedauth .=    
 1708: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1709:                             } else {
 1710:                                 if ($authtype eq 'int') {
 1711:                                     $varauth = '<br />'.
 1712: &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>';
 1713:                                 } elsif ($authtype eq 'loc') {
 1714:                                     $varauth = '<br />'.
 1715: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1716:                                 } else {
 1717:                                     $varauth =
 1718: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1719:                                 }
 1720:                             }
 1721:                         }
 1722:                     }
 1723:                 } else {
 1724:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1725:                 }
 1726:             }
 1727:             if ($authmsg) {
 1728:                 $r->print(<<ENDAUTH);
 1729: $fixedauth
 1730: $authmsg
 1731: $varauth
 1732: ENDAUTH
 1733:             }
 1734:         } else {
 1735:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1736:         }
 1737:         $r->print($portfolioform.$domroleform);
 1738:         if ($env{'form.action'} eq 'singlestudent') {
 1739:             $r->print(&date_sections_select($context,$newuser,$formname,
 1740:                                             $permission,$crstype,$ccuname,
 1741:                                             $ccdomain,$showcredits));
 1742:         }
 1743:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1744:     } else { # user already exists
 1745: 	$r->print($start_page.$forminfo);
 1746:         if ($env{'form.action'} eq 'singlestudent') {
 1747:             if ($crstype eq 'Community') {
 1748:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1749:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1750:             } else {
 1751:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1752:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1753:             }
 1754:         } else {
 1755:             if ($permission->{'cusr'}) {
 1756:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1757:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1758:             } else {
 1759:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1760:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1761:             }
 1762:         }
 1763:         $r->print('<h2>'.$title.'</h2>'."\n");
 1764:         $r->print('<div class="LC_left_float">');
 1765:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1766:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1767:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1768:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1769:             $r->print('<br /><h3>'.&mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1770:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1771:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1772:                 $r->print(&Apache::loncommon::start_data_table());
 1773:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1774:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1775:                 } else {
 1776:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1777:                                                       $env{'request.role.domain'}));
 1778:                 }
 1779:                 $r->print(&Apache::loncommon::end_data_table());
 1780:             } else {
 1781:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1782:                               &Apache::lonnet::domain($ccdomain,'description')));
 1783:             }
 1784:         }
 1785:         $r->print('</div>');
 1786:         my @order = ('auth','quota','tools','requestauthor','authordefaults');
 1787:         my %user_text;
 1788:         my ($isadv,$isauthor) = 
 1789:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1790:         if (((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1791:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1792:             ($env{'request.role.domain'} eq $ccdomain)) {
 1793:             if (!$isauthor) {
 1794:                 $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1795:             }
 1796:             $user_text{'authordefaults'} = &authoring_defaults($ccuname,$ccdomain);
 1797:             if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1798:                 $need_quota_js = 1;
 1799:             }
 1800:         }
 1801:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1802:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1803:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1804:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1805:             $user_text{'quota'} = '<br /><h3>'.&mt('User Tools').'</h3>'."\n".
 1806:                                   &Apache::loncommon::start_data_table();
 1807:             if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1808:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1809:                 $user_text{'quota'} .= &build_tools_display($ccuname,$ccdomain,'tools');
 1810:             }
 1811:             # Current user has quota modification privileges
 1812:             if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1813:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1814:                 $user_text{'quota'} .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1815:                 $need_quota_js = 1;
 1816:             }
 1817:             $user_text{'quota'} .= &Apache::loncommon::end_data_table();
 1818:         }
 1819:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1820:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1821:                 my %lt=&Apache::lonlocal::texthash(
 1822:                     'dska'  => "Disk quotas for user's portfolio",
 1823:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1824:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1825:                 );
 1826:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1827: <h3>$lt{'dska'}</h3>
 1828: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1829: ENDNOPORTPRIV
 1830:             }
 1831:         }
 1832:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1833:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1834:                 my %lt=&Apache::lonlocal::texthash(
 1835:                     'utav'  => "User Tools Availability",
 1836:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, Personal Information Page, or Time Zone settings for this user.",
 1837:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1838:                 );
 1839:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1840: <h3>$lt{'utav'}</h3>
 1841: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1842: ENDNOTOOLSPRIV
 1843:             }
 1844:         }
 1845:         my $gotdiv = 0; 
 1846:         foreach my $item (@order) {
 1847:             if ($user_text{$item} ne '') {
 1848:                 unless ($gotdiv) {
 1849:                     $r->print('<div class="LC_left_float">');
 1850:                     $gotdiv = 1;
 1851:                 }
 1852:                 $r->print('<br />'.$user_text{$item});
 1853:             }
 1854:         }
 1855:         if ($env{'form.action'} eq 'singlestudent') {
 1856:             unless ($gotdiv) {
 1857:                 $r->print('<div class="LC_left_float">');
 1858:             }
 1859:             my $credits;
 1860:             if ($showcredits) {
 1861:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1862:                 if ($credits eq '') {
 1863:                     $credits = $defaultcredits;
 1864:                 }
 1865:             }
 1866:             $r->print(&date_sections_select($context,$newuser,$formname,
 1867:                                             $permission,$crstype,$ccuname,
 1868:                                             $ccdomain,$showcredits));
 1869:         }
 1870:         if ($gotdiv) {
 1871:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1872:         }
 1873:         my $statuses;
 1874:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1875:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1876:             $statuses = ['active'];
 1877:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1878:                  ($env{'request.course.sec'} &&
 1879:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1880:             $statuses = ['active'];
 1881:         }
 1882:         if ($env{'form.action'} ne 'singlestudent') {
 1883:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1884:                                     $roledom,$crstype,$showcredits,$statuses);
 1885:         }
 1886:     } ## End of new user/old user logic
 1887:     if ($env{'form.action'} eq 'singlestudent') {
 1888:         my $btntxt;
 1889:         if ($crstype eq 'Community') {
 1890:             $btntxt = &mt('Enroll Member');
 1891:         } else {
 1892:             $btntxt = &mt('Enroll Student');
 1893:         }
 1894:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1895:     } elsif ($permission->{'cusr'}) {
 1896:         $r->print('<div class="LC_left_float">'.
 1897:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1898:         my $addrolesdisplay = 0;
 1899:         if ($context eq 'domain' || $context eq 'author') {
 1900:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1901:         }
 1902:         if ($context eq 'domain') {
 1903:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1904:             if (!$addrolesdisplay) {
 1905:                 $addrolesdisplay = $add_domainroles;
 1906:             }
 1907:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1908:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1909:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1910:         } elsif ($context eq 'author') {
 1911:             if ($addrolesdisplay) {
 1912:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1913:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1914:                 if ($newuser) {
 1915:                     $r->print(' onclick="auth_check()" \>'."\n");
 1916:                 } else {
 1917:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1918:                 }
 1919:             } else {
 1920:                 $r->print('</fieldset></div>'.
 1921:                           '<div class="LC_clear_float_footer"></div>'.
 1922:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1923:                           &mt('Back to previous page').'</a>');
 1924:             }
 1925:         } else {
 1926:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1927:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1928:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1929:         }
 1930:     }
 1931:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1932:     $r->print('<input type="hidden" name="currstate" value="" />');
 1933:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1934:     if ($need_quota_js) {
 1935:         $r->print(&user_quota_js());
 1936:     }
 1937:     return;
 1938: }
 1939: 
 1940: sub singleuser_breadcrumb {
 1941:     my ($crstype,$context,$domain) = @_;
 1942:     my %breadcrumb_text;
 1943:     if ($env{'form.action'} eq 'singlestudent') {
 1944:         if ($crstype eq 'Community') {
 1945:             $breadcrumb_text{'search'} = 'Enroll a member';
 1946:         } else {
 1947:             $breadcrumb_text{'search'} = 'Enroll a student';
 1948:         }
 1949:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1950:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1951:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1952:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1953:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1954:         $breadcrumb_text{'activity'} = 'Activity';
 1955:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1956:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1957:         $breadcrumb_text{'search'} = "View user's roles";
 1958:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1959:         $breadcrumb_text{'modify'} = 'User roles';
 1960:     } else {
 1961:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1962:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1963:         $breadcrumb_text{'modify'} = 'Set user role';
 1964:     }
 1965:     return %breadcrumb_text;
 1966: }
 1967: 
 1968: sub date_sections_select {
 1969:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1970:         $showcredits) = @_;
 1971:     my $credits;
 1972:     if ($showcredits) {
 1973:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1974:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1975:         if ($credits eq '') {
 1976:             $credits = $defaultcredits;
 1977:         }
 1978:     }
 1979:     my $cid = $env{'request.course.id'};
 1980:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1981:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1982:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1983:                                                   undef,$formname,$permission);
 1984:     my $rowtitle = 'Section';
 1985:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1986:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1987:                                               $permission,$context,'',$crstype,
 1988:                                               $showcredits,$credits);
 1989:     my $output = $date_table.$secbox;
 1990:     return $output;
 1991: }
 1992: 
 1993: sub validation_javascript {
 1994:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1995:         $loaditem,$permission) = @_;
 1996:     my $dc_setcourse_code = '';
 1997:     my $nondc_setsection_code = '';
 1998:     if ($context eq 'domain') {
 1999:         if ((ref($permission) eq 'HASH') && ($permission->{'cusr'})) {
 2000:             my $dcdom = $env{'request.role.domain'};
 2001:             $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 2002:             $dc_setcourse_code =
 2003:                 &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 2004:         }
 2005:     } else {
 2006:         my $checkauth; 
 2007:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2008:             $checkauth = 1;
 2009:         }
 2010:         if ($context eq 'course') {
 2011:             $nondc_setsection_code =
 2012:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 2013:                                                               undef,$checkauth,
 2014:                                                               $crstype);
 2015:         }
 2016:         if ($checkauth) {
 2017:             $nondc_setsection_code .= 
 2018:                 &Apache::lonuserutils::verify_authen($formname,$context);
 2019:         }
 2020:     }
 2021:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 2022:                                    $nondc_setsection_code,$groupslist);
 2023:     my ($jsback,$elements) = &crumb_utilities();
 2024:     $js .= "\n".
 2025:            '<script type="text/javascript">'."\n".
 2026:            '// <![CDATA['."\n".
 2027:            $jsback."\n".
 2028:            '// ]]>'."\n".
 2029:            '</script>'."\n";
 2030:     return $js;
 2031: }
 2032: 
 2033: sub display_existing_roles {
 2034:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 2035:         $showcredits,$statuses) = @_;
 2036:     my $now=time;
 2037:     my $showall = 1;
 2038:     my ($showexpired,$showactive);
 2039:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 2040:         $showall = 0;
 2041:         if (grep(/^expired$/,@{$statuses})) {
 2042:             $showexpired = 1;
 2043:         }
 2044:         if (grep(/^active$/,@{$statuses})) {
 2045:             $showactive = 1;
 2046:         }
 2047:         if ($showexpired && $showactive) {
 2048:             $showall = 1;
 2049:         }
 2050:     }
 2051:     my %lt=&Apache::lonlocal::texthash(
 2052:                     'rer'  => "Existing Roles",
 2053:                     'rev'  => "Revoke",
 2054:                     'del'  => "Delete",
 2055:                     'ren'  => "Re-Enable",
 2056:                     'rol'  => "Role",
 2057:                     'ext'  => "Extent",
 2058:                     'crd'  => "Credits",
 2059:                     'sta'  => "Start",
 2060:                     'end'  => "End",
 2061:                                        );
 2062:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 2063:     if ($context eq 'course' || $context eq 'author') {
 2064:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 2065:         my %roleshash = 
 2066:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 2067:                               ['active','previous','future'],\@roles,$roledom,1);
 2068:         foreach my $key (keys(%roleshash)) {
 2069:             my ($start,$end) = split(':',$roleshash{$key});
 2070:             next if ($start eq '-1' || $end eq '-1');
 2071:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 2072:             if ($context eq 'course') {
 2073:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 2074:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 2075:             } elsif ($context eq 'author') {
 2076:                 if ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2077:                     my ($audom,$auname) = ($1,$2);
 2078:                     next unless (($rnum eq $auname) && ($rdom eq $audom));
 2079:                 } else {
 2080:                     next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 2081:                 }
 2082:             }
 2083:             my ($newkey,$newvalue,$newrole);
 2084:             $newkey = '/'.$rdom.'/'.$rnum;
 2085:             if ($sec ne '') {
 2086:                 $newkey .= '/'.$sec;
 2087:             }
 2088:             $newvalue = $role;
 2089:             if ($role =~ /^cr/) {
 2090:                 $newrole = 'cr';
 2091:             } else {
 2092:                 $newrole = $role;
 2093:             }
 2094:             $newkey .= '_'.$newrole;
 2095:             if ($start ne '' && $end ne '') {
 2096:                 $newvalue .= '_'.$end.'_'.$start;
 2097:             } elsif ($end ne '') {
 2098:                 $newvalue .= '_'.$end;
 2099:             }
 2100:             $rolesdump{$newkey} = $newvalue;
 2101:         }
 2102:     } else {
 2103:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 2104:     }
 2105:     # Build up table of user roles to allow revocation and re-enabling of roles.
 2106:     my ($tmp) = keys(%rolesdump);
 2107:     return if ($tmp =~ /^(con_lost|error)/i);
 2108:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 2109:                                 my $b1=join('_',(split('_',$b))[1,0]);
 2110:                                 return $a1 cmp $b1;
 2111:                             } keys(%rolesdump)) {
 2112:         next if ($area =~ /^rolesdef/);
 2113:         my $envkey=$area;
 2114:         my $role = $rolesdump{$area};
 2115:         my $thisrole=$area;
 2116:         $area =~ s/\_\w\w$//;
 2117:         my ($role_code,$role_end_time,$role_start_time) =
 2118:             split(/_/,$role);
 2119:         my $active=1;
 2120:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 2121:         if ($active) {
 2122:             next unless($showall || $showactive);
 2123:         } else {
 2124:             next unless($showall || $showexpired);
 2125:         }
 2126: # Is this a custom role? Get role owner and title.
 2127:         my ($croleudom,$croleuname,$croletitle)=
 2128:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 2129:         my $allowed=0;
 2130:         my $delallowed=0;
 2131:         my $sortkey=$role_code;
 2132:         my $class='Unknown';
 2133:         my $credits='';
 2134:         my $csec;
 2135:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 2136:             $class='Course';
 2137:             my ($coursedom,$coursedir) = ($1,$2);
 2138:             my $cid = $1.'_'.$2;
 2139:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 2140:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 2141:             my %coursedata=
 2142:                 &Apache::lonnet::coursedescription($cid);
 2143:             if ($coursedir =~ /^$match_community$/) {
 2144:                 $class='Community';
 2145:             }
 2146:             $sortkey.="\0$coursedom";
 2147:             my $carea;
 2148:             if (defined($coursedata{'description'})) {
 2149:                 $carea=$coursedata{'description'}.
 2150:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 2151:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 2152:                 $sortkey.="\0".$coursedata{'description'};
 2153:             } else {
 2154:                 if ($class eq 'Community') {
 2155:                     $carea=&mt('Unavailable community').': '.$area;
 2156:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 2157:                 } else {
 2158:                     $carea=&mt('Unavailable course').': '.$area;
 2159:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 2160:                 }
 2161:             }
 2162:             $sortkey.="\0$coursedir";
 2163:             $inccourses->{$cid}=1;
 2164:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 2165:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 2166:                 $credits =
 2167:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 2168:                                       $coursedom,$coursedir);
 2169:                 if ($credits eq '') {
 2170:                     $credits = $defaultcredits;
 2171:                 }
 2172:             }
 2173:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 2174:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2175:                 $allowed=1;
 2176:             }
 2177:             unless ($allowed) {
 2178:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 2179:                 if ($isowner) {
 2180:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 2181:                         $allowed = 1;
 2182:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 2183:                         $allowed = 1;
 2184:                     }
 2185:                 }
 2186:             } 
 2187:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 2188:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 2189:                 $delallowed=1;
 2190:             }
 2191: # - custom role. Needs more info, too
 2192:             if ($croletitle) {
 2193:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 2194:                     $allowed=1;
 2195:                     $thisrole.='.'.$role_code;
 2196:                 }
 2197:             }
 2198:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 2199:                 $csec = $2;
 2200:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 2201:                 $sortkey.="\0$csec";
 2202:                 if (!$allowed) {
 2203:                     if ($env{'request.course.sec'} eq $csec) {
 2204:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 2205:                             $allowed = 1;
 2206:                         }
 2207:                     }
 2208:                 }
 2209:             }
 2210:             $area=$carea;
 2211:         } else {
 2212:             $sortkey.="\0".$area;
 2213:             # Determine if current user is able to revoke privileges
 2214:             if ($area=~m{^/($match_domain)/}) {
 2215:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 2216:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2217:                    $allowed=1;
 2218:                 }
 2219:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 2220:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 2221:                     ($role_code ne 'dc')) {
 2222:                     $delallowed=1;
 2223:                 }
 2224:             } else {
 2225:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 2226:                     $allowed=1;
 2227:                 }
 2228:             }
 2229:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 2230:                 $class='Authoring Space';
 2231:             } elsif ($role_code eq 'su') {
 2232:                 $class='System';
 2233:             } else {
 2234:                 $class='Domain';
 2235:             }
 2236:         }
 2237:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 2238:             $area=~m{/($match_domain)/($match_username)};
 2239:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 2240:                 $allowed=1;
 2241:             } elsif (&Apache::lonuserutils::coauthorpriv($2,$1)) {
 2242:                 $allowed=1;
 2243:             } else {
 2244:                 $allowed=0;
 2245:             }
 2246:         }
 2247:         my $row = '';
 2248:         if ($showall) {
 2249:             $row.= '<td>';
 2250:             if (($active) && ($allowed)) {
 2251:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 2252:             } else {
 2253:                 if ($active) {
 2254:                     $row.='&nbsp;';
 2255:                 } else {
 2256:                     $row.=&mt('expired or revoked');
 2257:                 }
 2258:             }
 2259:             $row.='</td><td>';
 2260:             if ($allowed && !$active) {
 2261:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 2262:             } else {
 2263:                 $row.='&nbsp;';
 2264:             }
 2265:             $row.='</td><td>';
 2266:             if ($delallowed) {
 2267:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 2268:             } else {
 2269:                 $row.='&nbsp;';
 2270:             }
 2271:             $row.= '</td>';
 2272:         }
 2273:         my $plaintext='';
 2274:         if (!$croletitle) {
 2275:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2276:             if (($showcredits) && ($credits ne '')) {
 2277:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2278:                               '<span class="LC_fontsize_small">'.
 2279:                               &mt('Credits: [_1]',$credits).
 2280:                               '</span></span>';
 2281:             }
 2282:         } else {
 2283:             $plaintext=
 2284:                 &mt('Custom role [_1][_2]defined by [_3]',
 2285:                         '"'.$croletitle.'"',
 2286:                         '<br />',
 2287:                         $croleuname.':'.$croleudom);
 2288:         }
 2289:         $row.= '<td>'.$plaintext.'</td>'.
 2290:                '<td>'.$area.'</td>'.
 2291:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2292:                                             : '&nbsp;' ).'</td>'.
 2293:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2294:                                             : '&nbsp;' ).'</td>';
 2295:         $sortrole{$sortkey}=$envkey;
 2296:         $roletext{$envkey}=$row;
 2297:         $roleclass{$envkey}=$class;
 2298:         if ($allowed) {
 2299:             $rolepriv{$envkey}='edit';
 2300:         } else {
 2301:             if ($context eq 'domain') {
 2302:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2303:                     ($envkey=~m{^/$ccdomain/})) {
 2304:                     $rolepriv{$envkey}='view';
 2305:                 }
 2306:             } elsif ($context eq 'course') {
 2307:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2308:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2309:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2310:                     $rolepriv{$envkey}='view';
 2311:                 }
 2312:             }
 2313:         }
 2314:     } # end of foreach        (table building loop)
 2315: 
 2316:     my $rolesdisplay = 0;
 2317:     my %output = ();
 2318:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2319:         $output{$type} = '';
 2320:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2321:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2322:                  $output{$type}.=
 2323:                       &Apache::loncommon::start_data_table_row().
 2324:                       $roletext{$sortrole{$which}}.
 2325:                       &Apache::loncommon::end_data_table_row();
 2326:             }
 2327:         }
 2328:         unless($output{$type} eq '') {
 2329:             $output{$type} = '<tr class="LC_info_row">'.
 2330:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2331:                       $output{$type};
 2332:             $rolesdisplay = 1;
 2333:         }
 2334:     }
 2335:     if ($rolesdisplay == 1) {
 2336:         my $contextrole='';
 2337:         if ($env{'request.course.id'}) {
 2338:             if (&Apache::loncommon::course_type() eq 'Community') {
 2339:                 $contextrole = &mt('Existing Roles in this Community');
 2340:             } else {
 2341:                 $contextrole = &mt('Existing Roles in this Course');
 2342:             }
 2343:         } elsif ($env{'request.role'} =~ /^au\./) {
 2344:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2345:         } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)/$}) {
 2346:             $contextrole = &mt('Existing Co-Author Roles in [_1] Authoring Space',
 2347:                                '<i>'.$1.'_'.$2.'</i>');
 2348:         } else {
 2349:             if ($showall) {
 2350:                 $contextrole = &mt('Existing Roles in this Domain');
 2351:             } elsif ($showactive) {
 2352:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2353:             } elsif ($showexpired) {
 2354:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2355:             }
 2356:         }
 2357:         $r->print('<div class="LC_left_float">'.
 2358: '<fieldset><legend>'.$contextrole.'</legend>'.
 2359: &Apache::loncommon::start_data_table("LC_createuser").
 2360: &Apache::loncommon::start_data_table_header_row());
 2361:         if ($showall) {
 2362:             $r->print(
 2363: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2364:             );
 2365:         } elsif ($showexpired) {
 2366:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2367:         }
 2368:         $r->print(
 2369: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2370: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2371: &Apache::loncommon::end_data_table_header_row());
 2372:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2373:             if ($output{$type}) {
 2374:                 $r->print($output{$type}."\n");
 2375:             }
 2376:         }
 2377:         $r->print(&Apache::loncommon::end_data_table().
 2378:                   '</fieldset></div>');
 2379:     }
 2380:     return;
 2381: }
 2382: 
 2383: sub new_coauthor_roles {
 2384:     my ($r,$ccuname,$ccdomain) = @_;
 2385:     my $addrolesdisplay = 0;
 2386:     #
 2387:     # Co-Author
 2388:     #
 2389:     my ($cuname,$cudom);
 2390:     if (($env{'request.role'} eq "au./$env{'user.domain'}/") ||
 2391:         ($env{'request.role'} eq "dc./$env{'user.domain'}/")) {
 2392:         $cuname=$env{'user.name'};
 2393:         $cudom=$env{'request.role.domain'};
 2394:         # No sense in assigning co-author role to yourself
 2395:         if ((&Apache::lonuserutils::authorpriv($cuname,$cudom)) &&
 2396:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2397:             $addrolesdisplay = 1;
 2398:         }
 2399:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2400:         ($cudom,$cuname) = ($1,$2);
 2401:         if ((&Apache::lonuserutils::coauthorpriv($cuname,$cudom)) &&
 2402:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain) &&
 2403:             ($cudom ne $ccdomain || $cuname ne $ccuname)) {
 2404:             $addrolesdisplay = 1;
 2405:         }
 2406:     }
 2407:     if ($addrolesdisplay) {
 2408:         my %lt=&Apache::lonlocal::texthash(
 2409:                     'cs'   => "Authoring Space",
 2410:                     'act'  => "Activate",
 2411:                     'rol'  => "Role",
 2412:                     'ext'  => "Extent",
 2413:                     'sta'  => "Start",
 2414:                     'end'  => "End",
 2415:                     'cau'  => "Co-Author",
 2416:                     'caa'  => "Assistant Co-Author",
 2417:                     'ssd'  => "Set Start Date",
 2418:                     'sed'  => "Set End Date"
 2419:                                        );
 2420:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2421:                   &Apache::loncommon::start_data_table()."\n".
 2422:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2423:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2424:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2425:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2426:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2427:                   &Apache::loncommon::start_data_table_row().'
 2428:            <td>
 2429:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2430:            </td>
 2431:            <td>'.$lt{'cau'}.'</td>
 2432:            <td>'.$cudom.'_'.$cuname.'</td>
 2433:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2434:              <a href=
 2435: "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>
 2436: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2437: <a href=
 2438: "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".
 2439:               &Apache::loncommon::end_data_table_row()."\n".
 2440:               &Apache::loncommon::start_data_table_row()."\n".
 2441: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2442: <td>'.$lt{'caa'}.'</td>
 2443: <td>'.$cudom.'_'.$cuname.'</td>
 2444: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2445: <a href=
 2446: "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>
 2447: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2448: <a href=
 2449: "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".
 2450:              &Apache::loncommon::end_data_table_row()."\n".
 2451:              &Apache::loncommon::end_data_table());
 2452:     } elsif ($env{'request.role'} =~ /^au\./) {
 2453:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2454:                                                 $env{'request.role.domain'}))) {
 2455:             $r->print('<span class="LC_error">'.
 2456:                       &mt('You do not have privileges to assign co-author roles.').
 2457:                       '</span>');
 2458:         } elsif (($env{'user.name'} eq $ccuname) &&
 2459:              ($env{'user.domain'} eq $ccdomain)) {
 2460:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2461:         }
 2462:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2463:         if (!(&Apache::lonuserutils::coauthorpriv($2,$1))) {
 2464:             $r->print('<span class="LC_error">'.
 2465:                       &mt('You do not have privileges to assign co-author roles.').
 2466:                       '</span>');
 2467:         } elsif (($env{'user.name'} eq $ccuname) &&
 2468:              ($env{'user.domain'} eq $ccdomain)) {
 2469:             $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'));
 2470:         } elsif (($cudom eq $ccdomain) && ($cuname eq $ccuname)) {
 2471:             $r->print(&mt("Assigning a co-author or assistant co-author role to an Authoring Space's author is not permitted"));
 2472:         }
 2473:     }
 2474:     return $addrolesdisplay;;
 2475: }
 2476: 
 2477: sub new_domain_roles {
 2478:     my ($r,$ccdomain) = @_;
 2479:     my $addrolesdisplay = 0;
 2480:     #
 2481:     # Domain level
 2482:     #
 2483:     my $num_domain_level = 0;
 2484:     my $domaintext =
 2485:     '<h4>'.&mt('Domain Level').'</h4>'.
 2486:     &Apache::loncommon::start_data_table().
 2487:     &Apache::loncommon::start_data_table_header_row().
 2488:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2489:     &mt('Extent').'</th>'.
 2490:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2491:     &Apache::loncommon::end_data_table_header_row();
 2492:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2493:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2494:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2495:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2496:         foreach my $role (@allroles) {
 2497:             next if ($role eq 'ad');
 2498:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2499:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2500:                if ($role eq 'dc') {
 2501:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2502:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2503:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2504:                        next unless ($uintdom eq $intdom);
 2505:                    }
 2506:                }
 2507:                my $plrole=&Apache::lonnet::plaintext($role);
 2508:                my %lt=&Apache::lonlocal::texthash(
 2509:                     'ssd'  => "Set Start Date",
 2510:                     'sed'  => "Set End Date"
 2511:                                        );
 2512:                $num_domain_level ++;
 2513:                $domaintext .=
 2514: &Apache::loncommon::start_data_table_row().
 2515: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2516: <td>'.$plrole.'</td>
 2517: <td>'.$thisdomain.'</td>
 2518: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2519: <a href=
 2520: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2521: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2522: <a href=
 2523: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2524: &Apache::loncommon::end_data_table_row();
 2525:             }
 2526:         }
 2527:     }
 2528:     $domaintext.= &Apache::loncommon::end_data_table();
 2529:     if ($num_domain_level > 0) {
 2530:         $r->print($domaintext);
 2531:         $addrolesdisplay = 1;
 2532:     }
 2533:     return $addrolesdisplay;
 2534: }
 2535: 
 2536: sub user_authentication {
 2537:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2538:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2539:     my $outcome;
 2540:     my %lt=&Apache::lonlocal::texthash(
 2541:                    'err'   => "ERROR",
 2542:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2543:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2544:                    'sldb'  => "Please specify login data below",
 2545:                    'ld'    => "Login Data"
 2546:     );
 2547:     # Check for a bad authentication type
 2548:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2549:         # bad authentication scheme
 2550:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2551:             &initialize_authen_forms($ccdomain,$formname);
 2552: 
 2553:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2554:             $outcome = <<ENDBADAUTH;
 2555: <script type="text/javascript" language="Javascript">
 2556: // <![CDATA[
 2557: $loginscript
 2558: // ]]>
 2559: </script>
 2560: <span class="LC_error">$lt{'err'}:
 2561: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2562: <h3>$lt{'ld'}</h3>
 2563: $choices
 2564: ENDBADAUTH
 2565:         } else {
 2566:             # This user is not allowed to modify the user's
 2567:             # authentication scheme, so just notify them of the problem
 2568:             $outcome = <<ENDBADAUTH;
 2569: <span class="LC_error"> $lt{'err'}: 
 2570: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2571: </span>
 2572: ENDBADAUTH
 2573:         }
 2574:     } else { # Authentication type is valid
 2575:         
 2576:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2577:         my ($authformcurrent,$can_modify,@authform_others) =
 2578:             &modify_login_block($ccdomain,$currentauth);
 2579:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2580:             # Current user has login modification privileges
 2581:             $outcome =
 2582:                        '<script type="text/javascript" language="Javascript">'."\n".
 2583:                        '// <![CDATA['."\n".
 2584:                        $loginscript."\n".
 2585:                        '// ]]>'."\n".
 2586:                        '</script>'."\n".
 2587:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2588:                        &Apache::loncommon::start_data_table().
 2589:                        &Apache::loncommon::start_data_table_row().
 2590:                        '<td>'.$authformnop;
 2591:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2592:                 $outcome .= '</td>'."\n".
 2593:                             &Apache::loncommon::end_data_table_row().
 2594:                             &Apache::loncommon::start_data_table_row().
 2595:                             '<td>'.$authformcurrent.'</td>'.
 2596:                             &Apache::loncommon::end_data_table_row()."\n";
 2597:             } else {
 2598:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2599:                             &Apache::loncommon::end_data_table_row()."\n";
 2600:             }
 2601:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2602:                 foreach my $item (@authform_others) { 
 2603:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2604:                                 '<td>'.$item.'</td>'.
 2605:                                 &Apache::loncommon::end_data_table_row()."\n";
 2606:                 }
 2607:             }
 2608:             $outcome .= &Apache::loncommon::end_data_table();
 2609:         } else {
 2610:             if (($currentauth =~ /^internal:/) &&
 2611:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2612:                 $outcome = <<"ENDJS";
 2613: <script type="text/javascript">
 2614: // <![CDATA[
 2615: function togglePwd(form) {
 2616:     if (form.newintpwd.length) {
 2617:         if (document.getElementById('LC_ownersetpwd')) {
 2618:             for (var i=0; i<form.newintpwd.length; i++) {
 2619:                 if (form.newintpwd[i].checked) {
 2620:                     if (form.newintpwd[i].value == 1) {
 2621:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2622:                     } else {
 2623:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2624:                     }
 2625:                 }
 2626:             }
 2627:         }
 2628:     }
 2629: }
 2630: // ]]>
 2631: </script>
 2632: ENDJS
 2633: 
 2634:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2635:                             &Apache::loncommon::start_data_table().
 2636:                             &Apache::loncommon::start_data_table_row().
 2637:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2638:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2639:                             &mt('No').'</label>'.('&nbsp;'x2).
 2640:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2641:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2642:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2643:                             '<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>'.
 2644:                             &Apache::loncommon::end_data_table_row().
 2645:                             &Apache::loncommon::end_data_table();
 2646:             }
 2647:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2648:                 # Current user has rights to view domain preferences for user's domain
 2649:                 my $result;
 2650:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2651:                     my ($krbver,$krbrealm) = ($1,$2);
 2652:                     if ($krbrealm eq '') {
 2653:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2654:                     } else {
 2655:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2656:                                       $krbrealm,$krbver);
 2657:                     }
 2658:                 } elsif ($currentauth =~ /^internal:/) {
 2659:                     $result = &mt('Currently internally authenticated.');
 2660:                 } elsif ($currentauth =~ /^localauth:/) {
 2661:                     $result = &mt('Currently using local (institutional) authentication.');
 2662:                 } elsif ($currentauth =~ /^unix:/) {
 2663:                     $result = &mt('Currently Filesystem Authenticated.');
 2664:                 } elsif ($currentauth =~ /^lti:/) {
 2665:                     $result = &mt('Currently LTI authenticated.');
 2666:                 }
 2667:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2668:                            &Apache::loncommon::start_data_table().
 2669:                            &Apache::loncommon::start_data_table_row().
 2670:                            '<td>'.$result.'</td>'.
 2671:                            &Apache::loncommon::end_data_table_row()."\n".
 2672:                            &Apache::loncommon::end_data_table();
 2673:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2674:                 my %lt=&Apache::lonlocal::texthash(
 2675:                            'ccld'  => "Change Current Login Data",
 2676:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2677:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2678:                 );
 2679:                 $outcome .= <<ENDNOPRIV;
 2680: <h3>$lt{'ccld'}</h3>
 2681: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2682: <input type="hidden" name="login" value="nochange" />
 2683: ENDNOPRIV
 2684:             }
 2685:         }
 2686:     }  ## End of "check for bad authentication type" logic
 2687:     return $outcome;
 2688: }
 2689: 
 2690: sub modify_login_block {
 2691:     my ($dom,$currentauth) = @_;
 2692:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2693:     my ($authnum,%can_assign) =
 2694:         &Apache::loncommon::get_assignable_auth($dom);
 2695:     my ($authformcurrent,@authform_others,$show_override_msg);
 2696:     if ($currentauth=~/^krb(4|5):/) {
 2697:         $authformcurrent=$authformkrb;
 2698:         if ($can_assign{'int'}) {
 2699:             push(@authform_others,$authformint);
 2700:         }
 2701:         if ($can_assign{'loc'}) {
 2702:             push(@authform_others,$authformloc);
 2703:         }
 2704:         if ($can_assign{'lti'}) {
 2705:             push(@authform_others,$authformlti);
 2706:         }
 2707:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2708:             $show_override_msg = 1;
 2709:         }
 2710:     } elsif ($currentauth=~/^internal:/) {
 2711:         $authformcurrent=$authformint;
 2712:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2713:             push(@authform_others,$authformkrb);
 2714:         }
 2715:         if ($can_assign{'loc'}) {
 2716:             push(@authform_others,$authformloc);
 2717:         }
 2718:         if ($can_assign{'lti'}) {
 2719:             push(@authform_others,$authformlti);
 2720:         }
 2721:         if ($can_assign{'int'}) {
 2722:             $show_override_msg = 1;
 2723:         }
 2724:     } elsif ($currentauth=~/^unix:/) {
 2725:         $authformcurrent=$authformfsys;
 2726:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2727:             push(@authform_others,$authformkrb);
 2728:         }
 2729:         if ($can_assign{'int'}) {
 2730:             push(@authform_others,$authformint);
 2731:         }
 2732:         if ($can_assign{'loc'}) {
 2733:             push(@authform_others,$authformloc);
 2734:         }
 2735:         if ($can_assign{'lti'}) {
 2736:             push(@authform_others,$authformlti);
 2737:         }
 2738:         if ($can_assign{'fsys'}) {
 2739:             $show_override_msg = 1;
 2740:         }
 2741:     } elsif ($currentauth=~/^localauth:/) {
 2742:         $authformcurrent=$authformloc;
 2743:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2744:             push(@authform_others,$authformkrb);
 2745:         }
 2746:         if ($can_assign{'int'}) {
 2747:             push(@authform_others,$authformint);
 2748:         }
 2749:         if ($can_assign{'lti'}) {
 2750:             push(@authform_others,$authformlti);
 2751:         }
 2752:         if ($can_assign{'loc'}) {
 2753:             $show_override_msg = 1;
 2754:         }
 2755:     } elsif ($currentauth=~/^lti:/) {
 2756:         $authformcurrent=$authformlti;
 2757:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2758:             push(@authform_others,$authformkrb);
 2759:         }
 2760:         if ($can_assign{'int'}) {
 2761:             push(@authform_others,$authformint);
 2762:         }
 2763:         if ($can_assign{'loc'}) {
 2764:             push(@authform_others,$authformloc);
 2765:         }
 2766:     }
 2767:     if ($show_override_msg) {
 2768:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2769:                            '</td></tr>'."\n".
 2770:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2771:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2772:                            '<td align="right"><span class="LC_cusr_emph">'.
 2773:                             &mt('will override current values').
 2774:                             '</span></td></tr></table>';
 2775:     }
 2776:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2777: }
 2778: 
 2779: sub personal_data_display {
 2780:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$readonly,$rolesarray,$now,
 2781:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2782:     my ($output,%userenv,%canmodify,%canmodify_status,$disabled);
 2783:     my @userinfo = ('firstname','middlename','lastname','generation',
 2784:                     'permanentemail','id');
 2785:     my $rowcount = 0;
 2786:     my $editable = 0;
 2787:     my %textboxsize = (
 2788:                        firstname      => '15',
 2789:                        middlename     => '15',
 2790:                        lastname       => '15',
 2791:                        generation     => '5',
 2792:                        permanentemail => '25',
 2793:                        id             => '15',
 2794:                       );
 2795: 
 2796:     my %lt=&Apache::lonlocal::texthash(
 2797:                 'pd'             => "Personal Data",
 2798:                 'firstname'      => "First Name",
 2799:                 'middlename'     => "Middle Name",
 2800:                 'lastname'       => "Last Name",
 2801:                 'generation'     => "Generation",
 2802:                 'permanentemail' => "Permanent e-mail address",
 2803:                 'id'             => "Student/Employee ID",
 2804:                 'lg'             => "Login Data",
 2805:                 'inststatus'     => "Affiliation",
 2806:                 'email'          => 'E-mail address',
 2807:                 'valid'          => 'Validation',
 2808:                 'username'       => 'Username',
 2809:     );
 2810: 
 2811:     %canmodify_status =
 2812:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2813:                                                    ['inststatus'],$rolesarray);
 2814:     if (!$newuser) {
 2815:         # Get the users information
 2816:         %userenv = &Apache::lonnet::get('environment',
 2817:                    ['firstname','middlename','lastname','generation',
 2818:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2819:         %canmodify =
 2820:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2821:                                                        \@userinfo,$rolesarray);
 2822:     } elsif ($context eq 'selfcreate') {
 2823:         if ($newuser eq 'email') {
 2824:             if (ref($emailusername) eq 'HASH') {
 2825:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2826:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2827:                     @userinfo = ();
 2828:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2829:                         foreach my $field (@{$infofields}) { 
 2830:                             if ($emailusername->{$usertype}->{$field}) {
 2831:                                 push(@userinfo,$field);
 2832:                                 $canmodify{$field} = 1;
 2833:                                 unless ($textboxsize{$field}) {
 2834:                                     $textboxsize{$field} = 25;
 2835:                                 }
 2836:                                 unless ($lt{$field}) {
 2837:                                     $lt{$field} = $infotitles->{$field};
 2838:                                 }
 2839:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2840:                                     $lt{$field} .= '<b>*</b>';
 2841:                                 }
 2842:                             }
 2843:                         }
 2844:                     }
 2845:                 }
 2846:             }
 2847:         } else {
 2848:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2849:                                                $inst_results,$rolesarray);
 2850:         }
 2851:     } elsif ($readonly) {
 2852:         $disabled = ' disabled="disabled"';
 2853:     }
 2854: 
 2855:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2856:     $output = '<h3 class="LC_heading_3">'.$lt{'pd'}.'</h3>'.
 2857:               &Apache::lonhtmlcommon::start_pick_box();
 2858:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2859:         my $size = 25;
 2860:         if ($condition) {
 2861:             if ($condition =~ /^\@[^\@]+$/) {
 2862:                 $size = 10;
 2863:             } else {
 2864:                 undef($condition);
 2865:             }
 2866:         } 
 2867:         if ($excluded) {
 2868:             unless ($excluded =~ /^\@[^\@]+$/) {
 2869:                 undef($condition);
 2870:             }
 2871:         }
 2872:         $output .= &Apache::lonhtmlcommon::row_title('<label for="uname_selfcreate">'.$lt{'email'}.'</label><b>*</b>',undef,
 2873:                                                      'LC_oddrow_value')."\n".
 2874:                    '<input type="text" name="uname" id="uname_selfcreate" size="'.$size.'" value="" autocomplete="off" />';
 2875:         if ($condition) {
 2876:             $output .= $condition;
 2877:         } elsif ($excluded) {
 2878:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2879:                                                                      $excluded).'</span>';
 2880:         }
 2881:         if ($usernameset eq 'first') {
 2882:             $output .= '<br /><span style="font-size: smaller">';
 2883:             if ($condition) {
 2884:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2885:                                       $condition);
 2886:             } else {
 2887:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2888:             }
 2889:             $output .= '</span>';
 2890:         }
 2891:         $rowcount ++;
 2892:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2893:         my $upassone = '<input type="password" name="upass'.$now.'" id="upass_selfcreate" size="20" autocomplete="new-password" />';
 2894:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" id="upasscheck_selfcreate" size="20" autocomplete="new-password" />';
 2895:         $output .= &Apache::lonhtmlcommon::row_title('<label for="upass_selfcreate">'.&mt('Password').'</label><b>*</b>',
 2896:                                                     'LC_pick_box_title',
 2897:                                                     'LC_oddrow_value')."\n".
 2898:                    $upassone."\n".
 2899:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2900:                    &Apache::lonhtmlcommon::row_title('<label for="upasscheck_selfcreate">'.&mt('Confirm password').'</label><b>*</b>',
 2901:                                                      'LC_pick_box_title',
 2902:                                                      'LC_oddrow_value')."\n".
 2903:                    $upasstwo.
 2904:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2905:         if ($usernameset eq 'free') {
 2906:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2907:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2908:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2909:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2910:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2911:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2912:                        &mt('No').'</label></span>'."\n".
 2913:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2914:                        '<br /><span class="LC_nobreak"><label>'.&mt('Preferred username').
 2915:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2916:                        '</label></span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2917:             $rowcount ++;
 2918:         }
 2919:     }
 2920:     my %shownfields;
 2921:     if ($env{'request.role.domain'} ne $ccdomain) {
 2922:         my %shownfields_by_type =
 2923:             &Apache::lonuserutils::get_othdom_shownfields($ccdomain,\@userinfo);
 2924:         my @types = split(/:/,$userenv{'inststatus'});
 2925:         if (@types == 0) {
 2926:             @types = ('default');
 2927:         }
 2928:         foreach my $type (@types) {
 2929:             if (ref($shownfields_by_type{$type}) eq 'HASH') {
 2930:                 foreach my $field (keys(%{$shownfields_by_type{$type}})) {
 2931:                     if ($shownfields_by_type{$type}{$field}) {
 2932:                         $shownfields{$field} = 1;
 2933:                     }
 2934:                 }
 2935:             }
 2936:         }
 2937:     }
 2938:     foreach my $item (@userinfo) {
 2939:         my $rowtitle = $lt{$item};
 2940:         my $hiderow = 0;
 2941:         if ($item eq 'generation') {
 2942:             $rowtitle = $genhelp.$rowtitle;
 2943:         }
 2944:         my $row = &Apache::lonhtmlcommon::row_title('<label for="userinfo_'.$item.'">'.$rowtitle.'</label>',undef,'LC_oddrow_value')."\n";
 2945:         if ($newuser) {
 2946:             if (ref($inst_results) eq 'HASH') {
 2947:                 if ($inst_results->{$item} ne '') {
 2948:                     $row .= '<input type="hidden" name="c'.$item.'" id="userinfo_'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2949:                 } else {
 2950:                     if ($context eq 'selfcreate') {
 2951:                         if ($canmodify{$item}) {
 2952:                             $row .= '<input type="text" name="c'.$item.'" id="userinfo_'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2953:                             $editable ++;
 2954:                         } else {
 2955:                             $hiderow = 1;
 2956:                         }
 2957:                     } else {
 2958:                         $row .= '<input type="text" name="c'.$item.'" id="userinfo_'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2959:                     }
 2960:                 }
 2961:             } else {
 2962:                 if ($context eq 'selfcreate') {
 2963:                     if ($canmodify{$item}) {
 2964:                         if ($newuser eq 'email') {
 2965:                             $row .= '<input type="text" name="'.$item.'" id="userinfo_'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2966:                         } else {
 2967:                             $row .= '<input type="text" name="c'.$item.'" id="userinfo_'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2968:                         }
 2969:                         $editable ++;
 2970:                     } else {
 2971:                         $hiderow = 1;
 2972:                     }
 2973:                 } else {
 2974:                     $row .= '<input type="text" name="c'.$item.'" id="userinfo_'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2975:                 }
 2976:             }
 2977:         } else {
 2978:             if ($canmodify{$item}) {
 2979:                 $row .= '<input type="text" name="c'.$item.'" id="userinfo_'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2980:                 if (($item eq 'id') && (!$newuser)) {
 2981:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2982:                 }
 2983:             } else {
 2984:                 if ($env{'request.role.domain'} ne $ccdomain) {
 2985:                     if ($shownfields{$item}) {
 2986:                         $row .= $userenv{$item};
 2987:                     } else {
 2988:                         $row .= &mt('not shown');
 2989:                     }
 2990:                 } else {
 2991:                     $row .= $userenv{$item};
 2992:                 }
 2993:             }
 2994:         }
 2995:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2996:         if (!$hiderow) {
 2997:             $output .= $row;
 2998:             $rowcount ++;
 2999:         }
 3000:     }
 3001:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 3002:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 3003:         if (ref($types) eq 'ARRAY') {
 3004:             if (@{$types} > 0) {
 3005:                 my ($hiderow,$shown);
 3006:                 if ($canmodify_status{'inststatus'}) {
 3007:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 3008:                 } else {
 3009:                     if ($userenv{'inststatus'} eq '') {
 3010:                         $hiderow = 1;
 3011:                     } else {
 3012:                         my @showitems;
 3013:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 3014:                             if (exists($usertypes->{$item})) {
 3015:                                 push(@showitems,$usertypes->{$item});
 3016:                             } else {
 3017:                                 push(@showitems,$item);
 3018:                             }
 3019:                         }
 3020:                         if (@showitems) {
 3021:                             $shown = join(', ',@showitems);
 3022:                         } else {
 3023:                             $hiderow = 1;
 3024:                         }
 3025:                     }
 3026:                 }
 3027:                 if (!$hiderow) {
 3028:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 3029:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 3030:                     if ($context eq 'selfcreate') {
 3031:                         $rowcount ++;
 3032:                     }
 3033:                     $output .= $row;
 3034:                 }
 3035:             }
 3036:         }
 3037:     }
 3038:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 3039:         if ($captchaform) {
 3040:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 3041:                                                          'LC_pick_box_title')."\n".
 3042:                        $captchaform."\n".'<br /><br />'.
 3043:                        &Apache::lonhtmlcommon::row_closure(1); 
 3044:             $rowcount ++;
 3045:         }
 3046:         if ($showsubmit) {
 3047:             my $submit_text = &mt('Create account');
 3048:             $output .= &Apache::lonhtmlcommon::row_title('<span class="LC_visually_hidden">'.
 3049:                                                          &mt('Submit').'</span>','','','',1)."\n".
 3050:                        '<br /><input type="submit" name="createaccount" value="'.
 3051:                        $submit_text.'" />';
 3052:             if ($usertype ne '') {
 3053:                 $output .= '<input type="hidden" name="type" value="'.
 3054:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 3055:             }
 3056:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 3057:         }
 3058:     }
 3059:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 3060:     if (wantarray) {
 3061:         if ($context eq 'selfcreate') {
 3062:             return($output,$rowcount,$editable);
 3063:         } else {
 3064:             return $output;
 3065:         }
 3066:     } else {
 3067:         return $output;
 3068:     }
 3069: }
 3070: 
 3071: sub pick_inst_statuses {
 3072:     my ($curr,$usertypes,$types) = @_;
 3073:     my ($output,$rem,@currtypes);
 3074:     if ($curr ne '') {
 3075:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 3076:     }
 3077:     my $numinrow = 2;
 3078:     if (ref($types) eq 'ARRAY') {
 3079:         $output = '<table>';
 3080:         my $lastcolspan; 
 3081:         for (my $i=0; $i<@{$types}; $i++) {
 3082:             if (defined($usertypes->{$types->[$i]})) {
 3083:                 my $rem = $i%($numinrow);
 3084:                 if ($rem == 0) {
 3085:                     if ($i<@{$types}-1) {
 3086:                         if ($i > 0) { 
 3087:                             $output .= '</tr>';
 3088:                         }
 3089:                         $output .= '<tr>';
 3090:                     }
 3091:                 } elsif ($i==@{$types}-1) {
 3092:                     my $colsleft = $numinrow - $rem;
 3093:                     if ($colsleft > 1) {
 3094:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 3095:                     }
 3096:                 }
 3097:                 my $check = ' ';
 3098:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 3099:                     $check = ' checked="checked" ';
 3100:                 }
 3101:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 3102:                            '<span class="LC_nobreak"><label>'.
 3103:                            '<input type="checkbox" name="inststatus" '.
 3104:                            'value="'.$types->[$i].'"'.$check.'/>'.
 3105:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 3106:             }
 3107:         }
 3108:         $output .= '</tr></table>';
 3109:     }
 3110:     return $output;
 3111: }
 3112: 
 3113: sub selfcreate_canmodify {
 3114:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 3115:     if (ref($inst_results) eq 'HASH') {
 3116:         my @inststatuses = &get_inststatuses($inst_results);
 3117:         if (@inststatuses == 0) {
 3118:             @inststatuses = ('default');
 3119:         }
 3120:         $rolesarray = \@inststatuses;
 3121:     }
 3122:     my %canmodify =
 3123:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 3124:                                                    $rolesarray);
 3125:     return %canmodify;
 3126: }
 3127: 
 3128: sub get_inststatuses {
 3129:     my ($insthashref) = @_;
 3130:     my @inststatuses = ();
 3131:     if (ref($insthashref) eq 'HASH') {
 3132:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 3133:             @inststatuses = @{$insthashref->{'inststatus'}};
 3134:         }
 3135:     }
 3136:     return @inststatuses;
 3137: }
 3138: 
 3139: # ================================================================= Phase Three
 3140: sub update_user_data {
 3141:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 3142:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 3143:                                           $env{'form.ccdomain'});
 3144:     # Error messages
 3145:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 3146:     my $end       = '</span><br /><br />';
 3147:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 3148:                     "'$env{'form.prevphase'}','modify')".'" />'.
 3149:                     &mt('Return to previous page').'</a>'.
 3150:                     &Apache::loncommon::end_page();
 3151:     my $now = time;
 3152:     my $title;
 3153:     if (exists($env{'form.makeuser'})) {
 3154: 	$title='Set Privileges for New User';
 3155:     } else {
 3156:         $title='Modify User Privileges';
 3157:     }
 3158:     my $newuser = 0;
 3159:     my ($jsback,$elements) = &crumb_utilities();
 3160:     my $jscript = '<script type="text/javascript">'."\n".
 3161:                   '// <![CDATA['."\n".
 3162:                   $jsback."\n".
 3163:                   '// ]]>'."\n".
 3164:                   '</script>'."\n";
 3165:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 3166:     push (@{$brcrum},
 3167:              {href => "javascript:backPage(document.userupdate)",
 3168:               text => $breadcrumb_text{'search'},
 3169:               faq  => 282,
 3170:               bug  => 'Instructor Interface',}
 3171:              );
 3172:     if ($env{'form.prevphase'} eq 'userpicked') {
 3173:         push(@{$brcrum},
 3174:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 3175:                 text => $breadcrumb_text{'userpicked'},
 3176:                 faq  => 282,
 3177:                 bug  => 'Instructor Interface',});
 3178:     }
 3179:     my $helpitem = 'Course_Change_Privileges';
 3180:     if ($env{'form.action'} eq 'singlestudent') {
 3181:         $helpitem = 'Course_Add_Student';
 3182:     } elsif ($context eq 'author') {
 3183:         $helpitem = 'Author_Change_Privileges';
 3184:     } elsif ($context eq 'domain') {
 3185:         $helpitem = 'Domain_Change_Privileges';
 3186:     }
 3187:     push(@{$brcrum}, 
 3188:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 3189:              text => $breadcrumb_text{'modify'},
 3190:              faq  => 282,
 3191:              bug  => 'Instructor Interface',},
 3192:             {href => "/adm/createuser",
 3193:              text => "Result",
 3194:              faq  => 282,
 3195:              bug  => 'Instructor Interface',
 3196:              help => $helpitem});
 3197:     my $args = {bread_crumbs          => $brcrum,
 3198:                 bread_crumbs_component => 'User Management'};
 3199:     if ($env{'form.popup'}) {
 3200:         $args->{'no_nav_bar'} = 1;
 3201:     }
 3202:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 3203:     $r->print(&update_result_form($uhome));
 3204:     # Check Inputs
 3205:     if (! $env{'form.ccuname'} ) {
 3206: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 3207: 	return;
 3208:     }
 3209:     if (  $env{'form.ccuname'} ne 
 3210: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 3211: 	$r->print($error.&mt('Invalid login name.').'  '.
 3212: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 3213: 		  $end.$rtnlink);
 3214: 	return;
 3215:     }
 3216:     if (! $env{'form.ccdomain'}       ) {
 3217: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 3218: 	return;
 3219:     }
 3220:     if (  $env{'form.ccdomain'} ne
 3221: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 3222: 	$r->print($error.&mt('Invalid domain name.').'  '.
 3223: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 3224: 		  $end.$rtnlink);
 3225: 	return;
 3226:     }
 3227:     if ($uhome eq 'no_host') {
 3228:         $newuser = 1;
 3229:     }
 3230:     if (! exists($env{'form.makeuser'})) {
 3231:         # Modifying an existing user, so check the validity of the name
 3232:         if ($uhome eq 'no_host') {
 3233:             $r->print(
 3234:                 $error
 3235:                .'<p class="LC_error">'
 3236:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 3237:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 3238:                .'</p>');
 3239:             return;
 3240:         }
 3241:     }
 3242:     # Determine authentication method and password for the user being modified
 3243:     my $amode='';
 3244:     my $genpwd='';
 3245:     if ($env{'form.login'} eq 'krb') {
 3246: 	$amode='krb';
 3247: 	$amode.=$env{'form.krbver'};
 3248: 	$genpwd=$env{'form.krbarg'};
 3249:     } elsif ($env{'form.login'} eq 'int') {
 3250: 	$amode='internal';
 3251: 	$genpwd=$env{'form.intarg'};
 3252:     } elsif ($env{'form.login'} eq 'fsys') {
 3253: 	$amode='unix';
 3254: 	$genpwd=$env{'form.fsysarg'};
 3255:     } elsif ($env{'form.login'} eq 'loc') {
 3256: 	$amode='localauth';
 3257: 	$genpwd=$env{'form.locarg'};
 3258: 	$genpwd=" " if (!$genpwd);
 3259:     } elsif ($env{'form.login'} eq 'lti') {
 3260:         $amode='lti';
 3261:         $genpwd=" ";
 3262:     } elsif (($env{'form.login'} eq 'nochange') ||
 3263:              ($env{'form.login'} eq ''        )) { 
 3264:         # There is no need to tell the user we did not change what they
 3265:         # did not ask us to change.
 3266:         # If they are creating a new user but have not specified login
 3267:         # information this will be caught below.
 3268:     } else {
 3269:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 3270:             return;
 3271:     }
 3272: 
 3273:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 3274:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 3275:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 3276:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 3277: 
 3278:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 3279:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3280:     my @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
 3281:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 3282:     my @requestauthor = ('requestauthor');
 3283:     my @authordefaults = ('webdav','editors','archive');
 3284:     my ($othertitle,$usertypes,$types) = 
 3285:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 3286:     my %canmodify_status =
 3287:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 3288:                                                    ['inststatus']);
 3289:     if ($env{'form.makeuser'}) {
 3290: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 3291:         # Check for the authentication mode and password
 3292:         if (! $amode || ! $genpwd) {
 3293: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 3294: 	    return;
 3295: 	}
 3296:         # Determine desired host
 3297:         my $desiredhost = $env{'form.hserver'};
 3298:         if (lc($desiredhost) eq 'default') {
 3299:             $desiredhost = undef;
 3300:         } else {
 3301:             my %home_servers = 
 3302: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 3303:             if (! exists($home_servers{$desiredhost})) {
 3304:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 3305:                 return;
 3306:             }
 3307:         }
 3308:         # Check ID format
 3309:         my %checkhash;
 3310:         my %checks = ('id' => 1);
 3311:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 3312:             'newuser' => $newuser, 
 3313:             'id' => $env{'form.cid'},
 3314:         );
 3315:         if ($env{'form.cid'} ne '') {
 3316:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 3317:                                           \%rulematch,\%inst_results,\%curr_rules);
 3318:             if (ref($alerts{'id'}) eq 'HASH') {
 3319:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3320:                     my $domdesc =
 3321:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 3322:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 3323:                         my $userchkmsg;
 3324:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 3325:                             $userchkmsg  = 
 3326:                                 &Apache::loncommon::instrule_disallow_msg('id',
 3327:                                                                     $domdesc,1).
 3328:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 3329:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 3330:                         }
 3331:                         $r->print($error.&mt('Invalid ID format').$end.
 3332:                                   $userchkmsg.$rtnlink);
 3333:                         return;
 3334:                     }
 3335:                 }
 3336:             }
 3337:         }
 3338:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 3339: 	# Call modifyuser
 3340: 	my $result = &Apache::lonnet::modifyuser
 3341: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 3342:              $amode,$genpwd,$env{'form.cfirstname'},
 3343:              $env{'form.cmiddlename'},$env{'form.clastname'},
 3344:              $env{'form.cgeneration'},undef,$desiredhost,
 3345:              $env{'form.cpermanentemail'});
 3346: 	$r->print(&mt('Generating user').': '.$result);
 3347:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 3348:                                                $env{'form.ccdomain'});
 3349:         my (%changeHash,%newcustom,%changed,%changedinfo);
 3350:         if ($uhome ne 'no_host') {
 3351:             if ($context eq 'domain') {
 3352:                 foreach my $name ('portfolio','author') {
 3353:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3354:                         if ($env{'form.'.$name.'quota'} eq '') {
 3355:                             $newcustom{$name.'quota'} = 0;
 3356:                         } else {
 3357:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 3358:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 3359:                         }
 3360:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 3361:                             $changed{$name.'quota'} = 1;
 3362:                         }
 3363:                     }
 3364:                 }
 3365:                 foreach my $item (@usertools) {
 3366:                     if ($env{'form.custom'.$item} == 1) {
 3367:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3368:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3369:                                                      \%changeHash,'tools');
 3370:                     }
 3371:                 }
 3372:                 foreach my $item (@requestcourses) {
 3373:                     if ($env{'form.custom'.$item} == 1) {
 3374:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3375:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3376:                             $newcustom{$item} .= '=';
 3377:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3378:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3379:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3380:                             }
 3381:                         }
 3382:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3383:                                                       \%changeHash,'requestcourses');
 3384:                     }
 3385:                 }
 3386:                 if ($env{'form.customrequestauthor'} == 1) {
 3387:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3388:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3389:                                                     $newcustom{'requestauthor'},
 3390:                                                     \%changeHash,'requestauthor');
 3391:                 }
 3392:                 if ($env{'form.customeditors'} == 1) {
 3393:                     my @editors;
 3394:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 3395:                     if (@posseditors) {
 3396:                         foreach my $editor (@posseditors) {
 3397:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 3398:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 3399:                                     push(@editors,$editor);
 3400:                                 }
 3401:                             }
 3402:                         }
 3403:                     }
 3404:                     if (@editors) {
 3405:                         @editors = sort(@editors);
 3406:                         $changed{'editors'} = &tool_admin('editors',join(',',@editors),
 3407:                                                           \%changeHash,'authordefaults');
 3408:                     }
 3409:                 }
 3410:                 if ($env{'form.customwebdav'} == 1) {
 3411:                     $newcustom{'webdav'} = $env{'form.authordefaults_webdav'};
 3412:                     $changed{'webdav'} = &tool_admin('webdav',$newcustom{'webdav'},
 3413:                                                      \%changeHash,'authordefaults');
 3414:                 }
 3415:                 if ($env{'form.customarchive'} == 1) {
 3416:                     $newcustom{'archive'} = $env{'form.authordefaults_archive'};
 3417:                     $changed{'archive'} = &tool_admin('archive',$newcustom{'archive'},
 3418:                                                       \%changeHash,'authordefaults');
 3419: 
 3420:                 }
 3421:             }
 3422:             if ($canmodify_status{'inststatus'}) {
 3423:                 if (exists($env{'form.inststatus'})) {
 3424:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3425:                     if (@inststatuses > 0) {
 3426:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3427:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3428:                     }
 3429:                 }
 3430:             }
 3431:             if (keys(%changed)) {
 3432:                 foreach my $item (@userinfo) {
 3433:                     $changeHash{$item}  = $env{'form.c'.$item};
 3434:                 }
 3435:                 my $chgresult =
 3436:                      &Apache::lonnet::put('environment',\%changeHash,
 3437:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3438:             }
 3439:         }
 3440:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3441:                   &Apache::lonnet::hostname($uhome));
 3442:     } elsif (($env{'form.login'} ne 'nochange') &&
 3443:              ($env{'form.login'} ne ''        )) {
 3444: 	# Modify user privileges
 3445:         if (! $amode || ! $genpwd) {
 3446: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3447: 	    return;
 3448: 	}
 3449: 	# Only allow authentication modification if the person has authority
 3450: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3451: 	    $r->print('Modifying authentication: '.
 3452:                       &Apache::lonnet::modifyuserauth(
 3453: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3454:                        $amode,$genpwd));
 3455:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3456: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3457: 	} else {
 3458: 	    # Okay, this is a non-fatal error.
 3459: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3460: 	}
 3461:     } elsif (($env{'form.intarg'} ne '') &&
 3462:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3463:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3464:         $r->print('Modifying authentication: '.
 3465:                   &Apache::lonnet::modifyuserauth(
 3466:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3467:                   'internal',$env{'form.intarg'}));
 3468:     }
 3469:     $r->rflush(); # Finish display of header before time consuming actions start
 3470:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3471:     ##
 3472:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3473:     if ($context eq 'course') {
 3474:         ($cnum,$cdom) =
 3475:             &Apache::lonuserutils::get_course_identity();
 3476:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3477:         if ($showcredits) {
 3478:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3479:         }
 3480:     }
 3481:     if (! $env{'form.makeuser'} ) {
 3482:         # Check for need to change
 3483:         my %userenv = &Apache::lonnet::get
 3484:             ('environment',['firstname','middlename','lastname','generation',
 3485:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3486:              'tools.aboutme','tools.blog','tools.webdav',
 3487:              'tools.portfolio','tools.timezone','tools.portaccess',
 3488:              'authormanagers','authoreditors','authorarchive','requestauthor',
 3489:              'requestcourses.official','requestcourses.unofficial',
 3490:              'requestcourses.community','requestcourses.textbook',
 3491:              'requestcourses.placement','requestcourses.lti',
 3492:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3493:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3494:              'reqcrsotherdom.placement','domcoord.author'],
 3495:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3496:         my ($tmp) = keys(%userenv);
 3497:         if ($tmp =~ /^(con_lost|error)/i) { 
 3498:             %userenv = ();
 3499:         }
 3500:         unless (($userenv{'domcoord.author'} eq 'blocked') &&
 3501:                 (($env{'user.name'} ne $env{'form.ccuname'}) ||
 3502:                  ($env{'user.domain'} ne $env{'form.ccdomain'}))) {
 3503:             push(@authordefaults,'managers');
 3504:         }
 3505:         my $no_forceid_alert;
 3506:         # Check to see if user information can be changed
 3507:         my %domconfig =
 3508:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3509:                                      $env{'form.ccdomain'});
 3510:         my @statuses = ('active','future');
 3511:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3512:         my ($auname,$audom);
 3513:         if ($context eq 'author') {
 3514:             $auname = $env{'user.name'};
 3515:             $audom = $env{'user.domain'};     
 3516:         }
 3517:         foreach my $item (keys(%roles)) {
 3518:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3519:             if ($context eq 'course') {
 3520:                 if ($cnum ne '' && $cdom ne '') {
 3521:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3522:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3523:                             push(@userroles,$role);
 3524:                         }
 3525:                     }
 3526:                 }
 3527:             } elsif ($context eq 'author') {
 3528:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3529:                     if (!grep(/^\Q$role\E$/,@userroles)) {
 3530:                         push(@userroles,$role);
 3531:                     }
 3532:                 }
 3533:             }
 3534:         }
 3535:         if ($env{'form.action'} eq 'singlestudent') {
 3536:             if (!grep(/^st$/,@userroles)) {
 3537:                 push(@userroles,'st');
 3538:             }
 3539:         } else {
 3540:             # Check for course or co-author roles being activated or re-enabled
 3541:             if ($context eq 'author' || $context eq 'course') {
 3542:                 foreach my $key (keys(%env)) {
 3543:                     if ($context eq 'author') {
 3544:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3545:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3546:                                 push(@userroles,$1);
 3547:                             }
 3548:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3549:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3550:                                 push(@userroles,$1);
 3551:                             }
 3552:                         }
 3553:                     } elsif ($context eq 'course') {
 3554:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3555:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3556:                                 push(@userroles,$1);
 3557:                             }
 3558:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3559:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3560:                                 push(@userroles,$1);
 3561:                             }
 3562:                         }
 3563:                     }
 3564:                 }
 3565:             }
 3566:         }
 3567:         #Check to see if we can change personal data for the user 
 3568:         my (@mod_disallowed,@longroles);
 3569:         foreach my $role (@userroles) {
 3570:             if ($role eq 'cr') {
 3571:                 push(@longroles,'Custom');
 3572:             } else {
 3573:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3574:             }
 3575:         }
 3576:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3577:         foreach my $item (@userinfo) {
 3578:             # Strip leading and trailing whitespace
 3579:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3580:             if (!$canmodify{$item}) {
 3581:                 if (defined($env{'form.c'.$item})) {
 3582:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3583:                         push(@mod_disallowed,$item);
 3584:                     }
 3585:                 }
 3586:                 $env{'form.c'.$item} = $userenv{$item};
 3587:             }
 3588:         }
 3589:         # Check to see if we can change the Student/Employee ID
 3590:         my $forceid = $env{'form.forceid'};
 3591:         my $recurseid = $env{'form.recurseid'};
 3592:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3593:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3594:                                             $env{'form.ccuname'});
 3595:         if (($uidhash{$env{'form.ccuname'}}) && 
 3596:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3597:             (!$forceid)) {
 3598:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3599:                 $env{'form.cid'} = $userenv{'id'};
 3600:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3601:                                    .'<br />'
 3602:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3603:                                    .'<br />'."\n";
 3604:             }
 3605:         }
 3606:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3607:             my $checkhash;
 3608:             my $checks = { 'id' => 1 };
 3609:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3610:                    { 'newuser' => $newuser,
 3611:                      'id'  => $env{'form.cid'}, 
 3612:                    };
 3613:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3614:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3615:             if (ref($alerts{'id'}) eq 'HASH') {
 3616:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3617:                    $env{'form.cid'} = $userenv{'id'};
 3618:                 }
 3619:             }
 3620:         }
 3621:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3622:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3623:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3624:             %oldsettingstatus,%newsettingstatus);
 3625:         @disporder = ('inststatus');
 3626:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3627:             push(@disporder,('requestcourses','requestauthor','authordefaults'));
 3628:         } else {
 3629:             push(@disporder,'reqcrsotherdom');
 3630:         }
 3631:         push(@disporder,('quota','tools'));
 3632:         $oldinststatus = $userenv{'inststatus'};
 3633:         foreach my $name ('portfolio','author') {
 3634:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3635:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3636:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3637:         }
 3638:         my %canshow;
 3639:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3640:             $canshow{'quota'} = 1;
 3641:         }
 3642:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3643:             $canshow{'tools'} = 1;
 3644:         }
 3645:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3646:             $canshow{'requestcourses'} = 1;
 3647:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3648:             $canshow{'reqcrsotherdom'} = 1;
 3649:         }
 3650:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3651:             $canshow{'inststatus'} = 1;
 3652:         }
 3653:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3654:             $canshow{'requestauthor'} = 1;
 3655:             $canshow{'authordefaults'} = 1;
 3656:         }
 3657:         my (%changeHash,%changed);
 3658:         if ($oldinststatus eq '') {
 3659:             $oldsettings{'inststatus'} = $othertitle; 
 3660:         } else {
 3661:             if (ref($usertypes) eq 'HASH') {
 3662:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3663:             } else {
 3664:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3665:             }
 3666:         }
 3667:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3668:         if ($canmodify_status{'inststatus'}) {
 3669:             $canshow{'inststatus'} = 1;
 3670:             if (exists($env{'form.inststatus'})) {
 3671:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3672:                 if (@inststatuses > 0) {
 3673:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3674:                     $changeHash{'inststatus'} = $newinststatus;
 3675:                     if ($newinststatus ne $oldinststatus) {
 3676:                         $changed{'inststatus'} = $newinststatus;
 3677:                         foreach my $name ('portfolio','author') {
 3678:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3679:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3680:                         }
 3681:                     }
 3682:                     if (ref($usertypes) eq 'HASH') {
 3683:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3684:                     } else {
 3685:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3686:                     }
 3687:                 }
 3688:             } else {
 3689:                 $newinststatus = '';
 3690:                 $changeHash{'inststatus'} = $newinststatus;
 3691:                 $newsettings{'inststatus'} = $othertitle;
 3692:                 if ($newinststatus ne $oldinststatus) {
 3693:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3694:                     foreach my $name ('portfolio','author') {
 3695:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3696:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3697:                     }
 3698:                 }
 3699:             }
 3700:         } elsif ($context ne 'selfcreate') {
 3701:             $canshow{'inststatus'} = 1;
 3702:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3703:         }
 3704:         foreach my $name ('portfolio','author') {
 3705:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3706:         }
 3707:         if ($context eq 'domain') {
 3708:             foreach my $name ('portfolio','author') {
 3709:                 if ($userenv{$name.'quota'} ne '') {
 3710:                     $oldquota{$name} = $userenv{$name.'quota'};
 3711:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3712:                         if ($env{'form.'.$name.'quota'} eq '') {
 3713:                             $newquota{$name} = 0;
 3714:                         } else {
 3715:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3716:                             $newquota{$name} =~ s/[^\d\.]//g;
 3717:                         }
 3718:                         if ($newquota{$name} != $oldquota{$name}) {
 3719:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3720:                                 $changed{$name.'quota'} = 1;
 3721:                             }
 3722:                         }
 3723:                     } else {
 3724:                         if (&quota_admin('',\%changeHash,$name)) {
 3725:                             $changed{$name.'quota'} = 1;
 3726:                             $newquota{$name} = $newdefquota{$name};
 3727:                             $newisdefault{$name} = 1;
 3728:                         }
 3729:                     }
 3730:                 } else {
 3731:                     $oldisdefault{$name} = 1;
 3732:                     $oldquota{$name} = $olddefquota{$name};
 3733:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3734:                         if ($env{'form.'.$name.'quota'} eq '') {
 3735:                             $newquota{$name} = 0;
 3736:                         } else {
 3737:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3738:                             $newquota{$name} =~ s/[^\d\.]//g;
 3739:                         }
 3740:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3741:                             $changed{$name.'quota'} = 1;
 3742:                         }
 3743:                     } else {
 3744:                         $newquota{$name} = $newdefquota{$name};
 3745:                         $newisdefault{$name} = 1;
 3746:                     }
 3747:                 }
 3748:                 if ($oldisdefault{$name}) {
 3749:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3750:                 }  else {
 3751:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3752:                 }
 3753:                 if ($newisdefault{$name}) {
 3754:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3755:                 } else {
 3756:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3757:                 }
 3758:             }
 3759:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3760:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3761:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3762:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3763:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3764:                 my ($isadv,$isauthor) =
 3765:                     &Apache::lonnet::is_advanced_user($env{'form.ccdomain'},$env{'form.ccuname'});
 3766:                 unless ($isauthor) {
 3767:                     &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3768:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3769:                 }
 3770:                 &tool_changes('authordefaults',\@authordefaults,\%oldsettings,\%oldsettingstext,
 3771:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3772:             } else {
 3773:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3774:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3775:             }
 3776:         }
 3777:         foreach my $item (@userinfo) {
 3778:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3779:                 $namechanged{$item} = 1;
 3780:             }
 3781:         }
 3782:         foreach my $name ('portfolio','author') {
 3783:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3784:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3785:         }
 3786:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3787:             my ($chgresult,$namechgresult);
 3788:             if (keys(%changed) > 0) {
 3789:                 $chgresult =
 3790:                     &Apache::lonnet::put('environment',\%changeHash,
 3791:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3792:                 if ($chgresult eq 'ok') {
 3793:                     my ($ca_mgr_del,%ca_mgr_add);
 3794:                     if ($changed{'managers'}) {
 3795:                         my (@adds,@dels);
 3796:                         if ($changeHash{'authormanagers'} eq '') {
 3797:                             @dels = split(/,/,$userenv{'authormanagers'});
 3798:                         } elsif ($userenv{'authormanagers'} eq '') {
 3799:                             @adds = split(/,/,$changeHash{'authormanagers'});
 3800:                         } else {
 3801:                             my @old = split(/,/,$userenv{'authormanagers'});
 3802:                             my @new = split(/,/,$changeHash{'authormanagers'});
 3803:                             my @diffs = &Apache::loncommon::compare_arrays(\@old,\@new);
 3804:                             if (@diffs) {
 3805:                                 foreach my $user (@diffs) {
 3806:                                     if (grep(/^\Q$user\E$/,@old)) {
 3807:                                         push(@dels,$user);
 3808:                                     } elsif (grep(/^\Q$user\E$/,@new)) {
 3809:                                         push(@adds,$user);
 3810:                                     }
 3811:                                 }
 3812:                             }
 3813:                         }
 3814:                         my $key = "internal.manager./$env{'form.ccdomain'}/$env{'form.ccuname'}";
 3815:                         if (@dels) {
 3816:                             foreach my $user (@dels) {
 3817:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3818:                                     &Apache::lonnet::del('environment',[$key],$2,$1);
 3819:                                 }
 3820:                             }
 3821:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3822:                             if (grep(/^\Q$curruser\E$/,@dels)) {
 3823:                                 $ca_mgr_del = $key;
 3824:                             }
 3825:                         }
 3826:                         if (@adds) {
 3827:                             foreach my $user (@adds) {
 3828:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3829:                                     &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 3830:                                 }
 3831:                             }
 3832:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3833:                             if (grep(/^\Q$curruser\E$/,@adds)) {
 3834:                                 $ca_mgr_add{$key} = 1;
 3835:                             }
 3836:                         }
 3837:                     }
 3838:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3839:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3840:                         my (%newenvhash,$got_domdefs,%domdefaults,$got_userenv,
 3841:                             %userenv);
 3842:                         my @fromenv = keys(%changed);
 3843:                         push(@fromenv,'inststatus');
 3844:                         foreach my $key (keys(%changed)) {
 3845:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3846:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3847:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3848:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3849:                                     $changeHash{'requestcourses.'.$key};
 3850:                                 if ($changeHash{'requestcourses.'.$key}) {
 3851:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3852:                                 } else {
 3853:                                     unless ($got_domdefs) {
 3854:                                         %domdefaults =
 3855:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3856:                                         $got_domdefs = 1;
 3857:                                     }
 3858:                                     unless ($got_userenv) {
 3859:                                         %userenv =
 3860:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3861:                                                                              $env{'user.name'},@fromenv);
 3862:                                         $got_userenv = 1;
 3863:                                     }
 3864:                                     $newenvhash{'environment.canrequest.'.$key} =
 3865:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3866:                                             $key,'reload','requestcourses',\%userenv,\%domdefaults);
 3867:                                 }
 3868:                             } elsif ($key eq 'requestauthor') {
 3869:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3870:                                 if ($changeHash{$key}) {
 3871:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3872:                                 } else {
 3873:                                     unless ($got_domdefs) {
 3874:                                         %domdefaults =
 3875:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3876:                                         $got_domdefs = 1;
 3877:                                     }
 3878:                                     unless ($got_userenv) {
 3879:                                         %userenv =
 3880:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3881:                                                                              $env{'user.name'},@fromenv);
 3882:                                         $got_userenv = 1;
 3883:                                     }
 3884:                                     $newenvhash{'environment.canrequest.author'} =
 3885:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3886:                                             $key,'reload','requestauthor',\%userenv,\%domdefaults);
 3887:                                 }
 3888:                             } elsif ($key eq 'editors') {
 3889:                                 $newenvhash{'environment.author'.$key} = $changeHash{'author'.$key};
 3890:                                 if ($env{'form.customeditors'}) {
 3891:                                     $newenvhash{'environment.editors'} = $changeHash{'author'.$key};
 3892:                                 } else {
 3893:                                     unless ($got_domdefs) {
 3894:                                         %domdefaults =
 3895:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3896:                                         $got_domdefs = 1;
 3897:                                     }
 3898:                                     if ($domdefaults{'editors'} ne '') {
 3899:                                         $newenvhash{'environment.editors'} = $domdefaults{'editors'};
 3900:                                     } else {
 3901:                                         $newenvhash{'environment.editors'} = 'edit,xml';
 3902:                                     }
 3903:                                 }
 3904:                             } elsif ($key eq 'archive') {
 3905:                                 $newenvhash{'environment.author.'.$key} =
 3906:                                     $changeHash{'author.'.$key};
 3907:                                 if ($changeHash{'author.'.$key} ne '') {
 3908:                                     $newenvhash{'environment.canarchive'} =
 3909:                                         $changeHash{'author.'.$key};
 3910:                                 } else {
 3911:                                     unless ($got_domdefs) {
 3912:                                         %domdefaults =
 3913:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3914:                                         $got_domdefs = 1;
 3915:                                     }
 3916:                                     $newenvhash{'environment.canarchive'} =
 3917:                                         $domdefaults{'archive'};
 3918:                                 }
 3919:                             } elsif ($key ne 'quota') {
 3920:                                 $newenvhash{'environment.tools.'.$key} = 
 3921:                                     $changeHash{'tools.'.$key};
 3922:                                 if ($changeHash{'tools.'.$key} ne '') {
 3923:                                     $newenvhash{'environment.availabletools.'.$key} =
 3924:                                         $changeHash{'tools.'.$key};
 3925:                                 } else {
 3926:                                     unless ($got_domdefs) {
 3927:                                         %domdefaults =
 3928:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3929:                                         $got_domdefs = 1;
 3930:                                     }
 3931:                                     unless ($got_userenv) {
 3932:                                         %userenv =
 3933:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3934:                                                                              $env{'user.name'},@fromenv);
 3935:                                         $got_userenv = 1;
 3936:                                     }
 3937:                                     $newenvhash{'environment.availabletools.'.$key} =
 3938:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3939:                                             $key,'reload','tools',\%userenv,\%domdefaults);
 3940:                                 }
 3941:                             }
 3942:                         }
 3943:                         if (keys(%newenvhash)) {
 3944:                             &Apache::lonnet::appenv(\%newenvhash);
 3945:                         }
 3946:                     } else {
 3947:                         if ($ca_mgr_del) {
 3948:                             &Apache::lonnet::delenv($ca_mgr_del);
 3949:                         }
 3950:                         if (keys(%ca_mgr_add)) {
 3951:                             &Apache::lonnet::appenv(\%ca_mgr_add);
 3952:                         }
 3953:                     }
 3954:                     if ($changed{'aboutme'}) {
 3955:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3956:                                                                      $env{'form.ccdomain'});
 3957:                     }
 3958:                 }
 3959:             }
 3960:             if (keys(%namechanged) > 0) {
 3961:                 foreach my $field (@userinfo) {
 3962:                     $changeHash{$field}  = $env{'form.c'.$field};
 3963:                 }
 3964: # Make the change
 3965:                 $namechgresult =
 3966:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3967:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3968:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3969:                         $changeHash{'lastname'},$changeHash{'generation'},
 3970:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3971:                 %userupdate = (
 3972:                                lastname   => $env{'form.clastname'},
 3973:                                middlename => $env{'form.cmiddlename'},
 3974:                                firstname  => $env{'form.cfirstname'},
 3975:                                generation => $env{'form.cgeneration'},
 3976:                                id         => $env{'form.cid'},
 3977:                              );
 3978:             }
 3979:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3980:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3981:             # Tell the user we changed the name
 3982:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3983:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3984:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3985:                                   \%newsettingstext);
 3986:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3987:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3988:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3989:                     if (($recurseid) &&
 3990:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3991:                         my $idresult = 
 3992:                             &Apache::lonuserutils::propagate_id_change(
 3993:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3994:                                 \%userupdate);
 3995:                         $r->print('<br />'.$idresult.'<br />');
 3996:                     }
 3997:                 }
 3998:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3999:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 4000:                     my %newenvhash;
 4001:                     foreach my $key (keys(%changeHash)) {
 4002:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 4003:                     }
 4004:                     &Apache::lonnet::appenv(\%newenvhash);
 4005:                 }
 4006:             } else { # error occurred
 4007:                 $r->print(
 4008:                     '<p class="LC_error">'
 4009:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 4010:                             '"'.$env{'form.ccuname'}.'"',
 4011:                             '"'.$env{'form.ccdomain'}.'"')
 4012:                    .'</p>');
 4013:             }
 4014:         } else { # End of if ($env ... ) logic
 4015:             # They did not want to change the users name, quota, tool availability,
 4016:             # or ability to request creation of courses, 
 4017:             # but we can still tell them what the name and quota and availabilities are  
 4018:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 4019:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 4020:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 4021:         }
 4022:         if (@mod_disallowed) {
 4023:             my ($rolestr,$contextname);
 4024:             if (@longroles > 0) {
 4025:                 $rolestr = join(', ',@longroles);
 4026:             } else {
 4027:                 $rolestr = &mt('No roles');
 4028:             }
 4029:             if ($context eq 'course') {
 4030:                 $contextname = 'course';
 4031:             } elsif ($context eq 'author') {
 4032:                 $contextname = 'co-author';
 4033:             }
 4034:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 4035:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4036:             foreach my $field (@mod_disallowed) {
 4037:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 4038:             }
 4039:             $r->print('</ul>');
 4040:             if (@mod_disallowed == 1) {
 4041:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 4042:             } else {
 4043:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 4044:             }
 4045:             my $helplink = 'javascript:helpMenu('."'display'".')';
 4046:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 4047:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 4048:                          ,'<a href="'.$helplink.'">','</a>')
 4049:                       .'<br />');
 4050:         }
 4051:         $r->print('<span class="LC_warning">'
 4052:                   .$no_forceid_alert
 4053:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 4054:                   .'</span>');
 4055:     }
 4056:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 4057:     if ($env{'form.action'} eq 'singlestudent') {
 4058:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 4059:                                $crstype,$showcredits,$defaultcredits);
 4060:         my $linktext = ($crstype eq 'Community' ?
 4061:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 4062:         $r->print(
 4063:             &Apache::lonhtmlcommon::actionbox([
 4064:                 '<a href="javascript:backPage(document.userupdate)">'
 4065:                .($crstype eq 'Community' ? 
 4066:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 4067:                .'</a>']));
 4068:     } else {
 4069:         my @rolechanges = &update_roles($r,$context,$showcredits);
 4070:         if (keys(%namechanged) > 0) {
 4071:             if ($context eq 'course') {
 4072:                 if (@userroles > 0) {
 4073:                     if ((@rolechanges == 0) || 
 4074:                         (!(grep(/^st$/,@rolechanges)))) {
 4075:                         if (grep(/^st$/,@userroles)) {
 4076:                             my $classlistupdated =
 4077:                                 &Apache::lonuserutils::update_classlist($cdom,
 4078:                                               $cnum,$env{'form.ccdomain'},
 4079:                                        $env{'form.ccuname'},\%userupdate);
 4080:                         }
 4081:                     }
 4082:                 }
 4083:             }
 4084:         }
 4085:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 4086:                                                      $env{'form.ccdomain'});
 4087:         if ($env{'form.popup'}) {
 4088:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 4089:         } else {
 4090:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 4091:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 4092:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 4093:         }
 4094:     }
 4095: }
 4096: 
 4097: sub display_userinfo {
 4098:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 4099:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 4100:         $newsetting,$newsettingtext) = @_;
 4101:     return unless (ref($order) eq 'ARRAY' &&
 4102:                    ref($canshow) eq 'HASH' && 
 4103:                    ref($requestcourses) eq 'ARRAY' && 
 4104:                    ref($requestauthor) eq 'ARRAY' &&
 4105:                    ref($usertools) eq 'ARRAY' && 
 4106:                    ref($userenv) eq 'HASH' &&
 4107:                    ref($changedhash) eq 'HASH' &&
 4108:                    ref($oldsetting) eq 'HASH' &&
 4109:                    ref($oldsettingtext) eq 'HASH' &&
 4110:                    ref($newsetting) eq 'HASH' &&
 4111:                    ref($newsettingtext) eq 'HASH');
 4112:     my %lt=&Apache::lonlocal::texthash(
 4113:          'ui'             => 'User Information',
 4114:          'uic'            => 'User Information Changed',
 4115:          'firstname'      => 'First Name',
 4116:          'middlename'     => 'Middle Name',
 4117:          'lastname'       => 'Last Name',
 4118:          'generation'     => 'Generation',
 4119:          'id'             => 'Student/Employee ID',
 4120:          'permanentemail' => 'Permanent e-mail address',
 4121:          'portfolioquota' => 'Disk space allocated to portfolio files',
 4122:          'authorquota'    => 'Disk space allocated to Authoring Space',
 4123:          'blog'           => 'Blog Availability',
 4124:          'webdav'         => 'WebDAV Availability',
 4125:          'aboutme'        => 'Personal Information Page Availability',
 4126:          'portfolio'      => 'Portfolio Availability',
 4127:          'portaccess'     => 'Portfolio Shareable',
 4128:          'timezone'       => 'Can set own Time Zone',
 4129:          'official'       => 'Can Request Official Courses',
 4130:          'unofficial'     => 'Can Request Unofficial Courses',
 4131:          'community'      => 'Can Request Communities',
 4132:          'textbook'       => 'Can Request Textbook Courses',
 4133:          'placement'      => 'Can Request Placement Tests',
 4134:          'lti'            => 'Can Request LTI Courses',
 4135:          'requestauthor'  => 'Can Request Author Role',
 4136:          'inststatus'     => "Affiliation",
 4137:          'prvs'           => 'Previous Value:',
 4138:          'chto'           => 'Changed To:',
 4139:          'editors'        => "Available Editors in Authoring Space",
 4140:          'managers'       => "Co-authors who can add/revoke roles",
 4141:          'archive'        => "Managers can download tar.gz file of Authoring Space",
 4142:          'edit'           => 'Standard editor (Edit)',
 4143:          'xml'            => 'Text editor (EditXML)',
 4144:          'daxe'           => 'Daxe editor (Daxe)',
 4145:     );
 4146:     if ($changed) {
 4147:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 4148:                 &Apache::loncommon::start_data_table().
 4149:                 &Apache::loncommon::start_data_table_header_row());
 4150:         $r->print("<th>&nbsp;</th>\n");
 4151:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 4152:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 4153:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4154:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 4155: 
 4156:         foreach my $item (@userinfo) {
 4157:             my $value = $env{'form.c'.$item};
 4158:             #show changes only:
 4159:             unless ($value eq $userenv->{$item}){
 4160:                 $r->print(&Apache::loncommon::start_data_table_row());
 4161:                 $r->print("<td>$lt{$item}</td>\n");
 4162:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 4163:                 $r->print("<td>$value </td>\n");
 4164:                 $r->print(&Apache::loncommon::end_data_table_row());
 4165:             }
 4166:         }
 4167:         foreach my $entry (@{$order}) {
 4168:             if ($canshow->{$entry}) {
 4169:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') ||
 4170:                     ($entry eq 'requestauthor') || ($entry eq 'authordefaults')) {
 4171:                     my @items;
 4172:                     if ($entry eq 'requestauthor') {
 4173:                         @items = ($entry);
 4174:                     } elsif ($entry eq 'authordefaults') {
 4175:                         @items = ('webdav','managers','editors','archive');
 4176:                     } else {
 4177:                         @items = @{$requestcourses};
 4178:                     }
 4179:                     foreach my $item (@items) {
 4180:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 4181:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 4182:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 4183:                             $r->print("<td>$lt{$item}</td><td>\n");
 4184:                             unless ($item eq 'managers') {
 4185:                                 $r->print($oldsetting->{$item});
 4186:                             }
 4187:                             if ($oldsettingtext->{$item}) {
 4188:                                 if ($oldsetting->{$item}) {
 4189:                                     unless ($item eq 'managers') {
 4190:                                         $r->print(' -- ');
 4191:                                     }
 4192:                                 }
 4193:                                 $r->print($oldsettingtext->{$item});
 4194:                             }
 4195:                             $r->print("</td>\n<td>");
 4196:                             unless ($item eq 'managers') {
 4197:                                 $r->print($newsetting->{$item});
 4198:                             }
 4199:                             if ($newsettingtext->{$item}) {
 4200:                                 if ($newsetting->{$item}) {
 4201:                                     unless ($item eq 'managers') {
 4202:                                         $r->print(' -- ');
 4203:                                     }
 4204:                                 }
 4205:                                 $r->print($newsettingtext->{$item});
 4206:                             }
 4207:                             $r->print("</td>\n");
 4208:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4209:                         }
 4210:                     }
 4211:                 } elsif ($entry eq 'tools') {
 4212:                     foreach my $item (@{$usertools}) {
 4213:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 4214:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4215:                             $r->print("<td>$lt{$item}</td>\n");
 4216:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 4217:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 4218:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4219:                         }
 4220:                     }
 4221:                 } elsif ($entry eq 'quota') {
 4222:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 4223:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 4224:                         foreach my $name ('portfolio','author') {
 4225:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 4226:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4227:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 4228:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 4229:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 4230:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4231:                             }
 4232:                         }
 4233:                     }
 4234:                 } else {
 4235:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 4236:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4237:                         $r->print("<td>$lt{$entry}</td>\n");
 4238:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 4239:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 4240:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4241:                     }
 4242:                 }
 4243:             }
 4244:         }
 4245:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 4246:     } else {
 4247:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 4248:                   '<p>'.&mt('No changes made to user information').'</p>');
 4249:     }
 4250:     return;
 4251: }
 4252: 
 4253: sub tool_changes {
 4254:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 4255:         $changed,$newaccess,$newaccesstext) = @_;
 4256:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 4257:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 4258:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 4259:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 4260:         return;
 4261:     }
 4262:     my %reqdisplay = &requestchange_display();
 4263:     if ($context eq 'reqcrsotherdom') {
 4264:         my @options = ('approval','validate','autolimit');
 4265:         my $optregex = join('|',@options);
 4266:         my $cdom = $env{'request.role.domain'};
 4267:         foreach my $tool (@{$usertools}) {
 4268:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4269:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4270:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 4271:             my ($newop,$limit);
 4272:             if ($env{'form.'.$context.'_'.$tool}) {
 4273:                 $newop = $env{'form.'.$context.'_'.$tool};
 4274:                 if ($newop eq 'autolimit') {
 4275:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4276:                     $limit =~ s/\D+//g;
 4277:                     $newop .= '='.$limit;
 4278:                 }
 4279:             }
 4280:             if ($userenv->{$context.'.'.$tool} eq '') {
 4281:                 if ($newop) {
 4282:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 4283:                                                   $changeHash,$context);
 4284:                     if ($changed->{$tool}) {
 4285:                         if ($newop =~ /^autolimit/) {
 4286:                             if ($limit) {
 4287:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4288:                             } else {
 4289:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4290:                             }
 4291:                         } else {
 4292:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 4293:                         }
 4294:                     } else {
 4295:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4296:                     }
 4297:                 }
 4298:             } else {
 4299:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 4300:                 my @new;
 4301:                 my $changedoms;
 4302:                 foreach my $req (@curr) {
 4303:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 4304:                         my $oldop = $1;
 4305:                         if ($oldop =~ /^autolimit=(\d*)/) {
 4306:                             my $limit = $1;
 4307:                             if ($limit) {
 4308:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4309:                             } else {
 4310:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4311:                             }
 4312:                         } else {
 4313:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 4314:                         }
 4315:                         if ($oldop ne $newop) {
 4316:                             $changedoms = 1;
 4317:                             foreach my $item (@curr) {
 4318:                                 my ($reqdom,$option) = split(':',$item);
 4319:                                 unless ($reqdom eq $cdom) {
 4320:                                     push(@new,$item);
 4321:                                 }
 4322:                             }
 4323:                             if ($newop) {
 4324:                                 push(@new,$cdom.':'.$newop);
 4325:                             }
 4326:                             @new = sort(@new);
 4327:                         }
 4328:                         last;
 4329:                     }
 4330:                 }
 4331:                 if ((!$changedoms) && ($newop)) {
 4332:                     $changedoms = 1;
 4333:                     @new = sort(@curr,$cdom.':'.$newop);
 4334:                 }
 4335:                 if ($changedoms) {
 4336:                     my $newdomstr;
 4337:                     if (@new) {
 4338:                         $newdomstr = join(',',@new);
 4339:                     }
 4340:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 4341:                                                   $context);
 4342:                     if ($changed->{$tool}) {
 4343:                         if ($env{'form.'.$context.'_'.$tool}) {
 4344:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 4345:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4346:                                 $limit =~ s/\D+//g;
 4347:                                 if ($limit) {
 4348:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4349:                                 } else {
 4350:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4351:                                 }
 4352:                             } else {
 4353:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 4354:                             }
 4355:                         } else {
 4356:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4357:                         }
 4358:                     }
 4359:                 }
 4360:             }
 4361:         }
 4362:         return;
 4363:     }
 4364:     my %tooldesc = &Apache::lonlocal::texthash(
 4365:         'edit' => 'Standard editor (Edit)',
 4366:         'xml'  => 'Text editor (EditXML)',
 4367:         'daxe' => 'Daxe editor (Daxe)',
 4368:     );
 4369:     foreach my $tool (@{$usertools}) {
 4370:         my ($newval,$limit,$envkey);
 4371:         $envkey = $context.'.'.$tool;
 4372:         if ($context eq 'requestcourses') {
 4373:             $newval = $env{'form.crsreq_'.$tool};
 4374:             if ($newval eq 'autolimit') {
 4375:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 4376:                 $limit =~ s/\D+//g;
 4377:                 $newval .= '='.$limit;
 4378:             }
 4379:         } elsif ($context eq 'requestauthor') {
 4380:             $newval = $env{'form.'.$context};
 4381:             $envkey = $context;
 4382:         } elsif ($context eq 'authordefaults') {
 4383:             if ($tool eq 'editors') {
 4384:                 $envkey = 'authoreditors';
 4385:                 if ($env{'form.customeditors'} == 1) {
 4386:                     my @editors;
 4387:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 4388:                     if (@posseditors) {
 4389:                         foreach my $editor (@posseditors) {
 4390:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 4391:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 4392:                                     push(@editors,$editor);
 4393:                                 }
 4394:                             }
 4395:                         }
 4396:                     }
 4397:                     if (@editors) {
 4398:                         $newval = join(',',(sort(@editors)));
 4399:                     }
 4400:                 }
 4401:             } elsif ($tool eq 'managers') {
 4402:                 $envkey = 'authormanagers';
 4403:                 my @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 4404:                 if (@possibles) {
 4405:                     my %ca_roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},
 4406:                                                                  undef,['active','future'],['ca']);
 4407:                     if (keys(%ca_roles)) {
 4408:                         my @custommanagers;
 4409:                         foreach my $user (@possibles) {
 4410:                             if ($user =~ /^($match_username):($match_domain)$/) {
 4411:                                 if (exists($ca_roles{$user.':ca'})) {
 4412:                                     unless ($user eq $env{'form.ccuname'}.':'.$env{'form.ccdomain'}) {
 4413:                                         push(@custommanagers,$user);
 4414:                                     }
 4415:                                 }
 4416:                             }
 4417:                         }
 4418:                         if (@custommanagers) {
 4419:                             $newval = join(',',sort(@custommanagers));
 4420:                         }
 4421:                     }
 4422:                 }
 4423:             } elsif ($tool eq 'webdav') {
 4424:                 $envkey = 'tools.webdav';
 4425:                 $newval = $env{'form.'.$context.'_'.$tool};
 4426:             } elsif ($tool eq 'archive') {
 4427:                 $envkey = 'authorarchive';
 4428:                 $newval = $env{'form.'.$context.'_'.$tool};
 4429:             }
 4430:         } else {
 4431:             $newval = $env{'form.'.$context.'_'.$tool};
 4432:         }
 4433:         if ($userenv->{$envkey} ne '') {
 4434:             $oldaccess->{$tool} = &mt('custom');
 4435:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4436:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 4437:                     my $currlimit = $1;
 4438:                     if ($currlimit eq '') {
 4439:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4440:                     } else {
 4441:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 4442:                     }
 4443:                 } elsif ($userenv->{$envkey}) {
 4444:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4445:                 } else {
 4446:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4447:                 }
 4448:             } elsif ($context eq 'authordefaults') {
 4449:                 if ($tool eq 'managers') {
 4450:                     if ($userenv->{$envkey} eq '') {
 4451:                         $oldaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4452:                     } else {
 4453:                         my $managers = $userenv->{$envkey};
 4454:                         $managers =~ s/,/, /g;
 4455:                         $oldaccesstext->{$tool} = $managers;
 4456:                     }
 4457:                 } elsif ($tool eq 'editors') {
 4458:                     $oldaccesstext->{$tool} = &mt('can use: [_1]',
 4459:                                                   join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4460:                 } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4461:                     if ($userenv->{$envkey}) {
 4462:                         $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4463:                     } else {
 4464:                         $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4465:                     }
 4466:                 }
 4467:             } else {
 4468:                 if ($userenv->{$envkey}) {
 4469:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4470:                 } else {
 4471:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4472:                 }
 4473:             }
 4474:             $changeHash->{$envkey} = $userenv->{$envkey};
 4475:             if (($env{'form.custom'.$tool} == 1) ||
 4476:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4477:                 if ($newval ne $userenv->{$envkey}) {
 4478:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4479:                                                     $context);
 4480:                     if ($changed->{$tool}) {
 4481:                         $newaccess->{$tool} = &mt('custom');
 4482:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4483:                             if ($newval =~ /^autolimit/) {
 4484:                                 if ($limit) {
 4485:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4486:                                 } else {
 4487:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4488:                                 }
 4489:                             } elsif ($newval) {
 4490:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 4491:                             } else {
 4492:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4493:                             }
 4494:                         } elsif ($context eq 'authordefaults') {
 4495:                             if ($tool eq 'editors') {
 4496:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4497:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$changeHash->{$envkey})));
 4498:                             } elsif ($tool eq 'managers') {
 4499:                                 if ($changeHash->{$envkey} eq '') {
 4500:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4501:                                 } else {
 4502:                                     my $managers = $changeHash->{$envkey};
 4503:                                     $managers =~ s/,/, /g;
 4504:                                     $newaccesstext->{$tool} = $managers;
 4505:                                 }
 4506:                             } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4507:                                 if ($newval) {
 4508:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4509:                                 } else {
 4510:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4511:                                 }
 4512:                             }
 4513:                         } else {
 4514:                             if ($newval) {
 4515:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4516:                             } else {
 4517:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4518:                             }
 4519:                         }
 4520:                     } else {
 4521:                         $newaccess->{$tool} = $oldaccess->{$tool};
 4522:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4523:                             if ($userenv->{$envkey} =~ /^autolimit/) {
 4524:                                 if ($limit) {
 4525:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4526:                                 } else {
 4527:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4528:                                 }
 4529:                             } elsif ($userenv->{$envkey}) {
 4530:                                 $newaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4531:                             } else {
 4532:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4533:                             }
 4534:                         } elsif ($context eq 'authordefaults') {
 4535:                             if ($tool eq 'editors') {
 4536:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4537:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4538:                             } elsif ($tool eq 'managers') {
 4539:                                 if ($userenv->{$envkey} eq '') {
 4540:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4541:                                 } else {
 4542:                                     my $managers = $userenv->{$envkey};
 4543:                                     $managers =~ s/,/, /g;
 4544:                                     $newaccesstext->{$tool} = $managers;
 4545:                                 }
 4546:                             } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4547:                                 if ($userenv->{$envkey}) {
 4548:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4549:                                 } else {
 4550:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4551:                                 }
 4552:                             }
 4553:                         } else {
 4554:                             if ($userenv->{$context.'.'.$tool}) {
 4555:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4556:                             } else {
 4557:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4558:                             }
 4559:                         }
 4560:                     }
 4561:                 } else {
 4562:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4563:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4564:                 }
 4565:             } else {
 4566:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 4567:                 if ($changed->{$tool}) {
 4568:                     $newaccess->{$tool} = &mt('default');
 4569:                 } else {
 4570:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4571:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4572:                         if ($newval =~ /^autolimit/) {
 4573:                             if ($limit) {
 4574:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4575:                             } else {
 4576:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4577:                             }
 4578:                         } elsif ($newval) {
 4579:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4580:                         } else {
 4581:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4582:                         }
 4583:                     } elsif ($context eq 'authordefaults') {
 4584:                         if ($tool eq 'editors') {
 4585:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4586:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4587:                         } elsif ($tool eq 'managers') {
 4588:                             if ($newval eq '') {
 4589:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4590:                             } else {
 4591:                                 my $managers = $newval;
 4592:                                 $managers =~ s/,/, /g;
 4593:                                 $newaccesstext->{$tool} = $managers;
 4594:                             }
 4595:                         } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4596:                             if ($userenv->{$envkey}) {
 4597:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4598:                             } else {
 4599:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4600:                             }
 4601:                         }
 4602:                     } else {
 4603:                         if ($userenv->{$context.'.'.$tool}) {
 4604:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4605:                         } else {
 4606:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4607:                         }
 4608:                     }
 4609:                 }
 4610:             }
 4611:         } else {
 4612:             $oldaccess->{$tool} = &mt('default');
 4613:             if (($env{'form.custom'.$tool} == 1) ||
 4614:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4615:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4616:                                                 $context);
 4617:                 if ($changed->{$tool}) {
 4618:                     $newaccess->{$tool} = &mt('custom');
 4619:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4620:                         if ($newval =~ /^autolimit/) {
 4621:                             if ($limit) {
 4622:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4623:                             } else {
 4624:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4625:                             }
 4626:                         } elsif ($newval) {
 4627:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4628:                         } else {
 4629:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4630:                         }
 4631:                     } elsif ($context eq 'authordefaults') {
 4632:                         if ($tool eq 'managers') {
 4633:                             if ($newval eq '') {
 4634:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4635:                             } else {
 4636:                                 my $managers = $newval;
 4637:                                 $managers =~ s/,/, /g;
 4638:                                 $newaccesstext->{$tool} = $managers;
 4639:                             }
 4640:                         } elsif ($tool eq 'editors') {
 4641:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4642:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4643:                         } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4644:                             if ($newval) {
 4645:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4646:                             } else {
 4647:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4648:                             }
 4649:                         }
 4650:                     } else {
 4651:                         if ($newval) {
 4652:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4653:                         } else {
 4654:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4655:                         }
 4656:                     }
 4657:                 } else {
 4658:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4659:                 }
 4660:             } else {
 4661:                 $newaccess->{$tool} = $oldaccess->{$tool};
 4662:             }
 4663:         }
 4664:     }
 4665:     return;
 4666: }
 4667: 
 4668: sub update_roles {
 4669:     my ($r,$context,$showcredits) = @_;
 4670:     my $now=time;
 4671:     my @rolechanges;
 4672:     my (%disallowed,%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 4673:         %pending,%reject,%notifydc,%status,%unauthorized,%currqueued);
 4674:     $got_role_approvals{$context} = '';
 4675:     $process_by{$context} = {};
 4676:     my @domroles = &Apache::lonuserutils::domain_roles();
 4677:     my @cstrroles = &Apache::lonuserutils::construction_space_roles();
 4678:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
 4679:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 4680:     foreach my $key (keys(%env)) {
 4681: 	next if (! $env{$key});
 4682:         next if ($key eq 'form.action');
 4683: 	# Revoke roles
 4684: 	if ($key=~/^form\.rev/) {
 4685: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 4686: # Revoke standard role
 4687: 		my ($scope,$role) = ($1,$2);
 4688: 		my $result =
 4689: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 4690: 						$env{'form.ccuname'},
 4691: 						$scope,$role,'','',$context);
 4692:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4693:                             &mt('Revoking [_1] in [_2]',
 4694:                                 &Apache::lonnet::plaintext($role),
 4695:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4696:                                 $result ne "ok").'<br />');
 4697:                 if ($result ne "ok") {
 4698:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4699:                 }
 4700: 		if ($role eq 'st') {
 4701: 		    my $result = 
 4702:                         &Apache::lonuserutils::classlist_drop($scope,
 4703:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4704: 			    $now);
 4705:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4706: 		}
 4707:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4708:                     push(@rolechanges,$role);
 4709:                 }
 4710: 	    }
 4711: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4712: # Revoke custom role
 4713:                 my $result = &Apache::lonnet::revokecustomrole(
 4714:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4715:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4716:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4717:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4718:                             $result ne 'ok').'<br />');
 4719:                 if ($result ne "ok") {
 4720:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4721:                 }
 4722:                 if (!grep(/^cr$/,@rolechanges)) {
 4723:                     push(@rolechanges,'cr');
 4724:                 }
 4725: 	    }
 4726: 	} elsif ($key=~/^form\.del/) {
 4727: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4728: # Delete standard role
 4729: 		my ($scope,$role) = ($1,$2);
 4730: 		my $result =
 4731: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4732: 						$env{'form.ccuname'},
 4733: 						$scope,$role,$now,0,1,'',
 4734:                                                 $context);
 4735:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4736:                             &mt('Deleting [_1] in [_2]',
 4737:                                 &Apache::lonnet::plaintext($role),
 4738:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4739:                             $result ne 'ok').'<br />');
 4740:                 if ($result ne "ok") {
 4741:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4742:                 }
 4743: 
 4744: 		if ($role eq 'st') {
 4745: 		    my $result = 
 4746:                         &Apache::lonuserutils::classlist_drop($scope,
 4747:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4748: 			    $now);
 4749: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4750: 		}
 4751:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4752:                     push(@rolechanges,$role);
 4753:                 }
 4754:             }
 4755: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4756:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4757: # Delete custom role
 4758:                 my $result =
 4759:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4760:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4761:                         0,1,$context);
 4762:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4763:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4764:                       $result ne "ok").'<br />');
 4765:                 if ($result ne "ok") {
 4766:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4767:                 }
 4768: 
 4769:                 if (!grep(/^cr$/,@rolechanges)) {
 4770:                     push(@rolechanges,'cr');
 4771:                 }
 4772:             }
 4773: 	} elsif ($key=~/^form\.ren/) {
 4774:             my $udom = $env{'form.ccdomain'};
 4775:             my $uname = $env{'form.ccuname'};
 4776: # Re-enable standard role
 4777: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4778:                 my $url = $1;
 4779:                 my $role = $2;
 4780:                 my $id = $url.'_'.$role;
 4781:                 my $logmsg;
 4782:                 my $output;
 4783:                 if ($role eq 'st') {
 4784:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4785:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4786:                         my $credits;
 4787:                         if ($showcredits) {
 4788:                             my $defaultcredits =
 4789:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4790:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4791:                         }
 4792:                         unless ($udom eq $cdom) {
 4793:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4794:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,$credits,
 4795:                                          \%process_by,\%instdoms,\%got_role_approvals,
 4796:                                          \%got_instdoms,\%reject,\%pending,\%notifydc,
 4797:                                          \%status,\%unauthorized,\%currqueued));
 4798:                         }
 4799:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4800:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4801:                             if ($result eq 'refused' && $logmsg) {
 4802:                                 $output = $logmsg;
 4803:                             } else { 
 4804:                                 $output = &mt('Error: [_1]',$result)."\n";
 4805:                             }
 4806:                         } else {
 4807:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4808:                                         &Apache::lonnet::plaintext($role),
 4809:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4810:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4811:                         }
 4812:                     }
 4813:                 } else {
 4814:                     my ($cdom,$cnum,$csec);
 4815:                     if (grep(/^\Q$role\E$/,@cstrroles)) {
 4816:                         ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_username)$});
 4817:                     } elsif (grep(/^\Q$role\E$/,@domroles)) {
 4818:                         ($cdom) = ($url =~ m{^/($match_domain)/$});
 4819:                     } elsif ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4820:                         ($cdom,$cnum,$csec) = ($1,$2,$3);
 4821:                     }
 4822:                     if ($cdom ne '') {
 4823:                         unless ($udom eq $cdom) {
 4824:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4825:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4826:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4827:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4828:                         }
 4829:                     }
 4830: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4831:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4832:                                $context);
 4833:                     $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4834:                                     &Apache::lonnet::plaintext($role),
 4835:                                     &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4836:                     if ($result ne "ok") {
 4837:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4838:                     }
 4839:                 }
 4840:                 $r->print($output);
 4841:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4842:                     push(@rolechanges,$role);
 4843:                 }
 4844: 	    }
 4845: # Re-enable custom role
 4846: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4847:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4848:                 my $id = $url.'_cr'."/$rdom/$rnam/$rolename";
 4849:                 my $role = "cr/$rdom/$rnam/$rolename";
 4850:                 if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4851:                     my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4852:                     unless ($udom eq $cdom) {
 4853:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4854:                                      $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4855:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4856:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4857:                     }
 4858:                 }
 4859:                 my $result = &Apache::lonnet::assigncustomrole(
 4860:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4861:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4862:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4863:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4864:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4865:                     $result ne "ok").'<br />');
 4866:                 if ($result ne "ok") {
 4867:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4868:                 }
 4869:                 if (!grep(/^cr$/,@rolechanges)) {
 4870:                     push(@rolechanges,'cr');
 4871:                 }
 4872:             }
 4873: 	} elsif ($key=~/^form\.act/) {
 4874:             my $udom = $env{'form.ccdomain'};
 4875:             my $uname = $env{'form.ccuname'};
 4876: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4877:                 # Activate a custom role
 4878: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4879: 		my $url='/'.$one.'/'.$two;
 4880:                 my $id = $url.'_cr/'."$three/$four/$five";
 4881:                 my $role = "cr/$three/$four/$five";
 4882: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4883: 
 4884:                 my $start = ( $env{'form.start_'.$full} ?
 4885:                               $env{'form.start_'.$full} :
 4886:                               $now );
 4887:                 my $end   = ( $env{'form.end_'.$full} ?
 4888:                               $env{'form.end_'.$full} :
 4889:                               0 );
 4890: 
 4891:                 # split multiple sections
 4892:                 my %sections = ();
 4893:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$five);
 4894:                 if ($num_sections == 0) {
 4895:                     unless ($udom eq $one) {
 4896:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4897:                                      $uname,$role,$start,$end,$one,$two,'','',\%process_by,
 4898:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4899:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4900:                     }
 4901:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4902:                 } else {
 4903: 		    my %curr_groups =
 4904: 			&Apache::longroup::coursegroups($one,$two);
 4905:                     my ($restricted,$numchanges);
 4906:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4907:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4908:                             exists($curr_groups{$sec})) {
 4909:                             $disallowed{$sec} = $url;
 4910:                             next;
 4911:                         }
 4912:                         my $securl = $url.'/'.$sec;
 4913:                         my $secid = $securl.'_cr'."/$three/$four/$five";
 4914:                         undef($restricted);
 4915:                         unless ($udom eq $one) {
 4916:                             next if (&Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4917:                                          $uname,$role,$start,$end,$one,$two,$sec,'',\%process_by,
 4918:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4919:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4920:                         }
 4921:                         $numchanges ++;
 4922: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4923:                     }
 4924:                     next unless ($numchanges);
 4925:                 }
 4926:                 if (!grep(/^cr$/,@rolechanges)) {
 4927:                     push(@rolechanges,'cr');
 4928:                 }
 4929: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4930: 		# Activate roles for sections with 3 id numbers
 4931: 		# set start, end times, and the url for the class
 4932: 		my ($one,$two,$three)=($1,$2,$3);
 4933: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ?
 4934: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} :
 4935: 			      $now );
 4936: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ?
 4937: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4938: 			      0 );
 4939: 		my $url='/'.$one.'/'.$two;
 4940:                 my $id = $url.'_'.$three;
 4941:                 # split multiple sections
 4942:                 my %sections = ();
 4943:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4944:                 my ($credits,$numchanges);
 4945:                 if ($three eq 'st') {
 4946:                     if ($showcredits) {
 4947:                         my $defaultcredits = 
 4948:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4949:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4950:                         $credits =~ s/[^\d\.]//g;
 4951:                         if ($credits eq $defaultcredits) {
 4952:                             undef($credits);
 4953:                         }
 4954:                     }
 4955:                 }
 4956:                 if ($num_sections == 0) {
 4957:                     unless ($udom eq $one) {
 4958:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4959:                                      $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4960:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4961:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4962:                     }
 4963:                     $numchanges ++;
 4964:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4965:                 } else {
 4966:                     my %curr_groups = 
 4967: 			&Apache::longroup::coursegroups($one,$two);
 4968:                     my $emptysec = 0;
 4969:                     my $restricted;
 4970:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4971:                         $sec =~ s/\W//g;
 4972:                         if ($sec ne '') {
 4973:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4974:                                 exists($curr_groups{$sec})) {
 4975:                                 $disallowed{$sec} = $url;
 4976:                                 next;
 4977:                             }
 4978:                             my $securl = $url.'/'.$sec;
 4979:                             my $secid = $securl.'_'.$three;
 4980:                             unless ($udom eq $one) {
 4981:                                 undef($restricted);
 4982:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4983:                                                   $uname,$three,$start,$end,$one,$two,$sec,$credits,\%process_by,
 4984:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4985:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4986:                                 next if ($restricted);
 4987:                             }
 4988:                             $numchanges ++;
 4989:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4990:                         } else {
 4991:                             $emptysec = 1;
 4992:                         }
 4993:                     }
 4994:                     if ($emptysec) {
 4995:                         unless ($udom eq $one) {
 4996:                             undef($restricted);
 4997:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4998:                                               $uname,$three,$start,$end,$one,$two,'',$credits,\%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,$three,$start,$end,$one,$two,'',$context,$credits));
 5005:                     }
 5006:                     next unless ($numchanges);
 5007:                 }
 5008:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 5009:                     push(@rolechanges,$three);
 5010:                 }
 5011: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 5012: 		# Activate roles for sections with two id numbers
 5013: 		# set start, end times, and the url for the class
 5014: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ?
 5015: 			      $env{'form.start_'.$1.'_'.$2} :
 5016: 			      $now );
 5017: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ?
 5018: 			      $env{'form.end_'.$1.'_'.$2} :
 5019: 			      0 );
 5020:                 my $one = $1;
 5021:                 my $two = $2;
 5022: 		my $url='/'.$one.'/';
 5023:                 my $id = $url.'_'.$two;
 5024:                 my ($cdom,$cnum) = split(/\//,$one);
 5025:                 # split multiple sections
 5026:                 my %sections = ();
 5027:                 my ($restricted,$numchanges);
 5028:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 5029:                 if ($num_sections == 0) {
 5030:                     unless ($udom eq $one) {
 5031:                         $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 5032:                                           $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 5033:                                           \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 5034:                                           \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 5035:                         next if ($restricted);
 5036:                     }
 5037:                     $numchanges ++;
 5038:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 5039:                 } else {
 5040:                     my $emptysec = 0;
 5041:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 5042:                         if ($sec ne '') {
 5043:                             my $securl = $url.'/'.$sec;
 5044:                             my $secid = $securl.'_'.$two;
 5045:                             unless ($udom eq $one) {
 5046:                                 undef($restricted);
 5047:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 5048:                                                   $uname,$two,$start,$end,$cdom,$cnum,$sec,'',\%process_by,
 5049:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 5050:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 5051:                                 next if ($restricted);
 5052:                             }
 5053:                             $numchanges ++;
 5054:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 5055:                         } else {
 5056:                             $emptysec = 1;
 5057:                         }
 5058:                     }
 5059:                     if ($emptysec) {
 5060:                         unless ($udom eq $one) {
 5061:                             undef($restricted);
 5062:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 5063:                                               $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 5064:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 5065:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 5066:                             next if ($restricted);
 5067:                         }
 5068:                         $numchanges ++;
 5069:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 5070:                     }
 5071:                     next unless ($numchanges); 
 5072:                 }
 5073:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 5074:                     push(@rolechanges,$two);
 5075:                 }
 5076: 	    } else {
 5077: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 5078:             }
 5079:             foreach my $key (sort(keys(%disallowed))) {
 5080:                 $r->print('<p class="LC_warning">');
 5081:                 if (($key eq 'none') || ($key eq 'all')) {  
 5082:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 5083:                 } else {
 5084:                     $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>'));
 5085:                 }
 5086:                 $r->print('</p><p>'
 5087:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 5088:                              ,'<a href="javascript:history.go(-1)'
 5089:                              ,'</a>')
 5090:                          .'</p><br />'
 5091:                 );
 5092:             }
 5093: 	}
 5094:     } # End of foreach (keys(%env))
 5095:     if ((keys(%reject)) || (keys(%unauthorized))) {
 5096:         $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5097:     }
 5098:     if ((keys(%pending)) || (keys(%currqueued))) {
 5099:         $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5100:     }
 5101: # Flush the course logs so reverse user roles immediately updated
 5102:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5103:     if (@rolechanges == 0) {
 5104:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 5105:     }
 5106:     return @rolechanges;
 5107: }
 5108: 
 5109: sub get_user_credits {
 5110:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 5111:     if ($cdom eq '' || $cnum eq '') {
 5112:         return unless ($env{'request.course.id'});
 5113:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5114:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5115:     }
 5116:     my $credits;
 5117:     my %currhash =
 5118:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 5119:     if (keys(%currhash) > 0) {
 5120:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 5121:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 5122:         $credits = $items[$crdidx];
 5123:         $credits =~ s/[^\d\.]//g;
 5124:     }
 5125:     if ($credits eq $defaultcredits) {
 5126:         undef($credits);
 5127:     }
 5128:     return $credits;
 5129: }
 5130: 
 5131: sub enroll_single_student {
 5132:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 5133:         $showcredits,$defaultcredits) = @_;
 5134:     $r->print('<h3>');
 5135:     if ($crstype eq 'Community') {
 5136:         $r->print(&mt('Enrolling Member'));
 5137:     } else {
 5138:         $r->print(&mt('Enrolling Student'));
 5139:     }
 5140:     $r->print('</h3>');
 5141: 
 5142:     # Remove non alphanumeric values from section
 5143:     $env{'form.sections'}=~s/\W//g;
 5144: 
 5145:     my $credits;
 5146:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 5147:         $credits = $env{'form.credits'};
 5148:         $credits =~ s/[^\d\.]//g;
 5149:         if ($credits ne '') {
 5150:             if ($credits eq $defaultcredits) {
 5151:                 undef($credits);
 5152:             }
 5153:         }
 5154:     }
 5155:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 5156:     my (%got_role_approvals,%got_instdoms,%process_by,%instdoms,%pending,%reject,%notifydc,
 5157:         %status,%unauthorized,%currqueued);
 5158:     unless ($env{'form.ccdomain'} eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 5159:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5160:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5161:         my $csec = $env{'form.sections'};
 5162:         my $id = "/$cdom/$cnum";
 5163:         if ($csec ne '') {
 5164:             $id .= "/$csec";
 5165:         }
 5166:         $id .= '_st';
 5167:         if (&Apache::lonuserutils::restricted_dom($context,$id,$env{'form.ccdomain'},$env{'form.ccuname'},
 5168:                                                   'st',$startdate,$enddate,$cdom,$cnum,$csec,$credits,
 5169:                                                   \%process_by,\%instdoms,\%got_role_approvals,\%got_instdoms,
 5170:                                                   \%reject,\%pending,\%notifydc,\%status,\%unauthorized,\%currqueued)) {
 5171:             if ((keys(%reject)) || (keys(%unauthorized))) {
 5172:                 $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5173:             }
 5174:             if ((keys(%pending)) || (keys(%currqueued))) {
 5175:                 $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5176:             }
 5177:             return;
 5178:         }
 5179:     }
 5180: 
 5181:     # Clean out any old student roles the user has in this class.
 5182:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 5183:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 5184:     my $enroll_result =
 5185:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 5186:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 5187:             $env{'form.cmiddlename'},$env{'form.clastname'},
 5188:             $env{'form.generation'},$env{'form.sections'},$enddate,
 5189:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 5190:             $credits);
 5191:     if ($enroll_result =~ /^ok/) {
 5192:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 5193:         if ($env{'form.sections'} ne '') {
 5194:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 5195:         }
 5196:         my ($showstart,$showend);
 5197:         if ($startdate <= $now) {
 5198:             $showstart = &mt('Access starts immediately');
 5199:         } else {
 5200:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 5201:         }
 5202:         if ($enddate == 0) {
 5203:             $showend = &mt('ends: no ending date');
 5204:         } else {
 5205:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 5206:         }
 5207:         $r->print('.<br />'.$showstart.'; '.$showend);
 5208:         if ($startdate <= $now && !$newuser) {
 5209:             $r->print('<p class="LC_info">');
 5210:             if ($crstype eq 'Community') {
 5211:                 $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.'));
 5212:             } else {
 5213:                 $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.'));
 5214:            }
 5215:            $r->print('</p>');
 5216:         }
 5217:     } else {
 5218:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 5219:     }
 5220:     return;
 5221: }
 5222: 
 5223: sub get_defaultquota_text {
 5224:     my ($settingstatus) = @_;
 5225:     my $defquotatext; 
 5226:     if ($settingstatus eq '') {
 5227:         $defquotatext = &mt('default');
 5228:     } else {
 5229:         my ($usertypes,$order) =
 5230:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 5231:         if ($usertypes->{$settingstatus} eq '') {
 5232:             $defquotatext = &mt('default');
 5233:         } else {
 5234:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 5235:         }
 5236:     }
 5237:     return $defquotatext;
 5238: }
 5239: 
 5240: sub update_result_form {
 5241:     my ($uhome) = @_;
 5242:     my $outcome = 
 5243:     '<form name="userupdate" method="post" action="">'."\n";
 5244:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 5245:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5246:     }
 5247:     if ($env{'form.origname'} ne '') {
 5248:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 5249:     }
 5250:     foreach my $item ('sortby','seluname','seludom') {
 5251:         if (exists($env{'form.'.$item})) {
 5252:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5253:         }
 5254:     }
 5255:     if ($uhome eq 'no_host') {
 5256:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 5257:     }
 5258:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 5259:                 '<input type="hidden" name="currstate" value="" />'."\n".
 5260:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5261:                 '</form>';
 5262:     return $outcome;
 5263: }
 5264: 
 5265: sub quota_admin {
 5266:     my ($setquota,$changeHash,$name) = @_;
 5267:     my $quotachanged;
 5268:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 5269:         # Current user has quota modification privileges
 5270:         if (ref($changeHash) eq 'HASH') {
 5271:             $quotachanged = 1;
 5272:             $changeHash->{$name.'quota'} = $setquota;
 5273:         }
 5274:     }
 5275:     return $quotachanged;
 5276: }
 5277: 
 5278: sub tool_admin {
 5279:     my ($tool,$settool,$changeHash,$context) = @_;
 5280:     my $canchange = 0; 
 5281:     if ($context eq 'requestcourses') {
 5282:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 5283:             $canchange = 1;
 5284:         }
 5285:     } elsif ($context eq 'reqcrsotherdom') {
 5286:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 5287:             $canchange = 1;
 5288:         }
 5289:     } elsif ($context eq 'requestauthor') {
 5290:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5291:             $canchange = 1;
 5292:         }
 5293:     } elsif ($context eq 'authordefaults') {
 5294:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5295:             $canchange = 1;
 5296:         }
 5297:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 5298:         # Current user has quota modification privileges
 5299:         $canchange = 1;
 5300:     }
 5301:     my $toolchanged;
 5302:     if ($canchange) {
 5303:         if (ref($changeHash) eq 'HASH') {
 5304:             $toolchanged = 1;
 5305:             if ($tool eq 'requestauthor') {
 5306:                 $changeHash->{$context} = $settool;
 5307:             } elsif (($tool eq 'managers') || ($tool eq 'editors') || ($tool eq 'archive')) {
 5308:                 $changeHash->{'author'.$tool} = $settool;
 5309:             } elsif ($tool eq 'webdav') {
 5310:                 $changeHash->{'tools.'.$tool} = $settool;
 5311:             } else {
 5312:                 $changeHash->{$context.'.'.$tool} = $settool;
 5313:             }
 5314:         }
 5315:     }
 5316:     return $toolchanged;
 5317: }
 5318: 
 5319: sub build_roles {
 5320:     my ($sectionstr,$sections,$role) = @_;
 5321:     my $num_sections = 0;
 5322:     if ($sectionstr=~ /,/) {
 5323:         my @secnums = split/,/,$sectionstr;
 5324:         if ($role eq 'st') {
 5325:             $secnums[0] =~ s/\W//g;
 5326:             $$sections{$secnums[0]} = 1;
 5327:             $num_sections = 1;
 5328:         } else {
 5329:             foreach my $sec (@secnums) {
 5330:                 $sec =~ ~s/\W//g;
 5331:                 if (!($sec eq "")) {
 5332:                     if (exists($$sections{$sec})) {
 5333:                         $$sections{$sec} ++;
 5334:                     } else {
 5335:                         $$sections{$sec} = 1;
 5336:                         $num_sections ++;
 5337:                     }
 5338:                 }
 5339:             }
 5340:         }
 5341:     } else {
 5342:         $sectionstr=~s/\W//g;
 5343:         unless ($sectionstr eq '') {
 5344:             $$sections{$sectionstr} = 1;
 5345:             $num_sections ++;
 5346:         }
 5347:     }
 5348: 
 5349:     return $num_sections;
 5350: }
 5351: 
 5352: # ========================================================== Custom Role Editor
 5353: 
 5354: sub custom_role_editor {
 5355:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5356:     my $action = $env{'form.customroleaction'};
 5357:     my ($rolename,$helpitem);
 5358:     if ($action eq 'new') {
 5359:         $rolename=$env{'form.newrolename'};
 5360:     } else {
 5361:         $rolename=$env{'form.rolename'};
 5362:     }
 5363: 
 5364:     my ($crstype,$context);
 5365:     if ($env{'request.course.id'}) {
 5366:         $crstype = &Apache::loncommon::course_type();
 5367:         $context = 'course';
 5368:         $helpitem = 'Course_Editing_Custom_Roles';
 5369:     } else {
 5370:         $context = 'domain';
 5371:         $crstype = 'course';
 5372:         $helpitem = 'Domain_Editing_Custom_Roles';
 5373:     }
 5374: 
 5375:     $rolename=~s/[^A-Za-z0-9]//gs;
 5376:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 5377: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 5378:                                    $permission);
 5379:         return;
 5380:     }
 5381: 
 5382:     my $formname = 'form1';
 5383:     my %privs=();
 5384:     my $body_top = '<h2>';
 5385: # ------------------------------------------------------- Does this role exist?
 5386:     my ($rdummy,$roledef)=
 5387: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5388:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5389:         $body_top .= &mt('Existing Role').' "';
 5390: # ------------------------------------------------- Get current role privileges
 5391:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 5392:         if ($privs{'system'} =~ /bre\&S/) {
 5393:             if ($context eq 'domain') {
 5394:                 $crstype = 'Course';
 5395:             } elsif ($crstype eq 'Community') {
 5396:                 $privs{'system'} =~ s/bre\&S//;
 5397:             }
 5398:         } elsif ($context eq 'domain') {
 5399:             $crstype = 'Course';
 5400:         }
 5401:     } else {
 5402:         $body_top .= &mt('New Role').' "';
 5403:         $roledef='';
 5404:     }
 5405:     $body_top .= $rolename.'"</h2>';
 5406: 
 5407: # ------------------------------------------------------- What can be assigned?
 5408:     my %full=();
 5409:     my %levels=(
 5410:                  course => {},
 5411:                  domain => {},
 5412:                  system => {},
 5413:                );
 5414:     my %levelscurrent=(
 5415:                         course => {},
 5416:                         domain => {},
 5417:                         system => {},
 5418:                       );
 5419:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5420:     my ($jsback,$elements) = &crumb_utilities();
 5421:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5422:     my $head_script =
 5423:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 5424:                                                   \%full,\@templateroles,$jsback);
 5425:     push (@{$brcrum},
 5426:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 5427:                text => "Pick custom role",
 5428:                faq  => 282,bug=>'Instructor Interface',},
 5429:               {href => "javascript:backPage(document.$formname,'','')",
 5430:                text => "Edit custom role",
 5431:                faq  => 282,
 5432:                bug  => 'Instructor Interface',
 5433:                help => $helpitem}
 5434:               );
 5435:     my $args = { bread_crumbs          => $brcrum,
 5436:                  bread_crumbs_component => 'User Management'};
 5437:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 5438:                                              $head_script,$args).
 5439:               $body_top);
 5440:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 5441:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 5442:                                                         \@templateroles,$prefix));
 5443: 
 5444:     $r->print(<<ENDCCF);
 5445: <input type="hidden" name="phase" value="set_custom_roles" />
 5446: <input type="hidden" name="rolename" value="$rolename" />
 5447: ENDCCF
 5448:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5449:                                                        \%levelscurrent,$prefix));
 5450:     $r->print(&Apache::loncommon::end_data_table().
 5451:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 5452:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 5453:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 5454:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 5455:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 5456: }
 5457: 
 5458: # ---------------------------------------------------------- Call to definerole
 5459: sub set_custom_role {
 5460:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5461:     my $rolename=$env{'form.rolename'};
 5462:     $rolename=~s/[^A-Za-z0-9]//gs;
 5463:     if (!$rolename) {
 5464: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5465:         return;
 5466:     }
 5467:     my ($jsback,$elements) = &crumb_utilities();
 5468:     my $jscript = '<script type="text/javascript">'
 5469:                  .'// <![CDATA['."\n"
 5470:                  .$jsback."\n"
 5471:                  .'// ]]>'."\n"
 5472:                  .'</script>'."\n";
 5473:     my $helpitem = 'Course_Editing_Custom_Roles';
 5474:     if ($context eq 'domain') {
 5475:         $helpitem = 'Domain_Editing_Custom_Roles';
 5476:     }
 5477:     push(@{$brcrum},
 5478:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 5479:          text => "Pick custom role",
 5480:          faq  => 282,
 5481:          bug  => 'Instructor Interface',},
 5482:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 5483:          text => "Edit custom role",
 5484:          faq  => 282,
 5485:          bug  => 'Instructor Interface',},
 5486:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 5487:          text => "Result",
 5488:          faq  => 282,
 5489:          bug  => 'Instructor Interface',
 5490:          help => $helpitem,}
 5491:         );
 5492:     my $args = { bread_crumbs           => $brcrum,
 5493:                  bread_crumbs_component => 'User Management'};
 5494:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 5495: 
 5496:     my $newrole;
 5497:     my ($rdummy,$roledef)=
 5498: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5499: 
 5500: # ------------------------------------------------------- Does this role exist?
 5501:     $r->print('<h3>');
 5502:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5503: 	$r->print(&mt('Existing Role').' "');
 5504:     } else {
 5505: 	$r->print(&mt('New Role').' "');
 5506: 	$roledef='';
 5507:         $newrole = 1;
 5508:     }
 5509:     $r->print($rolename.'"</h3>');
 5510: # ------------------------------------------------- Assign role and show result
 5511: 
 5512:     my $errmsg;
 5513:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 5514:     # Assign role and return result
 5515:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 5516:                                              $newprivs{'c'});
 5517:     if ($result ne 'ok') {
 5518:         $errmsg = ': '.$result;
 5519:     }
 5520:     my $message =
 5521:         &Apache::lonhtmlcommon::confirm_success(
 5522:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 5523:     if ($env{'request.course.id'}) {
 5524:         my $url='/'.$env{'request.course.id'};
 5525:         $url=~s/\_/\//g;
 5526:         $result =
 5527:             &Apache::lonnet::assigncustomrole(
 5528:                 $env{'user.domain'},$env{'user.name'},
 5529:                 $url,
 5530:                 $env{'user.domain'},$env{'user.name'},
 5531:                 $rolename,undef,undef,undef,$context);
 5532:         if ($result ne 'ok') {
 5533:             $errmsg = ': '.$result;
 5534:         }
 5535:         $message .=
 5536:             '<br />'
 5537:            .&Apache::lonhtmlcommon::confirm_success(
 5538:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 5539:     }
 5540:     $r->print(
 5541:         &Apache::loncommon::confirmwrapper($message)
 5542:        .'<br />'
 5543:        .&Apache::lonhtmlcommon::actionbox([
 5544:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 5545:            .&mt('Create or edit another custom role')
 5546:            .'</a>'])
 5547:        .'<form name="customresult" method="post" action="">'
 5548:        .&Apache::lonhtmlcommon::echo_form_input([])
 5549:        .'</form>'
 5550:     );
 5551: }
 5552: 
 5553: sub show_role_requests {
 5554:     my ($caller,$dom) = @_;
 5555:     my $showrolereqs;
 5556:     my %domconfig = &Apache::lonnet::get_dom('configuration',['privacy'],$dom);
 5557:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 5558:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 5559:             my %approvalconf = %{$domconfig{'privacy'}{'approval'}};
 5560:             foreach my $key ('instdom','extdom') {
 5561:                 if (ref($approvalconf{$key}) eq 'HASH') {
 5562:                     if (keys(%{$approvalconf{$key}})) {
 5563:                         foreach my $context ('domain','author','course','community') {
 5564:                             if ($approvalconf{$key}{$context} eq $caller) {
 5565:                                 $showrolereqs = 1;
 5566:                                 last if ($showrolereqs);
 5567:                             }
 5568:                         }
 5569:                     }
 5570:                 }
 5571:                 last if ($showrolereqs);
 5572:             }
 5573:         }
 5574:     }
 5575:     return $showrolereqs;
 5576: }
 5577: 
 5578: sub display_coauthor_managers {
 5579:     my ($permission) = @_;
 5580:     my $output;
 5581:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5582:         $output = '<form action="/adm/createuser" method="post" name="camanagers">'.
 5583:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5584:                   '<p>';
 5585:         my (@possmanagers,@custommanagers);
 5586:         my %userenv =
 5587:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5588:                                              $env{'user.name'},
 5589:                                              'authormanagers');
 5590:         my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5591:                                                      ['active','future'],['ca']);
 5592:         if (keys(%ca_roles)) {
 5593:             foreach my $entry (sort(keys(%ca_roles))) {
 5594:                 if ($entry =~ /^($match_username\:$match_domain):ca$/) {
 5595:                     my $user = $1;
 5596:                     unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5597:                         push(@possmanagers,$user);
 5598:                     }
 5599:                 }
 5600:             }
 5601:         }
 5602:         if ($userenv{'authormanagers'} eq '') {
 5603:             $output .= &mt('Currently author manages co-author roles');
 5604:         } else {
 5605:             if (keys(%ca_roles)) {
 5606:                 foreach my $user (split(/,/,$userenv{'authormanagers'})) {
 5607:                     if ($user =~ /^($match_username)\:($match_domain)$/) {
 5608:                         if (exists($ca_roles{$user.':ca'})) {
 5609:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5610:                                 push(@custommanagers,$user);
 5611:                             }
 5612:                         }
 5613:                     }
 5614:                 }
 5615:             }
 5616:             if (@custommanagers) {
 5617:                 $output .= &mt('Co-authors with active or future roles who currently manage co-author roles: [_1]',
 5618:                               '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @custommanagers));
 5619:             } else {
 5620:                 $output .= &mt('Currently author manages co-author roles');
 5621:             }
 5622:         }
 5623:         $output .= "</p>\n";
 5624:         if (@possmanagers) {
 5625:             $output .= '<p>'.&mt('If checked, can manage').': ';
 5626:             foreach my $user (@possmanagers) {
 5627:                  my $checked;
 5628:                  if (grep(/^\Q$user\E$/,@custommanagers)) {
 5629:                      $checked = ' checked="checked"';
 5630:                  }
 5631:                  $output .= '<span style="LC_nobreak"><label>'.
 5632:                             '<input type="checkbox" name="custommanagers" '.
 5633:                             'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
 5634:                             &Apache::loncommon::plainname(split(/:/,$user))." ($user)".'</label></span> '."\n";
 5635:             }
 5636:             $output .= '<input type="hidden" name="state" value="process" /></p>'."\n".
 5637:                        '<p><input type="submit" value="'.&mt('Save changes').'" /></p>'."\n";
 5638:         } else {
 5639:             $output .= '<p>'.&mt('No co-author roles assignable as manager').'</p>';
 5640:         }
 5641:         $output .= '</form>';
 5642:     } else {
 5643:         $output = '<span class="LC_warning">'.
 5644:                   &mt('You do not have permission to perform this action').
 5645:                   '</span>';
 5646:     }
 5647:     return $output;
 5648: }
 5649: 
 5650: sub update_coauthor_managers {
 5651:     my ($permission) = @_;
 5652:     my $output;
 5653:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5654:         my ($current,$newval,@possibles,@managers);
 5655:         my %userenv =
 5656:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5657:                                              $env{'user.name'},
 5658:                                              'authormanagers');
 5659:         $current = $userenv{'authormanagers'};
 5660:         @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 5661:         if (@possibles) {
 5662:             my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5663:                                                          ['active','future'],['ca']);
 5664:             if (keys(%ca_roles)) {
 5665:                 foreach my $user (@possibles) {
 5666:                     if ($user =~ /^($match_username):($match_domain)$/) {
 5667:                         if (exists($ca_roles{$user.':ca'})) {
 5668:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5669:                                 push(@managers,$user);
 5670:                             }
 5671:                         }
 5672:                     }
 5673:                 }
 5674:                 if (@managers) {
 5675:                     $newval = join(',',sort(@managers));
 5676:                 }
 5677:             }
 5678:         }
 5679:         if ($current eq $newval) {
 5680:             $output = &mt('No changes made to management of co-author roles');
 5681:         } else {
 5682:             my $chgresult =
 5683:                 &Apache::lonnet::put('environment',{'authormanagers' => $newval},
 5684:                                      $env{'user.domain'},$env{'user.name'});
 5685:             if ($chgresult eq 'ok') {
 5686:                 &Apache::lonnet::appenv({'environment.authormanagers' => $newval});
 5687:                 my (@adds,@dels);
 5688:                 if ($newval eq '') {
 5689:                     @dels = split(/,/,$current);
 5690:                 } elsif ($current eq '') {
 5691:                     @adds = @managers;
 5692:                 } else {
 5693:                     my @old = split(/,/,$current);
 5694:                     my @diffs = &Apache::loncommon::compare_arrays(\@old,\@managers);
 5695:                     if (@diffs) {
 5696:                         foreach my $user (@diffs) {
 5697:                             if (grep(/^\Q$user\E$/,@old)) {
 5698:                                 push(@dels,$user);
 5699:                             } elsif (grep(/^\Q$user\E$/,@managers)) {
 5700:                                 push(@adds,$user);
 5701:                             }
 5702:                         }
 5703:                     }
 5704:                 }
 5705:                 my $key = "internal.manager./$env{'user.domain'}/$env{'user.name'}";
 5706:                 if (@dels) {
 5707:                     foreach my $user (@dels) {
 5708:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5709:                             &Apache::lonnet::del('environment',[$key],$2,$1);
 5710:                         }
 5711:                     }
 5712:                 }
 5713:                 if (@adds) {
 5714:                     foreach my $user (@adds) {
 5715:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5716:                             &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 5717:                         }
 5718:                     }
 5719:                 }
 5720:                 if ($newval eq '') {
 5721:                     $output = &mt('Management of co-authors set to be author-only');
 5722:                 } else {
 5723:                     $output .= &mt('Co-authors who can manage co-author roles set to: [_1]',
 5724:                                    '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @managers));
 5725:                 }
 5726:             }
 5727:         }
 5728:     } else {
 5729:         $output = '<span class="LC_warning">'.
 5730:                   &mt('You do not have permission to perform this action').
 5731:                   '</span>';
 5732:     }
 5733:     return $output;
 5734: }
 5735: 
 5736: # ================================================================ Main Handler
 5737: sub handler {
 5738:     my $r = shift;
 5739:     if ($r->header_only) {
 5740:        &Apache::loncommon::content_type($r,'text/html');
 5741:        $r->send_http_header;
 5742:        return OK;
 5743:     }
 5744:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 5745: 
 5746:     if ($env{'request.course.id'}) {
 5747:         $context = 'course';
 5748:         $crstype = &Apache::loncommon::course_type();
 5749:     } elsif ($env{'request.role'} =~ /^au\./) {
 5750:         $context = 'author';
 5751:     } elsif ($env{'request.role'} =~ m{^(ca|aa)\./$match_domain/$match_username$}) {
 5752:         $context = 'coauthor';
 5753:     } else {
 5754:         $context = 'domain';
 5755:     }
 5756: 
 5757:     my ($permission,$allowed) =
 5758:         &Apache::lonuserutils::get_permission($context,$crstype);
 5759:     if (($context eq 'coauthor') && ($allowed)) {
 5760:         $context = 'author';
 5761:     }
 5762: 
 5763:     if ($allowed) {
 5764:         my @allhelp;
 5765:         if ($context eq 'course') {
 5766:             $cid = $env{'request.course.id'};
 5767:             $cdom = $env{'course.'.$cid.'.domain'};
 5768:             $cnum = $env{'course.'.$cid.'.num'};
 5769: 
 5770:             if ($permission->{'cusr'}) {
 5771:                 push(@allhelp,'Course_Create_Class_List');
 5772:             }
 5773:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5774:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 5775:             }
 5776:             if ($permission->{'custom'}) {
 5777:                 push(@allhelp,'Course_Editing_Custom_Roles');
 5778:             }
 5779:             if ($permission->{'cusr'}) {
 5780:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 5781:             }
 5782:             unless ($permission->{'cusr_section'}) {
 5783:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 5784:                     push(@allhelp,'Course_Automated_Enrollment');
 5785:                 }
 5786:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 5787:                     push(@allhelp,'Course_Approve_Selfenroll');
 5788:                 }
 5789:             }
 5790:             if ($permission->{'grp_manage'}) {
 5791:                 push(@allhelp,'Course_Manage_Group');
 5792:             }
 5793:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5794:                 push(@allhelp,'Course_User_Logs');
 5795:             }
 5796:         } elsif ($context eq 'author') {
 5797:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5798:                            'Author_View_Coauthor_List','Author_User_Logs'));
 5799:         } elsif ($context eq 'coauthor') {
 5800:             if ($permission->{'cusr'}) {
 5801:                 push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5802:                                'Author_View_Coauthor_List','Author_User_Logs'));
 5803:             } elsif ($permission->{'view'}) {
 5804:                 push(@allhelp,'Author_View_Coauthor_List');
 5805:             }
 5806:         } else {
 5807:             if ($permission->{'cusr'}) {
 5808:                 push(@allhelp,'Domain_Change_Privileges');
 5809:                 if ($permission->{'activity'}) {
 5810:                     push(@allhelp,'Domain_User_Access_Logs');
 5811:                 }
 5812:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 5813:                 if ($permission->{'custom'}) {
 5814:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 5815:                 }
 5816:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 5817:             } elsif ($permission->{'view'}) {
 5818:                 push(@allhelp,'Domain_View_Privileges');
 5819:                 if ($permission->{'activity'}) {
 5820:                     push(@allhelp,'Domain_User_Access_Logs');
 5821:                 }
 5822:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 5823:             }
 5824:         }
 5825:         if (@allhelp) {
 5826:             $allhelpitems = join(',',@allhelp);
 5827:         }
 5828:     }
 5829: 
 5830:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5831:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 5832:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue',
 5833:          'forceedit']);
 5834:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5835:     my $args;
 5836:     my $brcrum = [];
 5837:     my $bread_crumbs_component = 'User Management';
 5838:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 5839:         $brcrum = [{href=>"/adm/createuser",
 5840:                     text=>"User Management",
 5841:                     help=>$allhelpitems}
 5842:                   ];
 5843:     }
 5844:     if (!$allowed) {
 5845:         if ($context eq 'course') {
 5846:             $r->internal_redirect('/adm/viewclasslist');
 5847:             return OK;
 5848:         } elsif ($context eq 'coauthor') {
 5849:             $r->internal_redirect('/adm/viewcoauthors');
 5850:             return OK;
 5851:         }
 5852:         $env{'user.error.msg'}=
 5853:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 5854:                                  "or view user status.";
 5855:         return HTTP_NOT_ACCEPTABLE;
 5856:     }
 5857: 
 5858:     &Apache::loncommon::content_type($r,'text/html');
 5859:     $r->send_http_header;
 5860: 
 5861:     my $showcredits;
 5862:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 5863:          ($context eq 'domain')) {
 5864:         my %domdefaults = 
 5865:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 5866:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 5867:             $showcredits = 1;
 5868:         }
 5869:     }
 5870: 
 5871:     # Main switch on form.action and form.state, as appropriate
 5872:     if (! exists($env{'form.action'})) {
 5873:         $args = {bread_crumbs => $brcrum,
 5874:                  bread_crumbs_component => $bread_crumbs_component}; 
 5875:         $r->print(&header(undef,$args));
 5876:         $r->print(&print_main_menu($permission,$context,$crstype));
 5877:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 5878:         my $helpitem = 'Course_Create_Class_List';
 5879:         if ($context eq 'author') {
 5880:             $helpitem = 'Author_Create_Coauthor_List';
 5881:         } elsif ($context eq 'domain') {
 5882:             $helpitem = 'Domain_Create_Users';
 5883:         }
 5884:         push(@{$brcrum},
 5885:               { href => '/adm/createuser?action=upload&state=',
 5886:                 text => 'Upload Users List',
 5887:                 help => $helpitem,
 5888:               });
 5889:         $bread_crumbs_component = 'Upload Users List';
 5890:         $args = {bread_crumbs           => $brcrum,
 5891:                  bread_crumbs_component => $bread_crumbs_component};
 5892:         $r->print(&header(undef,$args));
 5893:         $r->print('<form name="studentform" method="post" '.
 5894:                   'enctype="multipart/form-data" '.
 5895:                   ' action="/adm/createuser">'."\n");
 5896:         if (! exists($env{'form.state'})) {
 5897:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5898:         } elsif ($env{'form.state'} eq 'got_file') {
 5899:             my $result = 
 5900:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 5901:                                                                  $permission,
 5902:                                                                  $crstype,$showcredits);
 5903:             if ($result eq 'missingdata') {
 5904:                 delete($env{'form.state'});
 5905:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5906:             }
 5907:         } elsif ($env{'form.state'} eq 'enrolling') {
 5908:             if ($env{'form.datatoken'}) {
 5909:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 5910:                                                                     $permission,
 5911:                                                                     $showcredits);
 5912:                 if ($result eq 'missingdata') {
 5913:                     delete($env{'form.state'});
 5914:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5915:                 } elsif ($result eq 'invalidhome') {
 5916:                     $env{'form.state'} = 'got_file';
 5917:                     delete($env{'form.lcserver'});
 5918:                     my $result =
 5919:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 5920:                                                                          $crstype,$showcredits);
 5921:                     if ($result eq 'missingdata') {
 5922:                         delete($env{'form.state'});
 5923:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5924:                     }
 5925:                 }
 5926:             } else {
 5927:                 delete($env{'form.state'});
 5928:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5929:             }
 5930:         } else {
 5931:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5932:         }
 5933:         $r->print('</form>');
 5934:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 5935:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 5936:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 5937:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 5938:         my $phase = $env{'form.phase'};
 5939:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 5940: 	&Apache::loncreateuser::restore_prev_selections();
 5941: 	my $srch;
 5942: 	foreach my $item (@search) {
 5943: 	    $srch->{$item} = $env{'form.'.$item};
 5944: 	}
 5945:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 5946:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 5947:             if ($env{'form.phase'} eq 'createnewuser') {
 5948:                 my $response;
 5949:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 5950:                     my $response =
 5951:                         '<span class="LC_warning">'
 5952:                        .&mt('You must specify a valid username. Only the following are allowed:'
 5953:                            .' letters numbers - . @')
 5954:                        .'</span>';
 5955:                     $env{'form.phase'} = '';
 5956:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 5957:                                                $crstype,$brcrum,$permission);
 5958:                 } else {
 5959:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 5960:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 5961:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 5962:                                                   $srch,$response,$context,
 5963:                                                   $permission,$crstype,$brcrum,
 5964:                                                   $showcredits);
 5965:                 }
 5966:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 5967:                 my ($currstate,$response,$forcenewuser,$results) = 
 5968:                     &user_search_result($context,$srch);
 5969:                 if ($env{'form.currstate'} eq 'modify') {
 5970:                     $currstate = $env{'form.currstate'};
 5971:                 }
 5972:                 if ($currstate eq 'select') {
 5973:                     &print_user_selection_page($r,$response,$srch,$results,
 5974:                                                \@search,$context,undef,$crstype,
 5975:                                                $brcrum);
 5976:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 5977:                     my ($ccuname,$ccdomain,$uhome);
 5978:                     if (($srch->{'srchby'} eq 'uname') && 
 5979:                         ($srch->{'srchtype'} eq 'exact')) {
 5980:                         $ccuname = $srch->{'srchterm'};
 5981:                         $ccdomain= $srch->{'srchdomain'};
 5982:                     } else {
 5983:                         my @matchedunames = keys(%{$results});
 5984:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 5985:                     }
 5986:                     $ccuname =&LONCAPA::clean_username($ccuname);
 5987:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 5988:                     if ($env{'form.action'} eq 'accesslogs') {
 5989:                         my $uhome;
 5990:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 5991:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 5992:                         }
 5993:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 5994:                             $env{'form.phase'} = '';
 5995:                             undef($forcenewuser);
 5996:                             #if ($response) {
 5997:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 5998:                             #        $response .= '<br /><br />';
 5999:                             #    }
 6000:                             #}
 6001:                             &print_username_entry_form($r,$context,$response,$srch,
 6002:                                                        $forcenewuser,$crstype,$brcrum,
 6003:                                                        $permission);
 6004:                         } else {
 6005:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 6006:                         }
 6007:                     } else {
 6008:                         if ($env{'form.forcenewuser'}) {
 6009:                             $response = '';
 6010:                         }
 6011:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 6012:                                                       $srch,$response,$context,
 6013:                                                       $permission,$crstype,$brcrum);
 6014:                     }
 6015:                 } elsif ($currstate eq 'query') {
 6016:                     &print_user_query_page($r,'createuser',$brcrum);
 6017:                 } else {
 6018:                     $env{'form.phase'} = '';
 6019:                     &print_username_entry_form($r,$context,$response,$srch,
 6020:                                                $forcenewuser,$crstype,$brcrum,
 6021:                                                $permission);
 6022:                 }
 6023:             } elsif ($env{'form.phase'} eq 'userpicked') {
 6024:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 6025:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 6026:                 if ($env{'form.action'} eq 'accesslogs') {
 6027:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 6028:                 } else {
 6029:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 6030:                                                   $context,$permission,$crstype,
 6031:                                                   $brcrum);
 6032:                 }
 6033:             } elsif ($env{'form.action'} eq 'accesslogs') {
 6034:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 6035:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 6036:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 6037:             }
 6038:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 6039:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 6040:         } else {
 6041:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 6042:                                        $brcrum,$permission);
 6043:         }
 6044:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 6045:         my $prefix;
 6046:         if ($env{'form.phase'} eq 'set_custom_roles') {
 6047:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 6048:         } else {
 6049:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 6050:         }
 6051:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 6052:              ($permission->{'cusr'}) && 
 6053:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 6054:         push(@{$brcrum},
 6055:                  {href => '/adm/createuser?action=processauthorreq',
 6056:                   text => 'Authoring Space requests',
 6057:                   help => 'Domain_Role_Approvals'});
 6058:         $bread_crumbs_component = 'Authoring requests';
 6059:         if ($env{'form.state'} eq 'done') {
 6060:             push(@{$brcrum},
 6061:                      {href => '/adm/createuser?action=authorreqqueue',
 6062:                       text => 'Result',
 6063:                       help => 'Domain_Role_Approvals'});
 6064:             $bread_crumbs_component = 'Authoring request result';
 6065:         }
 6066:         $args = { bread_crumbs           => $brcrum,
 6067:                   bread_crumbs_component => $bread_crumbs_component};
 6068:         my $js = &usernamerequest_javascript();
 6069:         $r->print(&header(&add_script($js),$args));
 6070:         if (!exists($env{'form.state'})) {
 6071:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 6072:                                                                             $env{'request.role.domain'}));
 6073:         } elsif ($env{'form.state'} eq 'done') {
 6074:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 6075:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 6076:                                                                          $env{'request.role.domain'}));
 6077:         }
 6078:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 6079:              ($permission->{'cusr'}) &&
 6080:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 6081:         push(@{$brcrum},
 6082:                  {href => '/adm/createuser?action=processusernamereq',
 6083:                   text => 'LON-CAPA account requests',
 6084:                   help => 'Domain_Username_Approvals'});
 6085:         $bread_crumbs_component = 'Account requests';
 6086:         if ($env{'form.state'} eq 'done') {
 6087:             push(@{$brcrum},
 6088:                      {href => '/adm/createuser?action=usernamereqqueue',
 6089:                       text => 'Result',
 6090:                       help => 'Domain_Username_Approvals'});
 6091:             $bread_crumbs_component = 'LON-CAPA account request result';
 6092:         }
 6093:         $args = { bread_crumbs           => $brcrum,
 6094:                   bread_crumbs_component => $bread_crumbs_component};
 6095:         my $js = &usernamerequest_javascript();
 6096:         $r->print(&header(&add_script($js),$args));
 6097:         if (!exists($env{'form.state'})) {
 6098:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 6099:                                                                             $env{'request.role.domain'}));
 6100:         } elsif ($env{'form.state'} eq 'done') {
 6101:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 6102:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 6103:                                                                          $env{'request.role.domain'}));
 6104:         }
 6105:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 6106:              ($permission->{'cusr'})) {
 6107:         my $dom = $env{'form.domain'};
 6108:         my $uname = $env{'form.username'};
 6109:         my $warning;
 6110:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 6111:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 6112:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 6113:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 6114:                     if ($uhome eq 'no_host') {
 6115:                         my $queue = $env{'form.queue'};
 6116:                         my $reqkey = &escape($uname).'_'.$queue; 
 6117:                         my $namespace = 'usernamequeue';
 6118:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 6119:                         my %queued =
 6120:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 6121:                         unless ($queued{$reqkey}) {
 6122:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 6123:                         }
 6124:                     } else {
 6125:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 6126:                     }
 6127:                 } else {
 6128:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 6129:                 }
 6130:             } else {
 6131:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 6132:             }
 6133:         } else {
 6134:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 6135:         }
 6136:         my $args = { only_body => 1 };
 6137:         $r->print(&header(undef,$args).
 6138:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 6139:         if ($warning ne '') {
 6140:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 6141:         } else {
 6142:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 6143:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 6144:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6145:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6146:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 6147:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 6148:                         my %info =
 6149:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 6150:                         if (ref($info{$uname}) eq 'HASH') {
 6151:                             my $usertype = $info{$uname}{'inststatus'};
 6152:                             unless ($usertype) {
 6153:                                 $usertype = 'default';
 6154:                             }
 6155:                             my ($showstatus,$showemail,$pickstart);
 6156:                             my $numextras = 0;
 6157:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6158:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 6159:                                 if (ref($usertypes) eq 'HASH') {
 6160:                                     if ($usertypes->{$usertype}) {
 6161:                                         $showstatus = $usertypes->{$usertype};
 6162:                                     } else {
 6163:                                         $showstatus = $othertitle;
 6164:                                     }
 6165:                                     if ($showstatus) {
 6166:                                         $numextras ++;
 6167:                                     }
 6168:                                 }
 6169:                             }
 6170:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 6171:                                 $showemail = $info{$uname}{'email'};
 6172:                                 $numextras ++;
 6173:                             }
 6174:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 6175:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 6176:                                     $pickstart = 1;
 6177:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6178:                                     my ($num,$count);
 6179:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 6180:                                     $count += $numextras;
 6181:                                     foreach my $field (@{$infofields}) {
 6182:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 6183:                                         next unless ($infotitles->{$field});
 6184:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 6185:                                                   $info{$uname}{$field});
 6186:                                         $num ++;
 6187:                                         unless ($count == $num) {
 6188:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 6189:                                         }
 6190:                                     }
 6191:                                 }
 6192:                             }
 6193:                             if ($numextras) {
 6194:                                 unless ($pickstart) {
 6195:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6196:                                     $pickstart = 1;
 6197:                                 }
 6198:                                 if ($showemail) {
 6199:                                     my $closure = '';
 6200:                                     unless ($showstatus) {
 6201:                                         $closure = 1;
 6202:                                     }
 6203:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 6204:                                               $showemail.
 6205:                                               &Apache::lonhtmlcommon::row_closure($closure));
 6206:                                 }
 6207:                                 if ($showstatus) {
 6208:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 6209:                                               $showstatus.
 6210:                                               &Apache::lonhtmlcommon::row_closure(1));
 6211:                                 }
 6212:                             }
 6213:                             if ($pickstart) { 
 6214:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 6215:                             } else {
 6216:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 6217:                             }
 6218:                         } else {
 6219:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 6220:                         }
 6221:                     }
 6222:                 }
 6223:             }
 6224:         }
 6225:         $r->print(&close_popup_form());
 6226:     } elsif (($env{'form.action'} eq 'listusers') && 
 6227:              ($permission->{'view'} || $permission->{'cusr'})) {
 6228:         my $helpitem = 'Course_View_Class_List';
 6229:         if ($context eq 'author') {
 6230:             $helpitem = 'Author_View_Coauthor_List';
 6231:         } elsif ($context eq 'domain') {
 6232:             $helpitem = 'Domain_View_Users_List';
 6233:         }
 6234:         if ($env{'form.phase'} eq 'bulkchange') {
 6235:             push(@{$brcrum},
 6236:                     {href => '/adm/createuser?action=listusers',
 6237:                      text => "List Users"},
 6238:                     {href => "/adm/createuser",
 6239:                      text => "Result",
 6240:                      help => $helpitem});
 6241:             $bread_crumbs_component = 'Update Users';
 6242:             $args = {bread_crumbs           => $brcrum,
 6243:                      bread_crumbs_component => $bread_crumbs_component};
 6244:             $r->print(&header(undef,$args));
 6245:             my $setting = $env{'form.roletype'};
 6246:             my $choice = $env{'form.bulkaction'};
 6247:             if ($permission->{'cusr'}) {
 6248:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 6249:             } else {
 6250:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 6251:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 6252:             }
 6253:         } else {
 6254:             push(@{$brcrum},
 6255:                     {href => '/adm/createuser?action=listusers',
 6256:                      text => "List Users",
 6257:                      help => $helpitem});
 6258:             $bread_crumbs_component = 'List Users';
 6259:             $args = {bread_crumbs           => $brcrum,
 6260:                      bread_crumbs_component => $bread_crumbs_component};
 6261:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 6262:             my $formname = 'studentform';
 6263:             my $hidecall = "hide_searching();";
 6264:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 6265:                 ($env{'form.roletype'} eq 'community'))) {
 6266:                 if ($env{'form.roletype'} eq 'course') {
 6267:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 6268:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 6269:                                                                 $formname);
 6270:                 } elsif ($env{'form.roletype'} eq 'community') {
 6271:                     $cb_jscript = 
 6272:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 6273:                     my %elements = (
 6274:                                       coursepick => 'radio',
 6275:                                       coursetotal => 'text',
 6276:                                       courselist => 'text',
 6277:                                    );
 6278:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 6279:                 }
 6280:                 $jscript .= &verify_user_display($context)."\n".
 6281:                             &Apache::loncommon::check_uncheck_jscript();
 6282:                 my $js = &add_script($jscript).$cb_jscript;
 6283:                 my $loadcode = 
 6284:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 6285:                 if ($loadcode ne '') {
 6286:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 6287:                 } else {
 6288:                     $args->{add_entries} = {onload => $hidecall};
 6289:                 }
 6290:                 $r->print(&header($js,$args));
 6291:             } else {
 6292:                 $args->{add_entries} = {onload => $hidecall};
 6293:                 $jscript = &verify_user_display($context).
 6294:                            &Apache::loncommon::check_uncheck_jscript(); 
 6295:                 $r->print(&header(&add_script($jscript),$args));
 6296:             }
 6297:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 6298:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 6299:                          $showcredits);
 6300:         }
 6301:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 6302:         my $brtext;
 6303:         if ($crstype eq 'Community') {
 6304:             $brtext = 'Drop Members';
 6305:         } else {
 6306:             $brtext = 'Drop Students';
 6307:         }
 6308:         push(@{$brcrum},
 6309:                 {href => '/adm/createuser?action=drop',
 6310:                  text => $brtext,
 6311:                  help => 'Course_Drop_Student'});
 6312:         if ($env{'form.state'} eq 'done') {
 6313:             push(@{$brcrum},
 6314:                      {href=>'/adm/createuser?action=drop',
 6315:                       text=>"Result"});
 6316:         }
 6317:         $bread_crumbs_component = $brtext;
 6318:         $args = {bread_crumbs           => $brcrum,
 6319:                  bread_crumbs_component => $bread_crumbs_component}; 
 6320:         $r->print(&header(undef,$args));
 6321:         if (!exists($env{'form.state'})) {
 6322:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 6323:         } elsif ($env{'form.state'} eq 'done') {
 6324:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 6325:                                                     $env{'form.action'});
 6326:         }
 6327:     } elsif ($env{'form.action'} eq 'dateselect') {
 6328:         if ($permission->{'cusr'}) {
 6329:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6330:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 6331:                                                                    $crstype,$showcredits));
 6332:         } else {
 6333:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6334:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 6335:         }
 6336:     } elsif ($env{'form.action'} eq 'selfenroll') {
 6337:         my %currsettings;
 6338:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 6339:             %currsettings = (
 6340:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 6341:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 6342:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 6343:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 6344:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 6345:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 6346:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 6347:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 6348:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 6349:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 6350:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 6351:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 6352:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 6353:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 6354:             );
 6355:         }
 6356:         if ($permission->{selfenrolladmin}) {
 6357:             push(@{$brcrum},
 6358:                     {href => '/adm/createuser?action=selfenroll',
 6359:                      text => "Configure Self-enrollment",
 6360:                      help => 'Course_Self_Enrollment'});
 6361:             if (!exists($env{'form.state'})) {
 6362:                 $args = { bread_crumbs           => $brcrum,
 6363:                           bread_crumbs_component => 'Configure Self-enrollment'};
 6364:                 $r->print(&header(undef,$args));
 6365:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6366:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 6367:             } elsif ($env{'form.state'} eq 'done') {
 6368:                 push (@{$brcrum},
 6369:                           {href=>'/adm/createuser?action=selfenroll',
 6370:                            text=>"Result"});
 6371:                 $args = { bread_crumbs           => $brcrum,
 6372:                           bread_crumbs_component => 'Self-enrollment result'};
 6373:                 $r->print(&header(undef,$args));
 6374:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6375:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 6376:             }
 6377:         } elsif ($permission->{selfenrollview}) {
 6378:             push(@{$brcrum},
 6379:                     {href => '/adm/createuser?action=selfenroll',
 6380:                      text => "View Self-enrollment configuration",
 6381:                      help => 'Course_Self_Enrollment'});
 6382:             $args = { bread_crumbs           => $brcrum,
 6383:                       bread_crumbs_component => 'Self-enrollment Settings'};
 6384:             $r->print(&header(undef,$args));
 6385:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6386:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 6387:         } else {
 6388:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6389:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 6390:         }
 6391:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 6392:         if ($permission->{selfenrolladmin}) {
 6393:             push(@{$brcrum},
 6394:                      {href => '/adm/createuser?action=selfenrollqueue',
 6395:                       text => 'Enrollment requests',
 6396:                       help => 'Course_Approve_Selfenroll'});
 6397:             $bread_crumbs_component = 'Enrollment requests';
 6398:             if ($env{'form.state'} eq 'done') {
 6399:                 push(@{$brcrum},
 6400:                          {href => '/adm/createuser?action=selfenrollqueue',
 6401:                           text => 'Result',
 6402:                           help => 'Course_Approve_Selfenroll'});
 6403:                 $bread_crumbs_component = 'Enrollment result';
 6404:             }
 6405:             $args = { bread_crumbs           => $brcrum,
 6406:                       bread_crumbs_component => $bread_crumbs_component};
 6407:             $r->print(&header(undef,$args));
 6408:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6409:             if (!exists($env{'form.state'})) {
 6410:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 6411:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 6412:                                                                                 $cdom,$cnum));
 6413:             } elsif ($env{'form.state'} eq 'done') {
 6414:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 6415:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 6416:                               $cdom,$cnum,$coursedesc));
 6417:             }
 6418:         } else {
 6419:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6420:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 6421:         }
 6422:     } elsif ($env{'form.action'} eq 'changelogs') {
 6423:         if ($permission->{cusr} || $permission->{view}) {
 6424:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 6425:         } else {
 6426:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6427:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 6428:         }
 6429:     } elsif ($env{'form.action'} eq 'helpdesk') {
 6430:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6431:             ($permission->{'cusr'} || $permission->{'view'})) {
 6432:             if ($env{'form.state'} eq 'process') {
 6433:                 if ($permission->{'owner'}) {
 6434:                     &update_helpdeskaccess($r,$permission,$brcrum);
 6435:                 } else {
 6436:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 6437:                 }
 6438:             } else {
 6439:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 6440:             }
 6441:         } else {
 6442:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6443:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 6444:         }
 6445:     } elsif ($env{'form.action'} eq 'rolerequests') {
 6446:         if ($permission->{cusr} || $permission->{view}) {
 6447:             &print_queued_roles($r,$context,$permission,$brcrum);
 6448:         }
 6449:     } elsif ($env{'form.action'} eq 'queuedroles') {
 6450:         if (($permission->{cusr}) && ($context eq 'domain')) {
 6451:             if (&show_role_requests($context,$env{'request.role.domain'})) {
 6452:                 if ($env{'form.state'} eq 'done') {
 6453:                     &process_pendingroles($r,$context,$permission,$brcrum);
 6454:                 } else {
 6455:                     &print_pendingroles($r,$context,$permission,$brcrum);
 6456:                 }
 6457:             } else {
 6458:                 $r->print(&header(undef,{'no_nav_bar' => 1}).
 6459:                           '<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>');
 6460:             }
 6461:         } else {
 6462:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6463:                      '<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>');
 6464:         }
 6465:     } elsif ($env{'form.action'} eq 'camanagers') {
 6466:         if (($permission->{cusr}) && ($context eq 'author')) {
 6467:             push(@{$brcrum},
 6468:                      {href => '/adm/createuser?action=camanagers',
 6469:                       text => 'Co-author Managers',
 6470:                       help => 'Author_Manage_Coauthors'});
 6471:             if ($env{'form.state'} eq 'process') {
 6472:                 push(@{$brcrum},
 6473:                          {href => '/adm/createuser?action=camanagers',
 6474:                           text => 'Result',
 6475:                           help => 'Author_Manage_Coauthors'});
 6476:             }
 6477:             $args = { bread_crumbs           => $brcrum };
 6478:             $r->print(&header(undef,$args));
 6479:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6480:             if (!exists($env{'form.state'})) {
 6481:                 $r->print('<h3>'.&mt('Co-author Management').'</h3>'."\n".
 6482:                           &display_coauthor_managers($permission));
 6483:             } elsif ($env{'form.state'} eq 'process') {
 6484:                 $r->print('<h3>'.&mt('Co-author Management Update Result').'</h3>'."\n".
 6485:                           &update_coauthor_managers($permission));
 6486:             }
 6487:         }
 6488:     } elsif (($env{'form.action'} eq 'calist') && ($context eq 'author')) {
 6489:         if ($permission->{'cusr'}) {
 6490:             my ($role,$audom,$auname,$canview,$canedit) =
 6491:                 &Apache::lonviewcoauthors::get_allowable();
 6492:             if (($canedit) && ($env{'form.forceedit'})) {
 6493:                 &Apache::lonviewcoauthors::get_editor_crumbs($brcrum,'/adm/createuser');
 6494:                 my $args = { 'bread_crumbs' => $brcrum };
 6495:                 $r->print(&Apache::loncommon::start_page('Configure co-author listing',undef,
 6496:                                                          $args).
 6497:                           &Apache::lonviewcoauthors::edit_settings($audom,$auname,$role,
 6498:                                                                    '/adm/createuser'));
 6499:             } else {
 6500:                 push(@{$brcrum},
 6501:                        {href => '/adm/createuser?action=calist',
 6502:                         text => 'Coauthor-viewable list',
 6503:                         help => 'Author_List_Coauthors'});
 6504:                 my $args = { 'bread_crumbs' => $brcrum };
 6505:                 $r->print(&Apache::loncommon::start_page('Coauthor-viewable list',undef,
 6506:                                                          $args));
 6507:                 my %viewsettings =
 6508:                     &Apache::lonviewcoauthors::retrieve_view_settings($auname,$audom,$role);
 6509:                 if ($viewsettings{'show'} eq 'none') {
 6510:                     $r->print('<h3>'.&mt('Coauthor-viewable listing').'</h3>'.
 6511:                               '<p class="LC_info">'.
 6512:                               &mt('Listing of co-authors not enabled for this Authoring Space').
 6513:                               '</p>');
 6514:                 } else {
 6515:                     &Apache::lonviewcoauthors::print_coauthors($r,$auname,$audom,$role,
 6516:                                                                '/adm/createuser',\%viewsettings);
 6517:                 }
 6518:             }
 6519:         } else {
 6520:             $r->internal_redirect('/adm/viewcoauthors');
 6521:             return OK;
 6522:         }
 6523:     } elsif (($env{'form.action'} eq 'setenv') && ($context eq 'author')) {
 6524:         my ($role,$audom,$auname,$canview,$canedit) =
 6525:             &Apache::lonviewcoauthors::get_allowable();
 6526:         push(@{$brcrum},
 6527:                  {href => '/adm/createuser?action=calist',
 6528:                   text => 'Coauthor-viewable list',
 6529:                   help => 'Author_List_Coauthors'});
 6530:         my $args = { 'bread_crumbs' => $brcrum };
 6531:         $r->print(&Apache::loncommon::start_page('Coauthor-viewable list',undef,
 6532:                                                  $args));
 6533:         my %viewsettings =
 6534:             &Apache::lonviewcoauthors::retrieve_view_settings($auname,$audom,$role);
 6535:         if ($viewsettings{'show'} eq 'none') {
 6536:             $r->print('<h3>'.&mt('Coauthor-viewable listing').'</h3>'.
 6537:                       '<p class="LC_info">'.
 6538:                       &mt('Listing of co-authors not enabled for this Authoring Space').
 6539:                       '</p>');
 6540:         } else {
 6541:             &Apache::lonviewcoauthors::print_coauthors($r,$auname,$audom,$role,
 6542:                                                        '/adm/createuser',\%viewsettings);
 6543:         }
 6544:     } else {
 6545:         $bread_crumbs_component = 'User Management';
 6546:         $args = { bread_crumbs           => $brcrum,
 6547:                   bread_crumbs_component => $bread_crumbs_component};
 6548:         $r->print(&header(undef,$args));
 6549:         $r->print(&print_main_menu($permission,$context,$crstype));
 6550:     }
 6551:     $r->print(&Apache::loncommon::end_page());
 6552:     return OK;
 6553: }
 6554: 
 6555: sub header {
 6556:     my ($jscript,$args) = @_;
 6557:     my $start_page;
 6558:     if (ref($args) eq 'HASH') {
 6559:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 6560:     } else {
 6561:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 6562:     }
 6563:     return $start_page;
 6564: }
 6565: 
 6566: sub add_script {
 6567:     my ($js) = @_;
 6568:     return '<script type="text/javascript">'."\n"
 6569:           .'// <![CDATA['."\n"
 6570:           .$js."\n"
 6571:           .'// ]]>'."\n"
 6572:           .'</script>'."\n";
 6573: }
 6574: 
 6575: sub usernamerequest_javascript {
 6576:     my $js = <<ENDJS;
 6577: 
 6578: function openusernamereqdisplay(dom,uname,queue) {
 6579:     var url = '/adm/createuser?action=displayuserreq';
 6580:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 6581:     var title = 'Account_Request_Browser';
 6582:     var options = 'scrollbars=1,resizable=1,menubar=0';
 6583:     options += ',width=700,height=600';
 6584:     var stdeditbrowser = open(url,title,options,'1');
 6585:     stdeditbrowser.focus();
 6586:     return;
 6587: }
 6588:  
 6589: ENDJS
 6590: }
 6591: 
 6592: sub close_popup_form {
 6593:     my $close= &mt('Close Window');
 6594:     return << "END";
 6595: <p><form name="displayreq" action="" method="post">
 6596: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 6597: </form></p>
 6598: END
 6599: }
 6600: 
 6601: sub verify_user_display {
 6602:     my ($context) = @_;
 6603:     my %lt = &Apache::lonlocal::texthash (
 6604:         course    => 'course(s): description, section(s), status',
 6605:         community => 'community(s): description, section(s), status',
 6606:         author    => 'author',
 6607:     );
 6608:     my $photos;
 6609:     if (($context eq 'course') && $env{'request.course.id'}) {
 6610:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 6611:     }
 6612:     my $output = <<"END";
 6613: 
 6614: function hide_searching() {
 6615:     if (document.getElementById('searching')) {
 6616:         document.getElementById('searching').style.display = 'none';
 6617:     }
 6618:     return;
 6619: }
 6620: 
 6621: function display_update() {
 6622:     document.studentform.action.value = 'listusers';
 6623:     document.studentform.phase.value = 'display';
 6624:     document.studentform.submit();
 6625: }
 6626: 
 6627: function updateCols(caller) {
 6628:     var context = '$context';
 6629:     var photos = '$photos';
 6630:     if (caller == 'Status') {
 6631:         if ((context == 'domain') && 
 6632:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6633:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 6634:             document.getElementById('showcolstatus').checked = false;
 6635:             document.getElementById('showcolstatus').disabled = 'disabled';
 6636:             document.getElementById('showcolstart').checked = false;
 6637:             document.getElementById('showcolend').checked = false;
 6638:         } else {
 6639:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6640:                 document.getElementById('showcolstatus').checked = true;
 6641:                 document.getElementById('showcolstatus').disabled = '';
 6642:                 document.getElementById('showcolstart').checked = true;
 6643:                 document.getElementById('showcolend').checked = true;
 6644:             } else {
 6645:                 document.getElementById('showcolstatus').checked = false;
 6646:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6647:                 document.getElementById('showcolstart').checked = false;
 6648:                 document.getElementById('showcolend').checked = false;
 6649:             }
 6650:             if (context == 'author') {
 6651:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Expired') {
 6652:                     document.getElementById('showcolmanager').checked = false;
 6653:                     document.getElementById('showcolmanager').disabled = 'disabled';
 6654:                 } else if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value != 'aa') {
 6655:                     document.getElementById('showcolmanager').checked = true;
 6656:                     document.getElementById('showcolmanager').disabled = '';
 6657:                 }
 6658:             }
 6659:         }
 6660:     }
 6661:     if (caller == 'output') {
 6662:         if (photos == 1) {
 6663:             if (document.getElementById('showcolphoto')) {
 6664:                 var photoitem = document.getElementById('showcolphoto');
 6665:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 6666:                     photoitem.checked = true;
 6667:                     photoitem.disabled = '';
 6668:                 } else {
 6669:                     photoitem.checked = false;
 6670:                     photoitem.disabled = 'disabled';
 6671:                 }
 6672:             }
 6673:         }
 6674:     }
 6675:     if (caller == 'showrole') {
 6676:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 6677:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 6678:             document.getElementById('showcolrole').checked = true;
 6679:             document.getElementById('showcolrole').disabled = '';
 6680:         } else {
 6681:             document.getElementById('showcolrole').checked = false;
 6682:             document.getElementById('showcolrole').disabled = 'disabled';
 6683:         }
 6684:         if (context == 'domain') {
 6685:             var quotausageshow = 0;
 6686:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6687:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 6688:                 document.getElementById('showcolstatus').checked = false;
 6689:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6690:                 document.getElementById('showcolstart').checked = false;
 6691:                 document.getElementById('showcolend').checked = false;
 6692:             } else {
 6693:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6694:                     document.getElementById('showcolstatus').checked = true;
 6695:                     document.getElementById('showcolstatus').disabled = '';
 6696:                     document.getElementById('showcolstart').checked = true;
 6697:                     document.getElementById('showcolend').checked = true;
 6698:                 }
 6699:             }
 6700:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 6701:                 document.getElementById('showcolextent').disabled = 'disabled';
 6702:                 document.getElementById('showcolextent').checked = 'false';
 6703:                 document.getElementById('showextent').style.display='none';
 6704:                 document.getElementById('showcoltextextent').innerHTML = '';
 6705:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 6706:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 6707:                     if (document.getElementById('showcolauthorusage')) {
 6708:                         document.getElementById('showcolauthorusage').disabled = '';
 6709:                     }
 6710:                     if (document.getElementById('showcolauthorquota')) {
 6711:                         document.getElementById('showcolauthorquota').disabled = '';
 6712:                     }
 6713:                     quotausageshow = 1;
 6714:                 }
 6715:             } else {
 6716:                 document.getElementById('showextent').style.display='block';
 6717:                 document.getElementById('showextent').style.textAlign='left';
 6718:                 document.getElementById('showextent').style.textFace='normal';
 6719:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 6720:                     document.getElementById('showcolextent').disabled = '';
 6721:                     document.getElementById('showcolextent').checked = 'true';
 6722:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 6723:                 } else {
 6724:                     document.getElementById('showcolextent').disabled = '';
 6725:                     document.getElementById('showcolextent').checked = 'true';
 6726:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 6727:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 6728:                     } else {
 6729:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 6730:                     }
 6731:                 }
 6732:             }
 6733:             if (quotausageshow == 0)  {
 6734:                 if (document.getElementById('showcolauthorusage')) {
 6735:                     document.getElementById('showcolauthorusage').checked = false;
 6736:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 6737:                 }
 6738:                 if (document.getElementById('showcolauthorquota')) {
 6739:                     document.getElementById('showcolauthorquota').checked = false;
 6740:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 6741:                 }
 6742:             }
 6743:         }
 6744:         if (context == 'author') {
 6745:             if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'aa') {
 6746:                 document.getElementById('showcolmanager').checked = false;
 6747:                 document.getElementById('showcolmanager').disabled = 'disabled';
 6748:             } else if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value != 'Expired') {
 6749:                 document.getElementById('showcolmanager').checked = true;
 6750:                 document.getElementById('showcolmanager').disabled = '';
 6751:             }
 6752:         }
 6753:     }
 6754:     return;
 6755: }
 6756: 
 6757: END
 6758:     return $output;
 6759: 
 6760: }
 6761: 
 6762: ###############################################################
 6763: ###############################################################
 6764: #  Menu Phase One
 6765: sub print_main_menu {
 6766:     my ($permission,$context,$crstype) = @_;
 6767:     my $linkcontext = $context;
 6768:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 6769:     if (($context eq 'course') && ($crstype eq 'Community')) {
 6770:         $linkcontext = lc($crstype);
 6771:         $stuterm = 'Members';
 6772:     }
 6773:     my %links = (
 6774:                 domain => {
 6775:                             upload     => 'Upload a File of Users',
 6776:                             singleuser => 'Add/Modify a User',
 6777:                             listusers  => 'Manage Users',
 6778:                             },
 6779:                 author => {
 6780:                             upload     => 'Upload a File of Co-authors',
 6781:                             singleuser => 'Add/Modify a Co-author',
 6782:                             listusers  => 'Manage Co-authors',
 6783:                             },
 6784:                 course => {
 6785:                             upload     => 'Upload a File of Course Users',
 6786:                             singleuser => 'Add/Modify a Course User',
 6787:                             listusers  => 'List and Modify Multiple Course Users',
 6788:                             },
 6789:                 community => {
 6790:                             upload     => 'Upload a File of Community Users',
 6791:                             singleuser => 'Add/Modify a Community User',
 6792:                             listusers  => 'List and Modify Multiple Community Users',
 6793:                            },
 6794:                 );
 6795:      my %linktitles = (
 6796:                 domain => {
 6797:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 6798:                             listusers  => 'Show and manage users in this domain.',
 6799:                             },
 6800:                 author => {
 6801:                             singleuser => 'Add a user with a co- or assistant author role.',
 6802:                             listusers  => 'Show and manage co- or assistant authors.',
 6803:                             },
 6804:                 course => {
 6805:                             singleuser => 'Add a user with a certain role to this course.',
 6806:                             listusers  => 'Show and manage users in this course.',
 6807:                             },
 6808:                 community => {
 6809:                             singleuser => 'Add a user with a certain role to this community.',
 6810:                             listusers  => 'Show and manage users in this community.',
 6811:                            },
 6812:                 );
 6813: 
 6814:   if ($linkcontext eq 'domain') {
 6815:       unless ($permission->{'cusr'}) {
 6816:           $links{'domain'}{'singleuser'} = 'View a User';
 6817:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 6818:       }
 6819:   } elsif ($linkcontext eq 'course') {
 6820:       unless ($permission->{'cusr'}) {
 6821:           $links{'course'}{'singleuser'} = 'View a Course User';
 6822:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 6823:           $links{'course'}{'listusers'} = 'List Course Users';
 6824:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 6825:       }
 6826:   } elsif ($linkcontext eq 'community') {
 6827:       unless ($permission->{'cusr'}) {
 6828:           $links{'community'}{'singleuser'} = 'View a Community User';
 6829:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 6830:           $links{'community'}{'listusers'} = 'List Community Users';
 6831:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 6832:       }
 6833:   }
 6834:   my @menu = ( {categorytitle => 'Single Users', 
 6835:          items =>
 6836:          [
 6837:             {
 6838:              linktext => $links{$linkcontext}{'singleuser'},
 6839:              icon => 'edit-redo.png',
 6840:              #help => 'Course_Change_Privileges',
 6841:              url => '/adm/createuser?action=singleuser',
 6842:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6843:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 6844:             },
 6845:          ]},
 6846: 
 6847:          {categorytitle => 'Multiple Users',
 6848:          items => 
 6849:          [
 6850:             {
 6851:              linktext => $links{$linkcontext}{'upload'},
 6852:              icon => 'uplusr.png',
 6853:              #help => 'Course_Create_Class_List',
 6854:              url => '/adm/createuser?action=upload',
 6855:              permission => $permission->{'cusr'},
 6856:              linktitle => 'Upload a CSV or a text file containing users.',
 6857:             },
 6858:             {
 6859:              linktext => $links{$linkcontext}{'listusers'},
 6860:              icon => 'mngcu.png',
 6861:              #help => 'Course_View_Class_List',
 6862:              url => '/adm/createuser?action=listusers',
 6863:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6864:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 6865:             },
 6866: 
 6867:          ]},
 6868: 
 6869:          {categorytitle => 'Administration',
 6870:          items => [ ]},
 6871:        );
 6872: 
 6873:     if ($context eq 'domain'){
 6874:         push(@{  $menu[0]->{items} }, # Single Users
 6875:             {
 6876:              linktext => 'User Access Log',
 6877:              icon => 'document-properties.png',
 6878:              #help => 'Domain_User_Access_Logs',
 6879:              url => '/adm/createuser?action=accesslogs',
 6880:              permission => $permission->{'activity'},
 6881:              linktitle => 'View user access log.',
 6882:             }
 6883:         );
 6884:         
 6885:         push(@{ $menu[2]->{items} }, #Category: Administration
 6886:             {
 6887:              linktext => 'Custom Roles',
 6888:              icon => 'emblem-photos.png',
 6889:              #help => 'Course_Editing_Custom_Roles',
 6890:              url => '/adm/createuser?action=custom',
 6891:              permission => $permission->{'custom'},
 6892:              linktitle => 'Configure a custom role.',
 6893:             },
 6894:             {
 6895:              linktext => 'Authoring Space Requests',
 6896:              icon => 'selfenrl-queue.png',
 6897:              #help => 'Domain_Role_Approvals',
 6898:              url => '/adm/createuser?action=processauthorreq',
 6899:              permission => $permission->{'cusr'},
 6900:              linktitle => 'Approve or reject author role requests',
 6901:             },
 6902:             {
 6903:              linktext => 'LON-CAPA Account Requests',
 6904:              icon => 'list-add.png',
 6905:              #help => 'Domain_Username_Approvals',
 6906:              url => '/adm/createuser?action=processusernamereq',
 6907:              permission => $permission->{'cusr'},
 6908:              linktitle => 'Approve or reject LON-CAPA account requests',
 6909:             },
 6910:             {
 6911:              linktext => 'Change Log',
 6912:              icon => 'document-properties.png',
 6913:              #help => 'Course_User_Logs',
 6914:              url => '/adm/createuser?action=changelogs',
 6915:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 6916:              linktitle => 'View change log.',
 6917:             },
 6918:         );
 6919:         
 6920:     }elsif ($context eq 'course'){
 6921:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 6922: 
 6923:         my %linktext = (
 6924:                          'Course'    => {
 6925:                                           single => 'Add/Modify a Student', 
 6926:                                           drop   => 'Drop Students',
 6927:                                           groups => 'Course Groups',
 6928:                                         },
 6929:                          'Community' => {
 6930:                                           single => 'Add/Modify a Member', 
 6931:                                           drop   => 'Drop Members',
 6932:                                           groups => 'Community Groups',
 6933:                                         },
 6934:                        );
 6935:         $linktext{'Placement'} = $linktext{'Course'};
 6936: 
 6937:         my %linktitle = (
 6938:             'Course' => {
 6939:                   single => 'Add a user with the role of student to this course',
 6940:                   drop   => 'Remove a student from this course.',
 6941:                   groups => 'Manage course groups',
 6942:                         },
 6943:             'Community' => {
 6944:                   single => 'Add a user with the role of member to this community',
 6945:                   drop   => 'Remove a member from this community.',
 6946:                   groups => 'Manage community groups',
 6947:                            },
 6948:         );
 6949: 
 6950:         $linktitle{'Placement'} = $linktitle{'Course'};
 6951: 
 6952:         push(@{ $menu[0]->{items} }, #Category: Single Users
 6953:             {   
 6954:              linktext => $linktext{$crstype}{'single'},
 6955:              #help => 'Course_Add_Student',
 6956:              icon => 'list-add.png',
 6957:              url => '/adm/createuser?action=singlestudent',
 6958:              permission => $permission->{'cusr'},
 6959:              linktitle => $linktitle{$crstype}{'single'},
 6960:             },
 6961:         );
 6962:         
 6963:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 6964:             {
 6965:              linktext => $linktext{$crstype}{'drop'},
 6966:              icon => 'edit-undo.png',
 6967:              #help => 'Course_Drop_Student',
 6968:              url => '/adm/createuser?action=drop',
 6969:              permission => $permission->{'cusr'},
 6970:              linktitle => $linktitle{$crstype}{'drop'},
 6971:             },
 6972:         );
 6973:         push(@{ $menu[2]->{items} }, #Category: Administration
 6974:             {
 6975:              linktext => 'Helpdesk Access',
 6976:              icon => 'helpdesk-access.png',
 6977:              #help => 'Course_Helpdesk_Access',
 6978:              url => '/adm/createuser?action=helpdesk',
 6979:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6980:                             ($permission->{'view'} || $permission->{'cusr'})),
 6981:              linktitle => 'Helpdesk access options',
 6982:             },
 6983:             {
 6984:              linktext => 'Custom Roles',
 6985:              icon => 'emblem-photos.png',
 6986:              #help => 'Course_Editing_Custom_Roles',
 6987:              url => '/adm/createuser?action=custom',
 6988:              permission => $permission->{'custom'},
 6989:              linktitle => 'Configure a custom role.',
 6990:             },
 6991:             {
 6992:              linktext => $linktext{$crstype}{'groups'},
 6993:              icon => 'grps.png',
 6994:              #help => 'Course_Manage_Group',
 6995:              url => '/adm/coursegroups?refpage=cusr',
 6996:              permission => $permission->{'grp_manage'},
 6997:              linktitle => $linktitle{$crstype}{'groups'},
 6998:             },
 6999:             {
 7000:              linktext => 'Change Log',
 7001:              icon => 'document-properties.png',
 7002:              #help => 'Course_User_Logs',
 7003:              url => '/adm/createuser?action=changelogs',
 7004:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 7005:              linktitle => 'View change log.',
 7006:             },
 7007:         );
 7008:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 7009:             push(@{ $menu[2]->{items} },
 7010:                     {
 7011:                      linktext => 'Enrollment Requests',
 7012:                      icon => 'selfenrl-queue.png',
 7013:                      #help => 'Course_Approve_Selfenroll',
 7014:                      url => '/adm/createuser?action=selfenrollqueue',
 7015:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 7016:                      linktitle =>'Approve or reject enrollment requests.',
 7017:                     },
 7018:             );
 7019:         }
 7020:         
 7021:         if (!exists($permission->{'cusr_section'})){
 7022:             if ($crstype ne 'Community') {
 7023:                 push(@{ $menu[2]->{items} },
 7024:                     {
 7025:                      linktext => 'Automated Enrollment',
 7026:                      icon => 'roles.png',
 7027:                      #help => 'Course_Automated_Enrollment',
 7028:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 7029:                                          && (($permission->{'cusr'}) ||
 7030:                                              ($permission->{'view'}))),
 7031:                      url  => '/adm/populate',
 7032:                      linktitle => 'Automated enrollment manager.',
 7033:                     }
 7034:                 );
 7035:             }
 7036:             push(@{ $menu[2]->{items} }, 
 7037:                 {
 7038:                  linktext => 'User Self-Enrollment',
 7039:                  icon => 'self_enroll.png',
 7040:                  #help => 'Course_Self_Enrollment',
 7041:                  url => '/adm/createuser?action=selfenroll',
 7042:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 7043:                  linktitle => 'Configure user self-enrollment.',
 7044:                 },
 7045:             );
 7046:         }
 7047:     } elsif ($context eq 'author') {
 7048:         my $coauthorlist;
 7049:         if ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)$}) {
 7050:             if ($env{'environment.internal.coauthorlist./'.$1.'/'.$2}) {
 7051:                 $coauthorlist = 1;
 7052:             }
 7053:         } elsif ($env{'request.role'} eq "au./$env{'user.domain'}/") {
 7054:             if ($env{'environment.coauthorlist'}) {
 7055:                 $coauthorlist = 1;
 7056:             }
 7057:         }
 7058:         if ($coauthorlist) {
 7059:             push(@{ $menu[1]->{items} },
 7060:                 {
 7061:                  linktext => 'Co-author-viewable list',
 7062:                  icon => 'clst.png',
 7063:                  #help => 'Coauthor_Listing',
 7064:                  url => '/adm/createuser?action=calist&forceedit=0',
 7065:                  permission => $permission->{'cusr'},
 7066:                  linktitle => 'Co-author-viewable listing',
 7067:             });
 7068:         }
 7069:         push(@{ $menu[2]->{items} }, #Category: Administration
 7070:             {
 7071:              linktext => 'Change Log',
 7072:              icon => 'document-properties.png',
 7073:              #help => 'Course_User_Logs',
 7074:              url => '/adm/createuser?action=changelogs',
 7075:              permission => $permission->{'cusr'},
 7076:              linktitle => 'View change log.',
 7077:             },
 7078:             {
 7079:              linktext => 'Co-author Managers',
 7080:              icon => 'camanager.png',
 7081:              #help => 'Coauthor_Management',
 7082:              url => '/adm/createuser?action=camanagers',
 7083:              permission => $permission->{'author'},
 7084:              linktitle => 'Assign/Revoke right to manage co-author roles',
 7085:             },
 7086:             {
 7087:              linktext => 'Configure Co-author Listing',
 7088:              icon => 'coauthors.png',
 7089:              #help => 'Coauthor_Settings',
 7090:              url => '/adm/createuser?action=calist&forceedit=1',
 7091:              permission => ($permission->{'cusr'}),
 7092:              linktitle => 'Set availability of coauthor-viewable user listing',
 7093:             },
 7094:         );
 7095:     }
 7096:     push(@{ $menu[2]->{items} },
 7097:         {
 7098:          linktext => 'Role Requests (other domains)',
 7099:          icon => 'edit-find.png',
 7100:          #help => 'Role_Requests',
 7101:          url => '/adm/createuser?action=rolerequests',
 7102:          permission => $permission->{'cusr'},
 7103:          linktitle => 'Role requests for users in other domains',
 7104:         },
 7105:     );
 7106:     if (&show_role_requests($context,$env{'request.role.domain'})) {
 7107:         push(@{ $menu[2]->{items} },
 7108:             {
 7109:              linktext => 'Queued Role Assignments (this domain)',
 7110:              icon => 'edit-find.png',
 7111:              #help => 'Role_Approvals',
 7112:              url => '/adm/createuser?action=queuedroles',
 7113:              permission => $permission->{'cusr'},
 7114:              linktitle => "Role requests for this domain's users",
 7115:             },
 7116:         );
 7117:     }
 7118:     return Apache::lonhtmlcommon::generate_menu(@menu);
 7119: #               { text => 'View Log-in History',
 7120: #                 help => 'Course_User_Logins',
 7121: #                 action => 'logins',
 7122: #                 permission => $permission->{'cusr'},
 7123: #               });
 7124: }
 7125: 
 7126: sub restore_prev_selections {
 7127:     my %saveable_parameters = ('srchby'   => 'scalar',
 7128: 			       'srchin'   => 'scalar',
 7129: 			       'srchtype' => 'scalar',
 7130: 			       );
 7131:     &Apache::loncommon::store_settings('user','user_picker',
 7132: 				       \%saveable_parameters);
 7133:     &Apache::loncommon::restore_settings('user','user_picker',
 7134: 					 \%saveable_parameters);
 7135: }
 7136: 
 7137: sub print_selfenroll_menu {
 7138:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 7139:     my $crstype = &Apache::loncommon::course_type();
 7140:     my $formname = 'selfenroll';
 7141:     my $nolink = 1;
 7142:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7143:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 7144:     my $setsec_js = 
 7145:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 7146:     my %alerts = &Apache::lonlocal::texthash(
 7147:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 7148:         butn => 'but no user types have been checked.',
 7149:         wilf => "Please uncheck 'activate' or check at least one type.",
 7150:     );
 7151:     my $disabled;
 7152:     if ($readonly) {
 7153:        $disabled = ' disabled="disabled"';
 7154:     }
 7155:     &js_escape(\%alerts);
 7156:     my $selfenroll_js = <<"ENDSCRIPT";
 7157: function update_types(caller,num) {
 7158:     var delidx = getIndexByName('selfenroll_delete');
 7159:     var actidx = getIndexByName('selfenroll_activate');
 7160:     if (caller == 'selfenroll_all') {
 7161:         var selall;
 7162:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7163:             if (document.$formname.selfenroll_all[i].checked) {
 7164:                 selall = document.$formname.selfenroll_all[i].value;
 7165:             }
 7166:         }
 7167:         if (selall == 1) {
 7168:             if (delidx != -1) {
 7169:                 if (document.$formname.selfenroll_delete.length) {
 7170:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7171:                         document.$formname.selfenroll_delete[j].checked = true;
 7172:                     }
 7173:                 } else {
 7174:                     document.$formname.elements[delidx].checked = true;
 7175:                 }
 7176:             }
 7177:             if (actidx != -1) {
 7178:                 if (document.$formname.selfenroll_activate.length) {
 7179:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7180:                         document.$formname.selfenroll_activate[j].checked = false;
 7181:                     }
 7182:                 } else {
 7183:                     document.$formname.elements[actidx].checked = false;
 7184:                 }
 7185:             }
 7186:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 7187:         }
 7188:     }
 7189:     if (caller == 'selfenroll_activate') {
 7190:         if (document.$formname.selfenroll_activate.length) {
 7191:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7192:                 if (document.$formname.selfenroll_activate[j].value == num) {
 7193:                     if (document.$formname.selfenroll_activate[j].checked) {
 7194:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7195:                             if (document.$formname.selfenroll_all[i].value == '1') {
 7196:                                 document.$formname.selfenroll_all[i].checked = false;
 7197:                             }
 7198:                             if (document.$formname.selfenroll_all[i].value == '0') {
 7199:                                 document.$formname.selfenroll_all[i].checked = true;
 7200:                             }
 7201:                         }
 7202:                     }
 7203:                 }
 7204:             }
 7205:         } else {
 7206:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7207:                 if (document.$formname.selfenroll_all[i].value == '1') {
 7208:                     document.$formname.selfenroll_all[i].checked = false;
 7209:                 }
 7210:                 if (document.$formname.selfenroll_all[i].value == '0') {
 7211:                     document.$formname.selfenroll_all[i].checked = true;
 7212:                 }
 7213:             }
 7214:         }
 7215:     }
 7216:     if (caller == 'selfenroll_delete') {
 7217:         if (document.$formname.selfenroll_delete.length) {
 7218:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7219:                 if (document.$formname.selfenroll_delete[j].value == num) {
 7220:                     if (document.$formname.selfenroll_delete[j].checked) {
 7221:                         var delindex = getIndexByName('selfenroll_types_'+num);
 7222:                         if (delindex != -1) { 
 7223:                             if (document.$formname.elements[delindex].length) {
 7224:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7225:                                     document.$formname.elements[delindex][k].checked = false;
 7226:                                 }
 7227:                             } else {
 7228:                                 document.$formname.elements[delindex].checked = false;
 7229:                             }
 7230:                         }
 7231:                     }
 7232:                 }
 7233:             }
 7234:         } else {
 7235:             if (document.$formname.selfenroll_delete.checked) {
 7236:                 var delindex = getIndexByName('selfenroll_types_'+num);
 7237:                 if (delindex != -1) {
 7238:                     if (document.$formname.elements[delindex].length) {
 7239:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7240:                             document.$formname.elements[delindex][k].checked = false;
 7241:                         }
 7242:                     } else {
 7243:                         document.$formname.elements[delindex].checked = false;
 7244:                     }
 7245:                 }
 7246:             }
 7247:         }
 7248:     }
 7249:     return;
 7250: }
 7251: 
 7252: function validate_types(form) {
 7253:     var needaction = new Array();
 7254:     var countfail = 0;
 7255:     var actidx = getIndexByName('selfenroll_activate');
 7256:     if (actidx != -1) {
 7257:         if (document.$formname.selfenroll_activate.length) {
 7258:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7259:                 var num = document.$formname.selfenroll_activate[j].value;
 7260:                 if (document.$formname.selfenroll_activate[j].checked) {
 7261:                     countfail = check_types(num,countfail,needaction)
 7262:                 }
 7263:             }
 7264:         } else {
 7265:             if (document.$formname.selfenroll_activate.checked) {
 7266:                 var num = document.$formname.selfenroll_activate.value;
 7267:                 countfail = check_types(num,countfail,needaction)
 7268:             }
 7269:         }
 7270:     }
 7271:     if (countfail > 0) {
 7272:         var msg = "$alerts{'acto'}\\n";
 7273:         var loopend = needaction.length -1;
 7274:         if (loopend > 0) {
 7275:             for (var m=0; m<loopend; m++) {
 7276:                 msg += needaction[m]+", ";
 7277:             }
 7278:         }
 7279:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 7280:         alert(msg);
 7281:         return; 
 7282:     }
 7283:     setSections(form);
 7284: }
 7285: 
 7286: function check_types(num,countfail,needaction) {
 7287:     var boxname = 'selfenroll_types_'+num;
 7288:     var typeidx = getIndexByName(boxname);
 7289:     var count = 0;
 7290:     if (typeidx != -1) {
 7291:         if (document.$formname.elements[boxname].length) {
 7292:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 7293:                 if (document.$formname.elements[boxname][k].checked) {
 7294:                     count ++;
 7295:                 }
 7296:             }
 7297:         } else {
 7298:             if (document.$formname.elements[typeidx].checked) {
 7299:                 count ++;
 7300:             }
 7301:         }
 7302:         if (count == 0) {
 7303:             var domidx = getIndexByName('selfenroll_dom_'+num);
 7304:             if (domidx != -1) {
 7305:                 var domname = document.$formname.elements[domidx].value;
 7306:                 needaction[countfail] = domname;
 7307:                 countfail ++;
 7308:             }
 7309:         }
 7310:     }
 7311:     return countfail;
 7312: }
 7313: 
 7314: function toggleNotify() {
 7315:     var selfenrollApproval = 0;
 7316:     if (document.$formname.selfenroll_approval.length) {
 7317:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 7318:             if (document.$formname.selfenroll_approval[i].checked) {
 7319:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 7320:                 break;        
 7321:             }
 7322:         }
 7323:     }
 7324:     if (document.getElementById('notified')) {
 7325:         if (selfenrollApproval == 0) {
 7326:             document.getElementById('notified').style.display='none';
 7327:         } else {
 7328:             document.getElementById('notified').style.display='block';
 7329:         }
 7330:     }
 7331:     return;
 7332: }
 7333: 
 7334: function getIndexByName(item) {
 7335:     for (var i=0;i<document.$formname.elements.length;i++) {
 7336:         if (document.$formname.elements[i].name == item) {
 7337:             return i;
 7338:         }
 7339:     }
 7340:     return -1;
 7341: }
 7342: ENDSCRIPT
 7343: 
 7344:     my $output = '<script type="text/javascript">'."\n".
 7345:                  '// <![CDATA['."\n".
 7346:                  $setsec_js."\n".$selfenroll_js."\n".
 7347:                  '// ]]>'."\n".
 7348:                  '</script>'."\n".
 7349:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 7350:     my $visactions = &cat_visibility($cdom);
 7351:     my ($cathash,%cattype);
 7352:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7353:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7354:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7355:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7356:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7357:         if ($cattype{'auth'} eq '') {
 7358:             $cattype{'auth'} = 'std';
 7359:         }
 7360:         if ($cattype{'unauth'} eq '') {
 7361:             $cattype{'unauth'} = 'std';
 7362:         }
 7363:     } else {
 7364:         $cathash = {};
 7365:         $cattype{'auth'} = 'std';
 7366:         $cattype{'unauth'} = 'std';
 7367:     }
 7368:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7369:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7370:                   '<br />'.
 7371:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7372:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7373:                   '</ul>');
 7374:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7375:         if ($currsettings->{'uniquecode'}) {
 7376:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7377:         } else {
 7378:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7379:                   '<br />'.
 7380:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7381:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7382:                   '</ul><br />');
 7383:         }
 7384:     } else {
 7385:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7386:         if (ref($visactions) eq 'HASH') {
 7387:             if ($visible) {
 7388:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 7389:            } else {
 7390:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 7391:                           .$visactions->{'yous'}.
 7392:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 7393:                 if (ref($vismsgs) eq 'ARRAY') {
 7394:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 7395:                     foreach my $item (@{$vismsgs}) {
 7396:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 7397:                     }
 7398:                     $output .= '</ul>';
 7399:                 }
 7400:                 $output .= '</p>';
 7401:             }
 7402:         }
 7403:     }
 7404:     my $actionhref = '/adm/createuser';
 7405:     if ($context eq 'domain') {
 7406:         $actionhref = '/adm/modifycourse';
 7407:     }
 7408: 
 7409:     my %noedit;
 7410:     unless ($context eq 'domain') {
 7411:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7412:     }
 7413:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 7414:                &Apache::lonhtmlcommon::start_pick_box();
 7415:     if (ref($row) eq 'ARRAY') {
 7416:         foreach my $item (@{$row}) {
 7417:             my $title = $item; 
 7418:             if (ref($lt) eq 'HASH') {
 7419:                 $title = $lt->{$item};
 7420:             }
 7421:             $output .= &Apache::lonhtmlcommon::row_title($title);
 7422:             if ($item eq 'types') {
 7423:                 my $curr_types;
 7424:                 if (ref($currsettings) eq 'HASH') {
 7425:                     $curr_types = $currsettings->{'selfenroll_types'};
 7426:                 }
 7427:                 if ($noedit{$item}) {
 7428:                     if ($curr_types eq '*') {
 7429:                         $output .= &mt('Any user in any domain');   
 7430:                     } else {
 7431:                         my @entries = split(/;/,$curr_types);
 7432:                         if (@entries > 0) {
 7433:                             $output .= '<ul>'; 
 7434:                             foreach my $entry (@entries) {
 7435:                                 my ($currdom,$typestr) = split(/:/,$entry);
 7436:                                 next if ($typestr eq '');
 7437:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 7438:                                 my @currinsttypes = split(',',$typestr);
 7439:                                 my ($othertitle,$usertypes,$types) = 
 7440:                                     &Apache::loncommon::sorted_inst_types($currdom);
 7441:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7442:                                     $usertypes->{'any'} = &mt('any user'); 
 7443:                                     if (keys(%{$usertypes}) > 0) {
 7444:                                         $usertypes->{'other'} = &mt('other users');
 7445:                                     }
 7446:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 7447:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 7448:                                  }
 7449:                             }
 7450:                             $output .= '</ul>';
 7451:                         } else {
 7452:                             $output .= &mt('None');
 7453:                         }
 7454:                     }
 7455:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7456:                     next;
 7457:                 }
 7458:                 my $showdomdesc = 1;
 7459:                 my $includeempty = 1;
 7460:                 my $num = 0;
 7461:                 $output .= &Apache::loncommon::start_data_table().
 7462:                            &Apache::loncommon::start_data_table_row()
 7463:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 7464:                            .&mt('Any user in any domain:')
 7465:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 7466:                 if ($curr_types eq '*') {
 7467:                     $output .= ' checked="checked" '; 
 7468:                 }
 7469:                 $output .= 'onchange="javascript:update_types('.
 7470:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 7471:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 7472:                 if ($curr_types ne '*') {
 7473:                     $output .= ' checked="checked" ';
 7474:                 }
 7475:                 $output .= ' onchange="javascript:update_types('.
 7476:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 7477:                            &Apache::loncommon::end_data_table_row().
 7478:                            &Apache::loncommon::end_data_table().
 7479:                            &mt('Or').'<br />'.
 7480:                            &Apache::loncommon::start_data_table();
 7481:                 my %currdoms;
 7482:                 if ($curr_types eq '') {
 7483:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 7484:                 } elsif ($curr_types ne '*') {
 7485:                     my @entries = split(/;/,$curr_types);
 7486:                     if (@entries > 0) {
 7487:                         foreach my $entry (@entries) {
 7488:                             my ($currdom,$typestr) = split(/:/,$entry);
 7489:                             $currdoms{$currdom} = 1;
 7490:                             my $domdesc = &Apache::lonnet::domain($currdom);
 7491:                             my @currinsttypes = split(',',$typestr);
 7492:                             $output .= &Apache::loncommon::start_data_table_row()
 7493:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 7494:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 7495:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 7496:                                        .'" value="'.$currdom.'" /></span><br />'
 7497:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 7498:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 7499:                                        .&mt('Delete').'</label></span></td>';
 7500:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 7501:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 7502:                                        .&Apache::loncommon::end_data_table_row();
 7503:                             $num ++;
 7504:                         }
 7505:                     }
 7506:                 }
 7507:                 my $add_domtitle = &mt('Users in additional domain:');
 7508:                 if ($curr_types eq '*') { 
 7509:                     $add_domtitle = &mt('Users in specific domain:');
 7510:                 } elsif ($curr_types eq '') {
 7511:                     $add_domtitle = &mt('Users in other domain:');
 7512:                 }
 7513:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 7514:                 $output .= &Apache::loncommon::start_data_table_row()
 7515:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 7516:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 7517:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 7518:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 7519:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 7520:                            .&Apache::loncommon::end_data_table();
 7521:             } elsif ($item eq 'registered') {
 7522:                 my ($regon,$regoff);
 7523:                 my $registered;
 7524:                 if (ref($currsettings) eq 'HASH') {
 7525:                     $registered = $currsettings->{'selfenroll_registered'};
 7526:                 }
 7527:                 if ($noedit{$item}) {
 7528:                     if ($registered) {
 7529:                         $output .= &mt('Must be registered in course');
 7530:                     } else {
 7531:                         $output .= &mt('No requirement');
 7532:                     }
 7533:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7534:                     next;
 7535:                 }
 7536:                 if ($registered) {
 7537:                     $regon = ' checked="checked" ';
 7538:                     $regoff = '';
 7539:                 } else {
 7540:                     $regon = '';
 7541:                     $regoff = ' checked="checked" ';
 7542:                 }
 7543:                 $output .= '<label>'.
 7544:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 7545:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 7546:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 7547:                            &mt('No').'</label>';
 7548:             } elsif ($item eq 'enroll_dates') {
 7549:                 my ($starttime,$endtime);
 7550:                 if (ref($currsettings) eq 'HASH') {
 7551:                     $starttime = $currsettings->{'selfenroll_start_date'};
 7552:                     $endtime = $currsettings->{'selfenroll_end_date'};
 7553:                     if ($starttime eq '') {
 7554:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7555:                     }
 7556:                     if ($endtime eq '') {
 7557:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7558:                     }
 7559:                 }
 7560:                 if ($noedit{$item}) {
 7561:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7562:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7563:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7564:                     next;
 7565:                 }
 7566:                 my $startform =
 7567:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 7568:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7569:                 my $endform =
 7570:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 7571:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7572:                 $output .= &selfenroll_date_forms($startform,$endform);
 7573:             } elsif ($item eq 'access_dates') {
 7574:                 my ($starttime,$endtime);
 7575:                 if (ref($currsettings) eq 'HASH') {
 7576:                     $starttime = $currsettings->{'selfenroll_start_access'};
 7577:                     $endtime = $currsettings->{'selfenroll_end_access'};
 7578:                     if ($starttime eq '') {
 7579:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7580:                     }
 7581:                     if ($endtime eq '') {
 7582:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7583:                     }
 7584:                 }
 7585:                 if ($noedit{$item}) {
 7586:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7587:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7588:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7589:                     next;
 7590:                 }
 7591:                 my $startform =
 7592:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 7593:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7594:                 my $endform =
 7595:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 7596:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7597:                 $output .= &selfenroll_date_forms($startform,$endform);
 7598:             } elsif ($item eq 'section') {
 7599:                 my $currsec;
 7600:                 if (ref($currsettings) eq 'HASH') {
 7601:                     $currsec = $currsettings->{'selfenroll_section'};
 7602:                 }
 7603:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 7604:                 my $newsecval;
 7605:                 if ($currsec ne 'none' && $currsec ne '') {
 7606:                     if (!defined($sections_count{$currsec})) {
 7607:                         $newsecval = $currsec;
 7608:                     }
 7609:                 }
 7610:                 if ($noedit{$item}) {
 7611:                     if ($currsec ne '') {
 7612:                         $output .= $currsec;
 7613:                     } else {
 7614:                         $output .= &mt('No specific section');
 7615:                     }
 7616:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7617:                     next;
 7618:                 }
 7619:                 my $sections_select = 
 7620:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 7621:                 $output .= '<table class="LC_createuser">'."\n".
 7622:                            '<tr class="LC_section_row">'."\n".
 7623:                            '<td align="center">'.&mt('Existing sections')."\n".
 7624:                            '<br />'.$sections_select.'</td><td align="center">'.
 7625:                            &mt('New section').'<br />'."\n".
 7626:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 7627:                            '<input type="hidden" name="sections" value="" />'."\n".
 7628:                            '</td></tr></table>'."\n";
 7629:             } elsif ($item eq 'approval') {
 7630:                 my ($currnotified,$currapproval,%appchecked);
 7631:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7632:                 if (ref($currsettings) eq 'HASH') {
 7633:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 7634:                     $currapproval = $currsettings->{'selfenroll_approval'};
 7635:                 }
 7636:                 if ($currapproval !~ /^[012]$/) {
 7637:                     $currapproval = 0;
 7638:                 }
 7639:                 if ($noedit{$item}) {
 7640:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 7641:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 7642:                     next;
 7643:                 }
 7644:                 $appchecked{$currapproval} = ' checked="checked"';
 7645:                 for my $i (0..2) {
 7646:                     $output .= '<label>'.
 7647:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 7648:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 7649:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 7650:                 }
 7651:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 7652:                 my (@ccs,%notified);
 7653:                 my $ccrole = 'cc';
 7654:                 if ($crstype eq 'Community') {
 7655:                     $ccrole = 'co';
 7656:                 }
 7657:                 if ($advhash{$ccrole}) {
 7658:                     @ccs = split(/,/,$advhash{$ccrole});
 7659:                 }
 7660:                 if ($currnotified) {
 7661:                     foreach my $current (split(/,/,$currnotified)) {
 7662:                         $notified{$current} = 1;
 7663:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 7664:                             push(@ccs,$current);
 7665:                         }
 7666:                     }
 7667:                 }
 7668:                 if (@ccs) {
 7669:                     my $style;
 7670:                     unless ($currapproval) {
 7671:                         $style = ' style="display: none;"'; 
 7672:                     }
 7673:                     $output .= '<br /><div id="notified"'.$style.'>'.
 7674:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 7675:                                &Apache::loncommon::start_data_table().
 7676:                                &Apache::loncommon::start_data_table_row();
 7677:                     my $count = 0;
 7678:                     my $numcols = 4;
 7679:                     foreach my $cc (sort(@ccs)) {
 7680:                         my $notifyon;
 7681:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 7682:                         if ($notified{$cc}) {
 7683:                             $notifyon = ' checked="checked" ';
 7684:                         }
 7685:                         if ($count && !$count%$numcols) {
 7686:                             $output .= &Apache::loncommon::end_data_table_row().
 7687:                                        &Apache::loncommon::start_data_table_row()
 7688:                         }
 7689:                         $output .= '<td><span class="LC_nobreak"><label>'.
 7690:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 7691:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 7692:                                    '</label></span></td>';
 7693:                         $count ++;
 7694:                     }
 7695:                     my $rem = $count%$numcols;
 7696:                     if ($rem) {
 7697:                         my $emptycols = $numcols - $rem;
 7698:                         for (my $i=0; $i<$emptycols; $i++) { 
 7699:                             $output .= '<td>&nbsp;</td>';
 7700:                         }
 7701:                     }
 7702:                     $output .= &Apache::loncommon::end_data_table_row().
 7703:                                &Apache::loncommon::end_data_table().
 7704:                                '</div>';
 7705:                 }
 7706:             } elsif ($item eq 'limit') {
 7707:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 7708:                 if (ref($currsettings) eq 'HASH') {
 7709:                     $currlim = $currsettings->{'selfenroll_limit'};
 7710:                     $currcap = $currsettings->{'selfenroll_cap'};
 7711:                 }
 7712:                 if ($noedit{$item}) {
 7713:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 7714:                         if ($currlim eq 'allstudents') {
 7715:                             $output .= &mt('Limit by total students');
 7716:                         } elsif ($currlim eq 'selfenrolled') {
 7717:                             $output .= &mt('Limit by total self-enrolled students');
 7718:                         }
 7719:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 7720:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 7721:                     } else {
 7722:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 7723:                     }
 7724:                     next;
 7725:                 }
 7726:                 if ($currlim eq 'allstudents') {
 7727:                     $crslimit = ' checked="checked" ';
 7728:                     $selflimit = ' ';
 7729:                     $nolimit = ' ';
 7730:                 } elsif ($currlim eq 'selfenrolled') {
 7731:                     $crslimit = ' ';
 7732:                     $selflimit = ' checked="checked" ';
 7733:                     $nolimit = ' '; 
 7734:                 } else {
 7735:                     $crslimit = ' ';
 7736:                     $selflimit = ' ';
 7737:                     $nolimit = ' checked="checked" ';
 7738:                 }
 7739:                 $output .= '<table><tr><td><label>'.
 7740:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 7741:                            &mt('No limit').'</label></td><td><label>'.
 7742:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 7743:                            &mt('Limit by total students').'</label></td><td><label>'.
 7744:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 7745:                            &mt('Limit by total self-enrolled students').
 7746:                            '</td></tr><tr>'.
 7747:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 7748:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 7749:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 7750:             }
 7751:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 7752:         }
 7753:     }
 7754:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 7755:     unless ($readonly) {
 7756:         $output .= '<input type="button" name="selfenrollconf" value="'
 7757:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 7758:     }
 7759:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 7760:               .'<input type="hidden" name="state" value="done" />'."\n"
 7761:               .$additional.'</form>';
 7762:     $r->print($output);
 7763:     return;
 7764: }
 7765: 
 7766: sub get_noedit_fields {
 7767:     my ($cdom,$cnum,$crstype,$row) = @_;
 7768:     my %noedit;
 7769:     if (ref($row) eq 'ARRAY') {
 7770:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 7771:                                                            'internal.selfenrollmgrdc',
 7772:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 7773:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 7774:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 7775:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 7776:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 7777:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 7778:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 7779: 
 7780:         foreach my $item (@{$row}) {
 7781:             next if ($specific_managebycc{$item});
 7782:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 7783:                 $noedit{$item} = 1;
 7784:             }
 7785:         }
 7786:     }
 7787:     return %noedit;
 7788: }
 7789: 
 7790: sub visible_in_stdcat {
 7791:     my ($cdom,$cnum,$domconf) = @_;
 7792:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 7793:     unless (ref($domconf) eq 'HASH') {
 7794:         return ($visible,$cansetvis,\@vismsgs);
 7795:     }
 7796:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7797:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 7798:             $settable{'togglecats'} = 1;
 7799:         }
 7800:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 7801:             $settable{'categorize'} = 1;
 7802:         }
 7803:         $cathash = $domconf->{'coursecategories'}{'cats'};
 7804:     }
 7805:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 7806:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 7807:     } elsif ($settable{'togglecats'}) {
 7808:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 7809:     } elsif ($settable{'categorize'}) {
 7810:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 7811:     } else {
 7812:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 7813:     }
 7814:      
 7815:     my %currsettings =
 7816:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 7817:                              $cdom,$cnum);
 7818:     $visible = 0;
 7819:     if ($currsettings{'internal.coursecode'} ne '') {
 7820:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7821:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7822:             if (ref($cathash) eq 'HASH') {
 7823:                 if ($cathash->{'instcode::0'} eq '') {
 7824:                     push(@vismsgs,'dc_addinst'); 
 7825:                 } else {
 7826:                     $visible = 1;
 7827:                 }
 7828:             } else {
 7829:                 $visible = 1;
 7830:             }
 7831:         } else {
 7832:             $visible = 1;
 7833:         }
 7834:     } else {
 7835:         if (ref($cathash) eq 'HASH') {
 7836:             if ($cathash->{'instcode::0'} ne '') {
 7837:                 push(@vismsgs,'dc_instcode');
 7838:             }
 7839:         } else {
 7840:             push(@vismsgs,'dc_instcode');
 7841:         }
 7842:     }
 7843:     if ($currsettings{'categories'} ne '') {
 7844:         my $cathash;
 7845:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7846:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7847:             if (ref($cathash) eq 'HASH') {
 7848:                 if (keys(%{$cathash}) == 0) {
 7849:                     push(@vismsgs,'dc_catalog');
 7850:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 7851:                     push(@vismsgs,'dc_categories');
 7852:                 } else {
 7853:                     my @currcategories = split('&',$currsettings{'categories'});
 7854:                     my $matched = 0;
 7855:                     foreach my $cat (@currcategories) {
 7856:                         if ($cathash->{$cat} ne '') {
 7857:                             $visible = 1;
 7858:                             $matched = 1;
 7859:                             last;
 7860:                         }
 7861:                     }
 7862:                     if (!$matched) {
 7863:                         if ($settable{'categorize'}) { 
 7864:                             push(@vismsgs,'chgcat');
 7865:                         } else {
 7866:                             push(@vismsgs,'dc_chgcat');
 7867:                         }
 7868:                     }
 7869:                 }
 7870:             }
 7871:         }
 7872:     } else {
 7873:         if (ref($cathash) eq 'HASH') {
 7874:             if ((keys(%{$cathash}) > 1) || 
 7875:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 7876:                 if ($settable{'categorize'}) {
 7877:                     push(@vismsgs,'addcat');
 7878:                 } else {
 7879:                     push(@vismsgs,'dc_addcat');
 7880:                 }
 7881:             }
 7882:         }
 7883:     }
 7884:     if ($currsettings{'hidefromcat'} eq 'yes') {
 7885:         $visible = 0;
 7886:         if ($settable{'togglecats'}) {
 7887:             unshift(@vismsgs,'unhide');
 7888:         } else {
 7889:             unshift(@vismsgs,'dc_unhide')
 7890:         }
 7891:     }
 7892:     return ($visible,$cansetvis,\@vismsgs);
 7893: }
 7894: 
 7895: sub cat_visibility {
 7896:     my ($cdom) = @_;
 7897:     my %visactions = &Apache::lonlocal::texthash(
 7898:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 7899:                    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.',
 7900:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 7901:                    none => 'Display of a course catalog is disabled for this domain.',
 7902:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 7903:                    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.',
 7904:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 7905:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 7906:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 7907:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 7908:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 7909:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 7910:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 7911:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 7912:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 7913:                    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',
 7914:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 7915:     );
 7916:     if ($env{'request.role'} eq "dc./$cdom/") {
 7917:         $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;');
 7918:         $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;');
 7919:         $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;');
 7920:         $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;');
 7921:         $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;');
 7922:         $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;');
 7923:         $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;');
 7924:         $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;');
 7925:         $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;');
 7926:     }
 7927:     $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>"');
 7928:     $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>"');
 7929:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 7930:     return \%visactions;
 7931: }
 7932: 
 7933: sub new_selfenroll_dom_row {
 7934:     my ($newdom,$num) = @_;
 7935:     my $domdesc = &Apache::lonnet::domain($newdom);
 7936:     my $output;
 7937:     if ($domdesc ne '') {
 7938:         $output .= &Apache::loncommon::start_data_table_row()
 7939:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 7940:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 7941:                    .'" value="'.$newdom.'" /></span><br />'
 7942:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 7943:                    .'name="selfenroll_activate" value="'.$num.'" '
 7944:                    .'onchange="javascript:update_types('
 7945:                    ."'selfenroll_activate','$num'".');" />'
 7946:                    .&mt('Activate').'</label></span></td>';
 7947:         my @currinsttypes;
 7948:         $output .= '<td>'.&mt('User types:').'<br />'
 7949:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 7950:                    .&Apache::loncommon::end_data_table_row();
 7951:     }
 7952:     return $output;
 7953: }
 7954: 
 7955: sub selfenroll_inst_types {
 7956:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 7957:     my $output;
 7958:     my $numinrow = 4;
 7959:     my $count = 0;
 7960:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 7961:     my $othervalue = 'any';
 7962:     my $disabled;
 7963:     if ($readonly) {
 7964:         $disabled = ' disabled="disabled"';
 7965:     }
 7966:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7967:         if (keys(%{$usertypes}) > 0) {
 7968:             $othervalue = 'other';
 7969:         }
 7970:         $output .= '<table><tr>';
 7971:         foreach my $type (@{$types}) {
 7972:             if (($count > 0) && ($count%$numinrow == 0)) {
 7973:                 $output .= '</tr><tr>';
 7974:             }
 7975:             if (defined($usertypes->{$type})) {
 7976:                 my $esc_type = &escape($type);
 7977:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 7978:                            $esc_type.'" ';
 7979:                 if (ref($currinsttypes) eq 'ARRAY') {
 7980:                     if (@{$currinsttypes} > 0) {
 7981:                         if (grep(/^any$/,@{$currinsttypes})) {
 7982:                             $output .= 'checked="checked"';
 7983:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 7984:                             $output .= 'checked="checked"';
 7985:                         }
 7986:                     } else {
 7987:                         $output .= 'checked="checked"';
 7988:                     }
 7989:                 }
 7990:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 7991:             }
 7992:             $count ++;
 7993:         }
 7994:         if (($count > 0) && ($count%$numinrow == 0)) {
 7995:             $output .= '</tr><tr>';
 7996:         }
 7997:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 7998:         if (ref($currinsttypes) eq 'ARRAY') {
 7999:             if (@{$currinsttypes} > 0) {
 8000:                 if (grep(/^any$/,@{$currinsttypes})) { 
 8001:                     $output .= ' checked="checked"';
 8002:                 } elsif ($othervalue eq 'other') {
 8003:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 8004:                         $output .= ' checked="checked"';
 8005:                     }
 8006:                 }
 8007:             } else {
 8008:                 $output .= ' checked="checked"';
 8009:             }
 8010:         } else {
 8011:             $output .= ' checked="checked"';
 8012:         }
 8013:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 8014:     }
 8015:     return $output;
 8016: }
 8017: 
 8018: sub selfenroll_date_forms {
 8019:     my ($startform,$endform) = @_;
 8020:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 8021:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 8022:                                                     'LC_oddrow_value')."\n".
 8023:                   $startform."\n".
 8024:                   &Apache::lonhtmlcommon::row_closure(1).
 8025:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 8026:                                                    'LC_oddrow_value')."\n".
 8027:                   $endform."\n".
 8028:                   &Apache::lonhtmlcommon::row_closure(1).
 8029:                   &Apache::lonhtmlcommon::end_pick_box();
 8030:     return $output;
 8031: }
 8032: 
 8033: sub print_userchangelogs_display {
 8034:     my ($r,$context,$permission,$brcrum) = @_;
 8035:     my $formname = 'rolelog';
 8036:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 8037:     if ($context eq 'domain') {
 8038:         $domain = $env{'request.role.domain'};
 8039:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 8040:     } else {
 8041:         if ($context eq 'course') { 
 8042:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8043:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 8044:             $crstype = &Apache::loncommon::course_type();
 8045:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 8046:             my %saveable_parameters = ('show' => 'scalar',);
 8047:             &Apache::loncommon::store_course_settings('roles_log',
 8048:                                                       \%saveable_parameters);
 8049:             &Apache::loncommon::restore_course_settings('roles_log',
 8050:                                                         \%saveable_parameters);
 8051:         } elsif ($context eq 'author') {
 8052:             $domain = $env{'user.domain'};
 8053:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 8054:                 $username = $env{'user.name'};
 8055:             } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 8056:                 ($domain,$username) = ($1,$2);
 8057:             } else {
 8058:                 undef($domain);
 8059:             }
 8060:         }
 8061:         if ($domain ne '' && $username ne '') { 
 8062:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 8063:         }
 8064:     }
 8065:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 8066: 
 8067:     my $helpitem;
 8068:     if ($context eq 'course') {
 8069:         $helpitem = 'Course_User_Logs';
 8070:     } elsif ($context eq 'domain') {
 8071:         $helpitem = 'Domain_Role_Logs';
 8072:     } elsif ($context eq 'author') {
 8073:         $helpitem = 'Author_User_Logs';
 8074:     }
 8075:     push (@{$brcrum},
 8076:              {href => '/adm/createuser?action=changelogs',
 8077:               text => 'User Management Logs',
 8078:               help => $helpitem});
 8079:     my $bread_crumbs_component = 'User Changes';
 8080:     my $args = { bread_crumbs           => $brcrum,
 8081:                  bread_crumbs_component => $bread_crumbs_component};
 8082: 
 8083:     # Create navigation javascript
 8084:     my $jsnav = &userlogdisplay_js($formname);
 8085: 
 8086:     my $jscript = (<<ENDSCRIPT);
 8087: <script type="text/javascript">
 8088: // <![CDATA[
 8089: $jsnav
 8090: // ]]>
 8091: </script>
 8092: ENDSCRIPT
 8093: 
 8094:     # print page header
 8095:     $r->print(&header($jscript,$args));
 8096: 
 8097:     # set defaults
 8098:     my $now = time();
 8099:     my $defstart = $now - (7*24*3600); #7 days ago 
 8100:     my %defaults = (
 8101:                      page               => '1',
 8102:                      show               => '10',
 8103:                      role               => 'any',
 8104:                      chgcontext         => 'any',
 8105:                      rolelog_start_date => $defstart,
 8106:                      rolelog_end_date   => $now,
 8107:                      approvals          => 'any',
 8108:                    );
 8109:     my $more_records = 0;
 8110: 
 8111:     # set current
 8112:     my %curr;
 8113:     foreach my $item ('show','page','role','chgcontext','approvals') {
 8114:         $curr{$item} = $env{'form.'.$item};
 8115:     }
 8116:     my ($startdate,$enddate) = 
 8117:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 8118:     $curr{'rolelog_start_date'} = $startdate;
 8119:     $curr{'rolelog_end_date'} = $enddate;
 8120:     foreach my $key (keys(%defaults)) {
 8121:         if ($curr{$key} eq '') {
 8122:             $curr{$key} = $defaults{$key};
 8123:         }
 8124:     }
 8125:     my (%whodunit,%changed,$version);
 8126:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 8127:     my ($minshown,$maxshown);
 8128:     $minshown = 1;
 8129:     my $count = 0;
 8130:     if ($curr{'show'} =~ /\D/) {
 8131:         $curr{'page'} = 1;
 8132:     } else {
 8133:         $maxshown = $curr{'page'} * $curr{'show'};
 8134:         if ($curr{'page'} > 1) {
 8135:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8136:         }
 8137:     }
 8138: 
 8139:     # Form Header
 8140:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8141:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 8142:                                    $version,$crstype));
 8143: 
 8144:     my $showntableheader = 0;
 8145: 
 8146:     # Table Header
 8147:     my $tableheader = 
 8148:         &Apache::loncommon::start_data_table_header_row()
 8149:        .'<th>&nbsp;</th>'
 8150:        .'<th>'.&mt('When').'</th>'
 8151:        .'<th>'.&mt('Who made the change').'</th>'
 8152:        .'<th>'.&mt('Changed User').'</th>'
 8153:        .'<th>'.&mt('Role').'</th>';
 8154: 
 8155:     if ($context eq 'course') {
 8156:         $tableheader .= '<th>'.&mt('Section').'</th>';
 8157:     }
 8158:     $tableheader .=
 8159:         '<th>'.&mt('Context').'</th>'
 8160:        .'<th>'.&mt('Start').'</th>'
 8161:        .'<th>'.&mt('End').'</th>'
 8162:        .&Apache::loncommon::end_data_table_header_row();
 8163: 
 8164:     # Display user change log data
 8165:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 8166:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 8167:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 8168:         if ($curr{'show'} !~ /\D/) {
 8169:             if ($count >= $curr{'page'} * $curr{'show'}) {
 8170:                 $more_records = 1;
 8171:                 last;
 8172:             }
 8173:         }
 8174:         if ($curr{'role'} ne 'any') {
 8175:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 8176:         }
 8177:         if ($curr{'chgcontext'} ne 'any') {
 8178:             if ($curr{'chgcontext'} eq 'selfenroll') {
 8179:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 8180:             } else {
 8181:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 8182:             }
 8183:         }
 8184:         if (($context eq 'course') && ($viewablesec ne '')) {
 8185:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 8186:         }
 8187:         if ($curr{'approvals'} eq 'none') {
 8188:             next if ($roleslog{$id}{'logentry'}{'approval'});
 8189:         } elsif ($curr{'approvals'} ne 'any') { 
 8190:             next if ($roleslog{$id}{'logentry'}{'approval'} ne $curr{'approvals'});
 8191:         }
 8192:         $count ++;
 8193:         next if ($count < $minshown);
 8194:         unless ($showntableheader) {
 8195:             $r->print(&Apache::loncommon::start_data_table()
 8196:                      .$tableheader);
 8197:             $r->rflush();
 8198:             $showntableheader = 1;
 8199:         }
 8200:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 8201:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 8202:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 8203:         }
 8204:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 8205:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 8206:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 8207:         }
 8208:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 8209:         if ($sec eq '') {
 8210:             $sec = &mt('None');
 8211:         }
 8212:         my ($rolestart,$roleend);
 8213:         if ($roleslog{$id}{'delflag'}) {
 8214:             $rolestart = &mt('deleted');
 8215:             $roleend = &mt('deleted');
 8216:         } else {
 8217:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 8218:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 8219:             if ($rolestart eq '' || $rolestart == 0) {
 8220:                 $rolestart = &mt('No start date'); 
 8221:             } else {
 8222:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 8223:             }
 8224:             if ($roleend eq '' || $roleend == 0) { 
 8225:                 $roleend = &mt('No end date');
 8226:             } else {
 8227:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 8228:             }
 8229:         }
 8230:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 8231:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 8232:             $chgcontext = 'selfenroll';
 8233:         }
 8234:         my %lt = &rolechg_contexts($context,$crstype);
 8235:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 8236:             $chgcontext = $lt{$chgcontext};
 8237:         }
 8238:         my ($showreqby,%reqby);
 8239:         if (($roleslog{$id}{'logentry'}{'approval'}) &&
 8240:             ($roleslog{$id}{'logentry'}{'requester'})) {
 8241:             if ($reqby{$roleslog{$id}{'logentry'}{'requester'}} eq '') {
 8242:                 my ($requname,$requdom) = split(/:/,$roleslog{$id}{'logentry'}{'requester'});
 8243:                 $reqby{$roleslog{$id}{'logentry'}{'requester'}} =
 8244:                     &Apache::loncommon::plainname($requname,$requdom);
 8245:             }
 8246:             $showreqby = &mt('Requester').': <span class="LC_nobreak">'.$reqby{$roleslog{$id}{'logentry'}{'requester'}}.'</span><br />';
 8247:             if ($roleslog{$id}{'logentry'}{'approval'} eq 'domain') {
 8248:                 $showreqby .= &mt('Adjudicator').': <span class="LC_nobreak">'.
 8249:                               $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.
 8250:                               '</span>';
 8251:             } else {
 8252:                 $showreqby .= '<span class="LC_nobreak">'.&mt('User approved').'</span>';
 8253:             }
 8254:         } else {
 8255:             $showreqby = $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}};
 8256:         }
 8257:         $r->print(
 8258:             &Apache::loncommon::start_data_table_row()
 8259:            .'<td>'.$count.'</td>'
 8260:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 8261:            .'<td>'.$showreqby.'</td>'
 8262:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 8263:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 8264:         if ($context eq 'course') { 
 8265:             $r->print('<td>'.$sec.'</td>');
 8266:         }
 8267:         $r->print(
 8268:             '<td>'.$chgcontext.'</td>'
 8269:            .'<td>'.$rolestart.'</td>'
 8270:            .'<td>'.$roleend.'</td>'
 8271:            .&Apache::loncommon::end_data_table_row()."\n");
 8272:     }
 8273: 
 8274:     if ($showntableheader) { # Table footer, if content displayed above
 8275:         $r->print(&Apache::loncommon::end_data_table().
 8276:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8277:     } else { # No content displayed above
 8278:         $r->print('<p class="LC_info">'
 8279:                  .&mt('There are no records to display.')
 8280:                  .'</p>'
 8281:         );
 8282:     }
 8283: 
 8284:     # Form Footer
 8285:     $r->print( 
 8286:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8287:        .'<input type="hidden" name="action" value="changelogs" />'
 8288:        .'</form>');
 8289:     return;
 8290: }
 8291: 
 8292: sub print_useraccesslogs_display {
 8293:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 8294:     my $formname = 'accesslog';
 8295:     my $form = 'document.accesslog';
 8296: 
 8297: # set breadcrumbs
 8298:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 8299:     my $prevphasestr;
 8300:     if ($env{'form.popup'}) {
 8301:         $brcrum = [];
 8302:     } else {
 8303:         push (@{$brcrum},
 8304:             {href => "javascript:backPage($form)",
 8305:              text => $breadcrumb_text{'search'}});
 8306:         my @prevphases;
 8307:         if ($env{'form.prevphases'}) {
 8308:             @prevphases = split(/,/,$env{'form.prevphases'});
 8309:             $prevphasestr = $env{'form.prevphases'};
 8310:         }
 8311:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 8312:             push(@{$brcrum},
 8313:                   {href => "javascript:backPage($form,'get_user_info','select')",
 8314:                    text => $breadcrumb_text{'userpicked'}});
 8315:             if ($env{'form.phase'} eq 'userpicked') {
 8316:                 $prevphasestr = 'userpicked';
 8317:             }
 8318:         }
 8319:     }
 8320:     push(@{$brcrum},
 8321:              {href => '/adm/createuser?action=accesslogs',
 8322:               text => 'User access logs',
 8323:               help => 'Domain_User_Access_Logs'});
 8324:     my $bread_crumbs_component = 'User Access Logs';
 8325:     my $args = { bread_crumbs           => $brcrum,
 8326:                  bread_crumbs_component => 'User Management'};
 8327:     if ($env{'form.popup'}) {
 8328:         $args->{'no_nav_bar'} = 1;
 8329:         $args->{'bread_crumbs_nomenu'} = 1;
 8330:     }
 8331: 
 8332: # set javascript
 8333:     my ($jsback,$elements) = &crumb_utilities();
 8334:     my $jsnav = &userlogdisplay_js($formname);
 8335: 
 8336:     my $jscript = (<<ENDSCRIPT);
 8337: <script type="text/javascript">
 8338: // <![CDATA[
 8339: 
 8340: $jsback
 8341: $jsnav
 8342: 
 8343: // ]]>
 8344: </script>
 8345: 
 8346: ENDSCRIPT
 8347: 
 8348: # print page header
 8349:     $r->print(&header($jscript,$args));
 8350: 
 8351: # early out unless log data can be displayed.
 8352:     unless ($permission->{'activity'}) {
 8353:         $r->print('<p class="LC_warning">'
 8354:                  .&mt('You do not have rights to display user access logs.')
 8355:                  .'</p>');
 8356:         if ($env{'form.popup'}) {
 8357:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8358:         } else {
 8359:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8360:         }
 8361:         return;
 8362:     }
 8363: 
 8364:     unless ($udom eq $env{'request.role.domain'}) {
 8365:         $r->print('<p class="LC_warning">'
 8366:                  .&mt("User's domain must match role's domain")
 8367:                  .'</p>'
 8368:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8369:         return;
 8370:     }
 8371: 
 8372:     if (($uname eq '') || ($udom eq '')) {
 8373:         $r->print('<p class="LC_warning">'
 8374:                  .&mt('Invalid username or domain')
 8375:                  .'</p>'
 8376:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8377:         return;
 8378:     }
 8379: 
 8380:     if (&Apache::lonnet::privileged($uname,$udom,
 8381:                                     [$env{'request.role.domain'}],['dc','su'])) {
 8382:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 8383:                                             [$env{'request.role.domain'}],['dc','su'])) {
 8384:             $r->print('<p class="LC_warning">'
 8385:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 8386:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 8387:                                                          $uname,$udom))
 8388:                  .'</p>');
 8389:             if ($env{'form.popup'}) {
 8390:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8391:             } else {
 8392:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8393:             }
 8394:             return;
 8395:         }
 8396:     }
 8397: 
 8398: # set defaults
 8399:     my $now = time();
 8400:     my $defstart = $now - (7*24*3600);
 8401:     my %defaults = (
 8402:                      page                 => '1',
 8403:                      show                 => '10',
 8404:                      activity             => 'any',
 8405:                      accesslog_start_date => $defstart,
 8406:                      accesslog_end_date   => $now,
 8407:                    );
 8408:     my $more_records = 0;
 8409: 
 8410: # set current
 8411:     my %curr;
 8412:     foreach my $item ('show','page','activity') {
 8413:         $curr{$item} = $env{'form.'.$item};
 8414:     }
 8415:     my ($startdate,$enddate) =
 8416:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 8417:     $curr{'accesslog_start_date'} = $startdate;
 8418:     $curr{'accesslog_end_date'} = $enddate;
 8419:     foreach my $key (keys(%defaults)) {
 8420:         if ($curr{$key} eq '') {
 8421:             $curr{$key} = $defaults{$key};
 8422:         }
 8423:     }
 8424:     my ($minshown,$maxshown);
 8425:     $minshown = 1;
 8426:     my $count = 0;
 8427:     if ($curr{'show'} =~ /\D/) {
 8428:         $curr{'page'} = 1;
 8429:     } else {
 8430:         $maxshown = $curr{'page'} * $curr{'show'};
 8431:         if ($curr{'page'} > 1) {
 8432:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8433:         }
 8434:     }
 8435: 
 8436: # form header
 8437:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8438:               &activity_display_filter($formname,\%curr));
 8439: 
 8440:     my $showntableheader = 0;
 8441:     my ($nav_script,$nav_links);
 8442: 
 8443: # table header
 8444:     my $heading = '<h3>'.
 8445:         &mt('User access logs for: [_1]',
 8446:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 8447:     my $tableheader = $heading
 8448:        .&Apache::loncommon::start_data_table_header_row()
 8449:        .'<th>&nbsp;</th>'
 8450:        .'<th>'.&mt('When').'</th>'
 8451:        .'<th>'.&mt('HostID').'</th>'
 8452:        .'<th>'.&mt('Event').'</th>'
 8453:        .'<th>'.&mt('Other data').'</th>'
 8454:        .&Apache::loncommon::end_data_table_header_row();
 8455: 
 8456:     my %filters=(
 8457:         start  => $curr{'accesslog_start_date'},
 8458:         end    => $curr{'accesslog_end_date'},
 8459:         action => $curr{'activity'},
 8460:     );
 8461: 
 8462:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 8463:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8464:         my (%courses,%missing);
 8465:         my @results = split(/\&/,$reply);
 8466:         foreach my $item (reverse(@results)) {
 8467:             my ($timestamp,$host,$event) = split(/:/,$item);
 8468:             next unless ($event =~ /^(Log|Role)/);
 8469:             if ($curr{'show'} !~ /\D/) {
 8470:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 8471:                     $more_records = 1;
 8472:                     last;
 8473:                 }
 8474:             }
 8475:             $count ++;
 8476:             next if ($count < $minshown);
 8477:             unless ($showntableheader) {
 8478:                 $r->print($nav_script
 8479:                          .&Apache::loncommon::start_data_table()
 8480:                          .$tableheader);
 8481:                 $r->rflush();
 8482:                 $showntableheader = 1;
 8483:             }
 8484:             my ($shown,$extra);
 8485:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 8486:             if ($event eq 'Role') {
 8487:                 my ($rolecode,$extent) = split(/\./,$data,2);
 8488:                 next if ($extent eq '');
 8489:                 my ($crstype,$desc,$info);
 8490:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 8491:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 8492:                     my $cid = $cdom.'_'.$cnum;
 8493:                     if (exists($courses{$cid})) {
 8494:                         $crstype = $courses{$cid}{'type'};
 8495:                         $desc = $courses{$cid}{'description'};
 8496:                     } elsif ($missing{$cid}) {
 8497:                         $crstype = 'Course';
 8498:                         $desc = 'Course/Community';
 8499:                     } else {
 8500:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8501:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 8502:                             $courses{$cid} = $crsinfo{$cid};
 8503:                             $crstype = $crsinfo{$cid}{'type'};
 8504:                             $desc = $crsinfo{$cid}{'description'};
 8505:                         } else {
 8506:                             $missing{$cid} = 1;
 8507:                         }
 8508:                     }
 8509:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 8510:                     if ($sec ne '') {
 8511:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 8512:                     }
 8513:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 8514:                     my ($dom,$name) = ($1,$2);
 8515:                     if ($rolecode eq 'au') {
 8516:                         $extra = '';
 8517:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 8518:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 8519:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 8520:                         $extra = &mt('Domain: [_1]',$dom);
 8521:                     }
 8522:                 }
 8523:                 my $rolename;
 8524:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 8525:                     my $role = $3;
 8526:                     my $owner = "($2:$1)";
 8527:                     if ($2 eq $1.'-domainconfig') {
 8528:                         $owner = '(ad hoc)';
 8529:                     }
 8530:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 8531:                 } else {
 8532:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 8533:                 }
 8534:                 $shown = &mt('Role selection: [_1]',$rolename);
 8535:             } else {
 8536:                 $shown = &mt($event);
 8537:                 if ($data =~ /^webdav/) {
 8538:                     my ($path,$clientip) = split(/\s+/,$data,2);
 8539:                     $path =~ s/^webdav//;
 8540:                     if ($clientip ne '') {
 8541:                         $extra = &mt('Client IP address: [_1]',$clientip);
 8542:                     }
 8543:                     if ($path ne '') {
 8544:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 8545:                     }
 8546:                 } elsif ($data ne '') {
 8547:                     $extra = &mt('Client IP address: [_1]',$data);
 8548:                 }
 8549:             }
 8550:             $r->print(
 8551:             &Apache::loncommon::start_data_table_row()
 8552:            .'<td>'.$count.'</td>'
 8553:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 8554:            .'<td>'.$host.'</td>'
 8555:            .'<td>'.$shown.'</td>'
 8556:            .'<td>'.$extra.'</td>'
 8557:            .&Apache::loncommon::end_data_table_row()."\n");
 8558:         }
 8559:     }
 8560: 
 8561:     if ($showntableheader) { # Table footer, if content displayed above
 8562:         $r->print(&Apache::loncommon::end_data_table().
 8563:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8564:     } else { # No content displayed above
 8565:         $r->print($heading.'<p class="LC_info">'
 8566:                  .&mt('There are no records to display.')
 8567:                  .'</p>');
 8568:     }
 8569: 
 8570:     if ($env{'form.popup'} == 1) {
 8571:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 8572:     }
 8573: 
 8574:     # Form Footer
 8575:     $r->print(
 8576:         '<input type="hidden" name="currstate" value="" />'
 8577:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 8578:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 8579:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8580:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 8581:        .'<input type="hidden" name="phase" value="activity" />'
 8582:        .'<input type="hidden" name="action" value="accesslogs" />'
 8583:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 8584:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 8585:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 8586:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 8587:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 8588:        .'</form>');
 8589:     return;
 8590: }
 8591: 
 8592: sub earlyout_accesslog_form {
 8593:     my ($formname,$prevphasestr,$udom) = @_;
 8594:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 8595:    return <<"END";
 8596: <form action="/adm/createuser" method="post" name="$formname">
 8597: <input type="hidden" name="currstate" value="" />
 8598: <input type="hidden" name="prevphases" value="$prevphasestr" />
 8599: <input type="hidden" name="phase" value="activity" />
 8600: <input type="hidden" name="action" value="accesslogs" />
 8601: <input type="hidden" name="srchdomain" value="$udom" />
 8602: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 8603: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 8604: <input type="hidden" name="srchterm" value="$srchterm" />
 8605: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 8606: </form>
 8607: END
 8608: }
 8609: 
 8610: sub activity_display_filter {
 8611:     my ($formname,$curr) = @_;
 8612:     my $nolink = 1;
 8613:     my $output = '<table><tr><td valign="top">'.
 8614:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 8615:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'','',undef,
 8616:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8617:                  '</td><td>&nbsp;&nbsp;</td>';
 8618:     my $startform =
 8619:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 8620:                                             $curr->{'accesslog_start_date'},undef,
 8621:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8622:     my $endform =
 8623:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 8624:                                             $curr->{'accesslog_end_date'},undef,
 8625:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8626:     my %lt = &Apache::lonlocal::texthash (
 8627:                                           activity => 'Activity',
 8628:                                           Role     => 'Role selection',
 8629:                                           log      => 'Log-in or Logout',
 8630:     );
 8631:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 8632:                '<table><tr><td>'.&mt('After:').
 8633:                '</td><td>'.$startform.'</td></tr>'.
 8634:                '<tr><td>'.&mt('Before:').'</td>'.
 8635:                '<td>'.$endform.'</td></tr></table>'.
 8636:                '</td>'.
 8637:                '<td>&nbsp;&nbsp;</td>'.
 8638:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 8639:                '<select name="activity"><option value="any"';
 8640:     if ($curr->{'activity'} eq 'any') {
 8641:         $output .= ' selected="selected"';
 8642:     }
 8643:     $output .= '>'.&mt('Any').'</option>'."\n";
 8644:     foreach my $activity ('Role','log') {
 8645:         my $selstr = '';
 8646:         if ($activity eq $curr->{'activity'}) {
 8647:             $selstr = ' selected="selected"';
 8648:         }
 8649:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 8650:     }
 8651:     $output .= '</select></td>'.
 8652:                '</tr></table>';
 8653:     # Update Display button
 8654:     $output .= '<p>'
 8655:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8656:               .'</p><hr />';
 8657:     return $output;
 8658: }
 8659: 
 8660: sub userlogdisplay_js {
 8661:     my ($formname) = @_;
 8662:     return <<"ENDSCRIPT";
 8663: 
 8664: function chgPage(caller) {
 8665:     if (caller == 'previous') {
 8666:         document.$formname.page.value --;
 8667:     }
 8668:     if (caller == 'next') {
 8669:         document.$formname.page.value ++;
 8670:     }
 8671:     document.$formname.submit();
 8672:     return;
 8673: }
 8674: ENDSCRIPT
 8675: }
 8676: 
 8677: sub userlogdisplay_navlinks {
 8678:     my ($curr,$more_records) = @_;
 8679:     return unless(ref($curr) eq 'HASH');
 8680:     # Navigation Buttons
 8681:     my $nav_links = '<p>';
 8682:     if (($curr->{'page'} > 1) || ($more_records)) {
 8683:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 8684:             $nav_links .= '<input type="button"'
 8685:                          .' onclick="javascript:chgPage('."'previous'".');"'
 8686:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 8687:                          .'" /> ';
 8688:         }
 8689:         if ($more_records) {
 8690:             $nav_links .= '<input type="button"'
 8691:                          .' onclick="javascript:chgPage('."'next'".');"'
 8692:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 8693:                          .'" />';
 8694:         }
 8695:     }
 8696:     $nav_links .= '</p>';
 8697:     return $nav_links;
 8698: }
 8699: 
 8700: sub role_display_filter {
 8701:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 8702:     my $nolink = 1;
 8703:     my $output = '<table><tr><td valign="top">'.
 8704:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 8705:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'','',undef,
 8706:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8707:                  '</td><td>&nbsp;&nbsp;</td>';
 8708:     my $startform =
 8709:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 8710:                                             $curr->{'rolelog_start_date'},undef,
 8711:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8712:     my $endform =
 8713:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 8714:                                             $curr->{'rolelog_end_date'},undef,
 8715:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8716:     my %lt = &rolechg_contexts($context,$crstype);
 8717:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 8718:                '<table><tr><td>'.&mt('After:').
 8719:                '</td><td>'.$startform.'</td></tr>'.
 8720:                '<tr><td>'.&mt('Before:').'</td>'.
 8721:                '<td>'.$endform.'</td></tr></table>'.
 8722:                '</td>'.
 8723:                '<td>&nbsp;&nbsp;</td>'.
 8724:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 8725:                '<select name="role"><option value="any"';
 8726:     if ($curr->{'role'} eq 'any') {
 8727:         $output .= ' selected="selected"';
 8728:     }
 8729:     $output .= '>'.&mt('Any').'</option>'."\n";
 8730:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 8731:     foreach my $role (@roles) {
 8732:         my $plrole;
 8733:         if ($role eq 'cr') {
 8734:             $plrole = &mt('Custom Role');
 8735:         } else {
 8736:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8737:         }
 8738:         my $selstr = '';
 8739:         if ($role eq $curr->{'role'}) {
 8740:             $selstr = ' selected="selected"';
 8741:         }
 8742:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 8743:     }
 8744:     $output .= '</select></td>'.
 8745:                '<td>&nbsp;&nbsp;</td>'.
 8746:                '<td valign="top"><b>'.
 8747:                &mt('Context:').'</b><br /><select name="chgcontext">';
 8748:     my @posscontexts;
 8749:     if ($context eq 'course') {
 8750:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype','ltienroll');
 8751:     } elsif ($context eq 'domain') {
 8752:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 8753:     } else {
 8754:         @posscontexts = ('any','author','coauthor','domain');
 8755:     }
 8756:     foreach my $chgtype (@posscontexts) {
 8757:         my $selstr = '';
 8758:         if ($curr->{'chgcontext'} eq $chgtype) {
 8759:             $selstr = ' selected="selected"';
 8760:         }
 8761:         if ($context eq 'course') {
 8762:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 8763:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 8764:             }
 8765:         }
 8766:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 8767:     }
 8768:     my @possapprovals = ('any','none','domain','user');
 8769:     my %apptxt = &approval_types();
 8770:     $output .= '</select></td>'.
 8771:                '<td>&nbsp;&nbsp;</td>'.
 8772:                '<td valign="top"><b>'.
 8773:                &mt('Approvals:').'</b><br /><select name="approvals">';
 8774:     foreach my $approval (@possapprovals) {
 8775:         my $selstr = '';
 8776:         if ($curr->{'approvals'} eq $approval) {
 8777:             $selstr = ' selected="selected"';
 8778:         }    
 8779:         $output .= '<option value="'.$approval.'"'.$selstr.'>'.$apptxt{$approval}.'</option>';
 8780:     }
 8781:     $output .= '</select></td></tr></table>';
 8782: 
 8783:     # Update Display button
 8784:     $output .= '<p>'
 8785:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8786:               .'</p>';
 8787: 
 8788:     # Server version info
 8789:     my $needsrev = '2.11.0';
 8790:     if ($context eq 'course') {
 8791:         $needsrev = '2.7.0';
 8792:     }
 8793:     
 8794:     $output .= '<p class="LC_info">'
 8795:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 8796:                   ,$needsrev);
 8797:     if ($version) {
 8798:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 8799:     }
 8800:     $output .= '</p><hr />';
 8801:     return $output;
 8802: }
 8803: 
 8804: sub rolechg_contexts {
 8805:     my ($context,$crstype) = @_;
 8806:     my %lt;
 8807:     if ($context eq 'course') {
 8808:         %lt = &Apache::lonlocal::texthash (
 8809:                                              any          => 'Any',
 8810:                                              automated    => 'Automated Enrollment',
 8811:                                              chgtype      => 'Enrollment Type/Lock Change',
 8812:                                              updatenow    => 'Roster Update',
 8813:                                              createcourse => 'Course Creation',
 8814:                                              course       => 'User Management in course',
 8815:                                              domain       => 'User Management in domain',
 8816:                                              selfenroll   => 'Self-enrolled',
 8817:                                              requestcourses => 'Course Request',
 8818:                                              ltienroll    => 'Enrollment via LTI',
 8819:                                          );
 8820:         if ($crstype eq 'Community') {
 8821:             $lt{'createcourse'} = &mt('Community Creation');
 8822:             $lt{'course'} = &mt('User Management in community');
 8823:             $lt{'requestcourses'} = &mt('Community Request');
 8824:         }
 8825:     } elsif ($context eq 'domain') {
 8826:         %lt = &Apache::lonlocal::texthash (
 8827:                                              any           => 'Any',
 8828:                                              domain        => 'User Management in domain',
 8829:                                              requestauthor => 'Authoring Request',
 8830:                                              server        => 'Command line script (DC role)',
 8831:                                              domconfig     => 'Self-enrolled',
 8832:                                          );
 8833:     } else {
 8834:         %lt = &Apache::lonlocal::texthash (
 8835:                                              any    => 'Any',
 8836:                                              domain => 'User Management in domain',
 8837:                                              author => 'User Management by author',
 8838:                                              coauthor => 'User Management by coauthor',
 8839:                                          );
 8840:     } 
 8841:     return %lt;
 8842: }
 8843: 
 8844: sub approval_types {
 8845:     return &Apache::lonlocal::texthash (
 8846:                                           any => 'Any',
 8847:                                           none => 'No approval needed',
 8848:                                           user => 'Role recipient approval',
 8849:                                           domain => 'Domain coordinator approval',
 8850:                                        );
 8851: }
 8852: 
 8853: sub print_helpdeskaccess_display {
 8854:     my ($r,$permission,$brcrum) = @_;
 8855:     my $formname = 'helpdeskaccess';
 8856:     my $helpitem = 'Course_Helpdesk_Access';
 8857:     push (@{$brcrum},
 8858:              {href => '/adm/createuser?action=helpdesk',
 8859:               text => 'Helpdesk Access',
 8860:               help => $helpitem});
 8861:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8862:     my $args = { bread_crumbs           => $brcrum,
 8863:                  bread_crumbs_component => $bread_crumbs_component};
 8864: 
 8865:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8866:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8867:     my $confname = $cdom.'-domainconfig';
 8868:     my $crstype = &Apache::loncommon::course_type();
 8869: 
 8870:     my @accesstypes = ('all','dh','da','none');
 8871:     my ($numstatustypes,@jsarray);
 8872:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8873:     if (ref($types) eq 'ARRAY') {
 8874:         if (@{$types} > 0) {
 8875:             $numstatustypes = scalar(@{$types});
 8876:             push(@accesstypes,'status');
 8877:             @jsarray = ('bystatus');
 8878:         }
 8879:     }
 8880:     my %customroles = &get_domain_customroles($cdom,$confname);
 8881:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8882:     if (keys(%domhelpdesk)) {
 8883:        push(@accesstypes,('inc','exc'));
 8884:        push(@jsarray,('notinc','notexc'));
 8885:     }
 8886:     push(@jsarray,'privs');
 8887:     my $hiddenstr = join("','",@jsarray);
 8888:     my $rolestr = join("','",sort(keys(%customroles)));
 8889: 
 8890:     my $jscript;
 8891:     my (%settings,%overridden);
 8892:     if (keys(%customroles)) {
 8893:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8894:                                 $types,\%customroles,\%settings,\%overridden);
 8895:         my %jsfull=();
 8896:         my %jslevels= (
 8897:                      course => {},
 8898:                      domain => {},
 8899:                      system => {},
 8900:                     );
 8901:         my %jslevelscurrent=(
 8902:                            course => {},
 8903:                            domain => {},
 8904:                            system => {},
 8905:                           );
 8906:         my (%privs,%jsprivs);
 8907:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 8908:         foreach my $priv (keys(%jsfull)) {
 8909:             if ($jslevels{'course'}{$priv}) {
 8910:                 $jsprivs{$priv} = 1;
 8911:             }
 8912:         }
 8913:         my (%elements,%stored);
 8914:         foreach my $role (keys(%customroles)) {
 8915:             $elements{$role.'_access'} = 'radio';
 8916:             $elements{$role.'_incrs'} = 'radio';
 8917:             if ($numstatustypes) {
 8918:                 $elements{$role.'_status'} = 'checkbox';
 8919:             }
 8920:             if (keys(%domhelpdesk) > 0) {
 8921:                 $elements{$role.'_staff_inc'} = 'checkbox';
 8922:                 $elements{$role.'_staff_exc'} = 'checkbox';
 8923:             }
 8924:             $elements{$role.'_override'} = 'checkbox';
 8925:             if (ref($settings{$role}) eq 'HASH') {
 8926:                 if ($settings{$role}{'access'} ne '') {
 8927:                     my $curraccess = $settings{$role}{'access'};
 8928:                     $stored{$role.'_access'} = $curraccess;
 8929:                     $stored{$role.'_incrs'} = 1;
 8930:                     if ($curraccess eq 'status') {
 8931:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 8932:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 8933:                         }
 8934:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8935:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 8936:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 8937:                         }
 8938:                     }
 8939:                 } else {
 8940:                     $stored{$role.'_incrs'} = 0;
 8941:                 }
 8942:                 $stored{$role.'_override'} = [];
 8943:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 8944:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 8945:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 8946:                             push(@{$stored{$role.'_override'}},$priv);
 8947:                         }
 8948:                     }
 8949:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 8950:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 8951:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 8952:                                 push(@{$stored{$role.'_override'}},$priv);
 8953:                             }
 8954:                         }
 8955:                     }
 8956:                 }
 8957:             } else {
 8958:                 $stored{$role.'_incrs'} = 0;
 8959:             }
 8960:         }
 8961:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 8962:     }
 8963: 
 8964:     my $js = <<"ENDJS";
 8965: <script type="text/javascript">
 8966: // <![CDATA[
 8967: $jscript;
 8968: 
 8969: function switchRoleTab(caller,role) {
 8970:     if (document.getElementById(role+'_maindiv')) {
 8971:         if (caller.id != 'LC_current_minitab') {
 8972:             if (document.getElementById('LC_current_minitab')) {
 8973:                 document.getElementById('LC_current_minitab').id=null;
 8974:             }
 8975:             var roledivs = Array('$rolestr');
 8976:             if (roledivs.length > 0) {
 8977:                 for (var i=0; i<roledivs.length; i++) {
 8978:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 8979:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 8980:                     }
 8981:                 }
 8982:             }
 8983:             caller.id = 'LC_current_minitab';
 8984:             document.getElementById(role+'_maindiv').style.display='block';
 8985:         }
 8986:     }
 8987:     return false;
 8988: }
 8989: 
 8990: function helpdeskAccess(role) {
 8991:     var curraccess = null;
 8992:     if (document.$formname.elements[role+'_access'].length) {
 8993:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 8994:             if (document.$formname.elements[role+'_access'][i].checked) {
 8995:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 8996:             }
 8997:         }
 8998:     }
 8999:     var shown = Array();
 9000:     var hidden = Array();
 9001:     if (curraccess == 'none') {
 9002:         hidden = Array ('$hiddenstr');
 9003:     } else {
 9004:         if (curraccess == 'status') {
 9005:             shown = Array ('bystatus','privs');
 9006:             hidden = Array ('notinc','notexc');
 9007:         } else {
 9008:             if (curraccess == 'exc') {
 9009:                 shown = Array ('notexc','privs');
 9010:                 hidden = Array ('notinc','bystatus');
 9011:             }
 9012:             if (curraccess == 'inc') {
 9013:                 shown = Array ('notinc','privs');
 9014:                 hidden = Array ('notexc','bystatus');
 9015:             }
 9016:             if (curraccess == 'all') {
 9017:                 shown = Array ('privs');
 9018:                 hidden = Array ('notinc','notexc','bystatus');
 9019:             }
 9020:         }
 9021:     }
 9022:     if (hidden.length > 0) {
 9023:         for (var i=0; i<hidden.length; i++) {
 9024:             if (document.getElementById(role+'_'+hidden[i])) {
 9025:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 9026:             }
 9027:         }
 9028:     }
 9029:     if (shown.length > 0) {
 9030:         for (var i=0; i<shown.length; i++) {
 9031:             if (document.getElementById(role+'_'+shown[i])) {
 9032:                 if (shown[i] == 'privs') {
 9033:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 9034:                 } else {
 9035:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 9036:                 }
 9037:             }
 9038:         }
 9039:     }
 9040:     return;
 9041: }
 9042: 
 9043: function toggleAccess(role) {
 9044:     if ((document.getElementById(role+'_setincrs')) &&
 9045:         (document.getElementById(role+'_setindom'))) {
 9046:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 9047:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 9048:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 9049:                     document.getElementById(role+'_setindom').style.display = 'none';
 9050:                     document.getElementById(role+'_setincrs').style.display = 'block';
 9051:                 } else {
 9052:                     document.getElementById(role+'_setincrs').style.display = 'none';
 9053:                     document.getElementById(role+'_setindom').style.display = 'block';
 9054:                 }
 9055:                 break;
 9056:             }
 9057:         }
 9058:     }
 9059:     return;
 9060: }
 9061: 
 9062: // ]]>
 9063: </script>
 9064: ENDJS
 9065: 
 9066:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 9067: 
 9068:     # print page header
 9069:     $r->print(&header($js,$args));
 9070:     # print form header
 9071:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 9072: 
 9073:     if (keys(%customroles)) {
 9074:         my %lt = &Apache::lonlocal::texthash(
 9075:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 9076:                     'rou'    => 'Role usage',
 9077:                     'whi'    => 'Which helpdesk personnel may use this role?',
 9078:                     'udd'    => 'Use domain default',
 9079:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 9080:                     'dh'     => 'All with domain helpdesk role',
 9081:                     'da'     => 'All with domain helpdesk assistant role',
 9082:                     'none'   => 'None',
 9083:                     'status' => 'Determined based on institutional status',
 9084:                     'inc'    => 'Include all, but exclude specific personnel',
 9085:                     'exc'    => 'Exclude all, but include specific personnel',
 9086:                     'hel'    => 'Helpdesk',
 9087:                     'rpr'    => 'Role privileges',
 9088:                  );
 9089:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 9090:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9091:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 9092:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9093:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9094:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9095:             }
 9096:         }
 9097:         my $count = 0;
 9098:         foreach my $role (sort(keys(%customroles))) {
 9099:             my ($order,$desc,$access_in_dom);
 9100:             if (ref($domcurrent{$role}) eq 'HASH') {
 9101:                 $order = $domcurrent{$role}{'order'};
 9102:                 $desc = $domcurrent{$role}{'desc'};
 9103:                 $access_in_dom = $domcurrent{$role}{'access'};
 9104:             }
 9105:             if ($order eq '') {
 9106:                 $order = $count;
 9107:             }
 9108:             $ordered{$order} = $role;
 9109:             if ($desc ne '') {
 9110:                 $description{$role} = $desc;
 9111:             } else {
 9112:                 $description{$role}= $role;
 9113:             }
 9114:             $count++;
 9115:         }
 9116:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9117:         my @roles_by_num = ();
 9118:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9119:             push(@roles_by_num,$ordered{$item});
 9120:         }
 9121:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 9122:         if ($permission->{'owner'}) {
 9123:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 9124:             $r->print('<input type="hidden" name="state" value="process" />'.
 9125:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 9126:         } else {
 9127:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 9128:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 9129:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 9130:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 9131:             }
 9132:             $disabled = ' disabled="disabled"';
 9133:         }
 9134:         $r->print('</p>');
 9135: 
 9136:         $r->print('<div id="LC_minitab_header"><ul>');
 9137:         my $count = 0;
 9138:         my %visibility;
 9139:         foreach my $role (@roles_by_num) {
 9140:             my $id;
 9141:             if ($count == 0) {
 9142:                 $id=' id="LC_current_minitab"';
 9143:                 $visibility{$role} = ' style="display:block"';
 9144:             } else {
 9145:                 $visibility{$role} = ' style="display:none"';
 9146:             }
 9147:             $count ++;
 9148:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 9149:         }
 9150:         $r->print('</ul></div>');
 9151: 
 9152:         foreach my $role (@roles_by_num) {
 9153:             my %usecheck = (
 9154:                              all => ' checked="checked"',
 9155:                            );
 9156:             my %displaydiv = (
 9157:                                 status => 'none',
 9158:                                 inc    => 'none',
 9159:                                 exc    => 'none',
 9160:                                 priv   => 'block',
 9161:                              );
 9162:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 9163:             if (ref($settings{$role}) eq 'HASH') {
 9164:                 if ($settings{$role}{'access'} ne '') {
 9165:                     $indomvis = ' style="display:none"';
 9166:                     $incrsvis = ' style="display:block"';
 9167:                     $incrscheck = ' checked="checked"';
 9168:                     if ($settings{$role}{'access'} ne 'all') {
 9169:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 9170:                         delete($usecheck{'all'});
 9171:                         if ($settings{$role}{'access'} eq 'status') {
 9172:                             my $access = 'status';
 9173:                             $displaydiv{$access} = 'inline';
 9174:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9175:                                 $selected{$access} = $settings{$role}{$access};
 9176:                             }
 9177:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 9178:                             my $access = $1;
 9179:                             $displaydiv{$access} = 'inline';
 9180:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9181:                                 $selected{$access} = $settings{$role}{$access};
 9182:                             }
 9183:                         } elsif ($settings{$role}{'access'} eq 'none') {
 9184:                             $displaydiv{'priv'} = 'none';
 9185:                         }
 9186:                     }
 9187:                 } else {
 9188:                     $indomcheck = ' checked="checked"';
 9189:                     $indomvis = ' style="display:block"';
 9190:                     $incrsvis = ' style="display:none"';
 9191:                 }
 9192:             } else {
 9193:                 $indomcheck = ' checked="checked"';
 9194:                 $indomvis = ' style="display:block"';
 9195:                 $incrsvis = ' style="display:none"';
 9196:             }
 9197:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 9198:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 9199:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 9200:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9201:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 9202:                       '<span>'.('&nbsp;'x2).
 9203:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9204:                       $lt{'udd'}.'</label><span></p>'.
 9205:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 9206:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 9207:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 9208:             foreach my $access (@accesstypes) {
 9209:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 9210:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 9211:                 if ($access eq 'status') {
 9212:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 9213:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 9214:                                                                         $othertitle,$usertypes,$types,$disabled).
 9215:                               '</div>');
 9216:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 9217:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 9218:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9219:                                                                  \%domhelpdesk,$disabled).
 9220:                               '</div>');
 9221:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 9222:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 9223:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9224:                                                                  \%domhelpdesk,$disabled).
 9225:                               '</div>');
 9226:                 }
 9227:                 $r->print('</p>');
 9228:             }
 9229:             $r->print('</div></fieldset>');
 9230:             my %full=();
 9231:             my %levels= (
 9232:                          course => {},
 9233:                          domain => {},
 9234:                          system => {},
 9235:                         );
 9236:             my %levelscurrent=(
 9237:                                course => {},
 9238:                                domain => {},
 9239:                                system => {},
 9240:                               );
 9241:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9242:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 9243:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 9244:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 9245:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 9246:         }
 9247:         if ($permission->{'owner'}) {
 9248:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 9249:         }
 9250:     } else {
 9251:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 9252:     }
 9253:     # Form Footer
 9254:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 9255:              .'</form>');
 9256:     return;
 9257: }
 9258: 
 9259: sub print_queued_roles {
 9260:     my ($r,$context,$permission,$brcrum) = @_;
 9261:     push (@{$brcrum},
 9262:              {href => '/adm/createuser?action=rolerequests',
 9263:               text => 'Role Requests (other domains)',
 9264:               help => ''});
 9265:     my $bread_crumbs_component = 'Role Requests';
 9266:     my $args = { bread_crumbs           => $brcrum,
 9267:                  bread_crumbs_component => $bread_crumbs_component};
 9268:     # print page header
 9269:     $r->print(&header('',$args));
 9270:     my ($dom,$cnum);
 9271:     $dom = $env{'request.role.domain'};
 9272:     if ($context eq 'course') {
 9273:         if ($env{'request.course.id'}) {
 9274:             if (&Apache::loncommon::course_type() eq 'Community') {
 9275:                 $context = 'community';
 9276:             }
 9277:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9278:         }
 9279:     } elsif ($context eq 'author') {
 9280:         $cnum = $env{'user.name'};
 9281:     }
 9282:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomqueue',$dom,$cnum,$context));
 9283:     return;
 9284: }
 9285: 
 9286: sub print_pendingroles {
 9287:     my ($r,$context,$permission,$brcrum) = @_;
 9288:     push (@{$brcrum},
 9289:              {href => '/adm/createuser?action=queuedroles',
 9290:               text => 'Queued Role Assignments (users in this domain)',
 9291:               help => ''});
 9292:     my $bread_crumbs_component = 'Queued Role Assignments';
 9293:     my $args = { bread_crumbs           => $brcrum,
 9294:                  bread_crumbs_component => $bread_crumbs_component};
 9295:     # print page header
 9296:     $r->print(&header('',$args));
 9297:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomaction',$env{'request.role.domain'},'','domain'));
 9298:     return;
 9299: }
 9300: 
 9301: sub process_pendingroles {
 9302:     my ($r,$context,$permission,$brcrum) = @_;
 9303:     push (@{$brcrum},
 9304:              {href => '/adm/createuser?action=queuedroles',
 9305:               text => 'Queued Role Assignments (users in this domain)',
 9306:               help => ''},
 9307:              {href => '/adm/createuser?action=processrolereq',
 9308:               text => 'Process Queue',
 9309:               help => ''});
 9310:     my $bread_crumbs_component = 'Queued Role Assignments';
 9311:     my $args = { bread_crumbs           => $brcrum,
 9312:                  bread_crumbs_component => $bread_crumbs_component};
 9313:     # print page header
 9314:     $r->print(&header('',$args));
 9315:     $r->print(&Apache::loncoursequeueadmin::update_request_queue('othdombydc',
 9316:                                                                  $env{'request.role.domain'}));
 9317:     return;
 9318: }
 9319: 
 9320: sub domain_adhoc_access {
 9321:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 9322:     my %domusage;
 9323:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 9324:     foreach my $role (keys(%{$roles})) {
 9325:         if (ref($domcurrent->{$role}) eq 'HASH') {
 9326:             my $access = $domcurrent->{$role}{'access'};
 9327:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 9328:                 $access = 'all';
 9329:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 9330:                                                                                           &Apache::lonnet::plaintext('da'));
 9331:             } elsif ($access eq 'status') {
 9332:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 9333:                     my @shown;
 9334:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 9335:                         unless ($type eq 'default') {
 9336:                             if ($usertypes->{$type}) {
 9337:                                 push(@shown,$usertypes->{$type});
 9338:                             }
 9339:                         }
 9340:                     }
 9341:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 9342:                         push(@shown,$othertitle);
 9343:                     }
 9344:                     if (@shown) {
 9345:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 9346:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 9347:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 9348:                     } else {
 9349:                         $domusage{$role} = &mt('No one in the domain');
 9350:                     }
 9351:                 }
 9352:             } elsif ($access eq 'inc') {
 9353:                 my @dominc = ();
 9354:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 9355:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 9356:                         my ($uname,$udom) = split(/:/,$user);
 9357:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9358:                     }
 9359:                     my $showninc = join(', ',@dominc);
 9360:                     if ($showninc ne '') {
 9361:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 9362:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 9363:                     } else {
 9364:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9365:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9366:                     }
 9367:                 }
 9368:             } elsif ($access eq 'exc') {
 9369:                 my @domexc = ();
 9370:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 9371:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 9372:                         my ($uname,$udom) = split(/:/,$user);
 9373:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9374:                     }
 9375:                 }
 9376:                 my $shownexc = join(', ',@domexc);
 9377:                 if ($shownexc ne '') {
 9378:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 9379:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 9380:                 } else {
 9381:                     $domusage{$role} = &mt('No one in the domain');
 9382:                 }
 9383:             } elsif ($access eq 'none') {
 9384:                 $domusage{$role} = &mt('No one in the domain');
 9385:             } elsif ($access eq 'dh') {
 9386:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 9387:             } elsif ($access eq 'da') {
 9388:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 9389:             } elsif ($access eq 'all') {
 9390:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9391:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9392:             }
 9393:         } else {
 9394:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9395:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9396:         }
 9397:     }
 9398:     return %domusage;
 9399: }
 9400: 
 9401: sub get_domain_customroles {
 9402:     my ($cdom,$confname) = @_;
 9403:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 9404:     my %customroles;
 9405:     foreach my $key (keys(%existing)) {
 9406:         if ($key=~/^rolesdef\_(\w+)$/) {
 9407:             my $rolename = $1;
 9408:             my %privs;
 9409:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 9410:             $customroles{$rolename} = \%privs;
 9411:         }
 9412:     }
 9413:     return %customroles;
 9414: }
 9415: 
 9416: sub role_priv_table {
 9417:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 9418:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 9419:                    (ref($levelscurrent) eq 'HASH'));
 9420:     my %lt=&Apache::lonlocal::texthash (
 9421:                     'crl'  => 'Course Level Privilege',
 9422:                     'def'  => 'Domain Defaults',
 9423:                     'ove'  => 'Override in Course',
 9424:                     'ine'  => 'In effect',
 9425:                     'dis'  => 'Disabled',
 9426:                     'ena'  => 'Enabled',
 9427:                    );
 9428:     if ($crstype eq 'Community') {
 9429:         $lt{'ove'} = 'Override in Community',
 9430:     }
 9431:     my @status = ('Disabled','Enabled');
 9432:     my (%on,%off);
 9433:     if (ref($overridden) eq 'HASH') {
 9434:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 9435:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 9436:         }
 9437:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 9438:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 9439:         }
 9440:     }
 9441:     my $output=&Apache::loncommon::start_data_table().
 9442:                &Apache::loncommon::start_data_table_header_row().
 9443:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 9444:                '</th><th>'.$lt{'ine'}.'</th>'.
 9445:                &Apache::loncommon::end_data_table_header_row();
 9446:     foreach my $priv (sort(keys(%{$full}))) {
 9447:         next unless ($levels->{'course'}{$priv});
 9448:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 9449:         my ($default,$ineffect);
 9450:         if ($levelscurrent->{'course'}{$priv}) {
 9451:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9452:             $ineffect = $default;
 9453:         }
 9454:         my ($customstatus,$checked);
 9455:         $output .= &Apache::loncommon::start_data_table_row().
 9456:                    '<td>'.$privtext.'</td>'.
 9457:                    '<td>'.$default.'</td><td>';
 9458:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 9459:             if ($permission->{'owner'}) {
 9460:                 $checked = ' checked="checked"';
 9461:             }
 9462:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 9463:             $ineffect = $customstatus;
 9464:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 9465:             if ($permission->{'owner'}) {
 9466:                 $checked = ' checked="checked"';
 9467:             }
 9468:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9469:             $ineffect = $customstatus;
 9470:         }
 9471:         if ($permission->{'owner'}) {
 9472:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 9473:         } else {
 9474:             $output .= $customstatus;
 9475:         }
 9476:         $output .= '</td><td>'.$ineffect.'</td>'.
 9477:                    &Apache::loncommon::end_data_table_row();
 9478:     }
 9479:     $output .= &Apache::loncommon::end_data_table();
 9480:     return $output;
 9481: }
 9482: 
 9483: sub get_adhocrole_settings {
 9484:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 9485:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 9486:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 9487:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 9488:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 9489:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 9490:             $settings->{$role}{'access'} = $curraccess;
 9491:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 9492:                 my @status = split(/,/,$rest);
 9493:                 my @currstatus;
 9494:                 foreach my $type (@status) {
 9495:                     if ($type eq 'default') {
 9496:                         push(@currstatus,$type);
 9497:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9498:                         push(@currstatus,$type);
 9499:                     }
 9500:                 }
 9501:                 if (@currstatus) {
 9502:                     $settings->{$role}{$curraccess} = \@currstatus;
 9503:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 9504:                     my @personnel = split(/,/,$rest);
 9505:                     $settings->{$role}{$curraccess} = \@personnel;
 9506:                 }
 9507:             }
 9508:         }
 9509:     }
 9510:     foreach my $role (keys(%{$customroles})) {
 9511:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 9512:             my %currentprivs;
 9513:             if (ref($customroles->{$role}) eq 'HASH') {
 9514:                 if (exists($customroles->{$role}{'course'})) {
 9515:                     my %full=();
 9516:                     my %levels= (
 9517:                                   course => {},
 9518:                                   domain => {},
 9519:                                   system => {},
 9520:                                 );
 9521:                     my %levelscurrent=(
 9522:                                         course => {},
 9523:                                         domain => {},
 9524:                                         system => {},
 9525:                                       );
 9526:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 9527:                     %currentprivs = %{$levelscurrent{'course'}};
 9528:                 }
 9529:             }
 9530:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 9531:                 next if ($item eq '');
 9532:                 my ($rule,$rest) = split(/=/,$item);
 9533:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 9534:                 foreach my $priv (split(/:/,$rest)) {
 9535:                     if ($priv ne '') {
 9536:                         if ($rule eq 'off') {
 9537:                             push(@{$overridden->{$role}{'off'}},$priv);
 9538:                             if ($currentprivs{$priv}) {
 9539:                                 push(@{$settings->{$role}{'off'}},$priv);
 9540:                             }
 9541:                         } else {
 9542:                             push(@{$overridden->{$role}{'on'}},$priv);
 9543:                             unless ($currentprivs{$priv}) {
 9544:                                 push(@{$settings->{$role}{'on'}},$priv);
 9545:                             }
 9546:                         }
 9547:                     }
 9548:                 }
 9549:             }
 9550:         }
 9551:     }
 9552:     return;
 9553: }
 9554: 
 9555: sub update_helpdeskaccess {
 9556:     my ($r,$permission,$brcrum) = @_;
 9557:     my $helpitem = 'Course_Helpdesk_Access';
 9558:     push (@{$brcrum},
 9559:              {href => '/adm/createuser?action=helpdesk',
 9560:               text => 'Helpdesk Access',
 9561:               help => $helpitem},
 9562:              {href => '/adm/createuser?action=helpdesk',
 9563:               text => 'Result',
 9564:               help => $helpitem}
 9565:          );
 9566:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 9567:     my $args = { bread_crumbs           => $brcrum,
 9568:                  bread_crumbs_component => $bread_crumbs_component};
 9569: 
 9570:     # print page header
 9571:     $r->print(&header('',$args));
 9572:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 9573:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 9574:         return;
 9575:     }
 9576:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 9577:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9578:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9579:     my $confname = $cdom.'-domainconfig';
 9580:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 9581:     my $crstype = &Apache::loncommon::course_type();
 9582:     my %customroles = &get_domain_customroles($cdom,$confname);
 9583:     my (%settings,%overridden);
 9584:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 9585:                             $types,\%customroles,\%settings,\%overridden);
 9586:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 9587:     my (%changed,%storehash,@todelete);
 9588: 
 9589:     if (keys(%customroles)) {
 9590:         my (%newsettings,@incrs);
 9591:         foreach my $role (keys(%customroles)) {
 9592:             $newsettings{$role} = {
 9593:                                     access => '',
 9594:                                     status => '',
 9595:                                     exc    => '',
 9596:                                     inc    => '',
 9597:                                     on     => '',
 9598:                                     off    => '',
 9599:                                   };
 9600:             my %current;
 9601:             if (ref($settings{$role}) eq 'HASH') {
 9602:                 %current = %{$settings{$role}};
 9603:             }
 9604:             if (ref($overridden{$role}) eq 'HASH') {
 9605:                 $current{'overridden'} = $overridden{$role};
 9606:             }
 9607:             if ($env{'form.'.$role.'_incrs'}) {
 9608:                 my $access = $env{'form.'.$role.'_access'};
 9609:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 9610:                     push(@incrs,$role);
 9611:                     unless ($current{'access'} eq $access) {
 9612:                         $changed{$role}{'access'} = 1;
 9613:                         $storehash{'internal.adhoc.'.$role} = $access;
 9614:                     }
 9615:                     if ($access eq 'status') {
 9616:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 9617:                         my @stored;
 9618:                         my @shownstatus;
 9619:                         if (ref($types) eq 'ARRAY') {
 9620:                             foreach my $type (sort(@statuses)) {
 9621:                                 if ($type eq 'default') {
 9622:                                     push(@stored,$type);
 9623:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9624:                                     push(@stored,$type);
 9625:                                     push(@shownstatus,$usertypes->{$type});
 9626:                                 }
 9627:                             }
 9628:                             if (grep(/^default$/,@statuses)) {
 9629:                                 push(@shownstatus,$othertitle);
 9630:                             }
 9631:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9632:                         }
 9633:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 9634:                         if (ref($current{'status'}) eq 'ARRAY') {
 9635:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 9636:                             if (@diffs) {
 9637:                                 $changed{$role}{'status'} = 1;
 9638:                             }
 9639:                         } elsif (@stored) {
 9640:                             $changed{$role}{'status'} = 1;
 9641:                         }
 9642:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 9643:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 9644:                         my @newspecstaff;
 9645:                         my @stored;
 9646:                         my @currstaff;
 9647:                         foreach my $person (sort(@personnel)) {
 9648:                             if ($domhelpdesk{$person}) {
 9649:                                 push(@stored,$person);
 9650:                             }
 9651:                         }
 9652:                         if (ref($current{$access}) eq 'ARRAY') {
 9653:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 9654:                             if (@diffs) {
 9655:                                 $changed{$role}{$access} = 1;
 9656:                             }
 9657:                         } elsif (@stored) {
 9658:                             $changed{$role}{$access} = 1;
 9659:                         }
 9660:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9661:                         foreach my $person (@stored) {
 9662:                             my ($uname,$udom) = split(/:/,$person);
 9663:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 9664:                         }
 9665:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 9666:                     }
 9667:                     $newsettings{$role}{'access'} = $access;
 9668:                 }
 9669:             } else {
 9670:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 9671:                     $changed{$role}{'access'} = 1;
 9672:                     $newsettings{$role} = {};
 9673:                     push(@todelete,'internal.adhoc.'.$role);
 9674:                 }
 9675:             }
 9676:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 9677:                 if (ref($current{'overridden'}) eq 'HASH') {
 9678:                     push(@todelete,'internal.adhocpriv.'.$role);
 9679:                 }
 9680:             } else {
 9681:                 my %full=();
 9682:                 my %levels= (
 9683:                              course => {},
 9684:                              domain => {},
 9685:                              system => {},
 9686:                             );
 9687:                 my %levelscurrent=(
 9688:                                    course => {},
 9689:                                    domain => {},
 9690:                                    system => {},
 9691:                                   );
 9692:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9693:                 my (@updatedon,@updatedoff,@override);
 9694:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 9695:                 if (@override) {
 9696:                     foreach my $priv (sort(keys(%full))) {
 9697:                         next unless ($levels{'course'}{$priv});
 9698:                         if (grep(/^\Q$priv\E$/,@override)) {
 9699:                             if ($levelscurrent{'course'}{$priv}) {
 9700:                                 push(@updatedoff,$priv);
 9701:                             } else {
 9702:                                 push(@updatedon,$priv);
 9703:                             }
 9704:                         }
 9705:                     }
 9706:                 }
 9707:                 if (@updatedon) {
 9708:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 9709:                 }
 9710:                 if (@updatedoff) {
 9711:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 9712:                 }
 9713:                 if (ref($current{'overridden'}) eq 'HASH') {
 9714:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 9715:                         if (@updatedon) {
 9716:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 9717:                             if (@diffs) {
 9718:                                 $changed{$role}{'on'} = 1;
 9719:                             }
 9720:                         } else {
 9721:                             $changed{$role}{'on'} = 1;
 9722:                         }
 9723:                     } elsif (@updatedon) {
 9724:                         $changed{$role}{'on'} = 1;
 9725:                     }
 9726:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 9727:                         if (@updatedoff) {
 9728:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 9729:                             if (@diffs) {
 9730:                                 $changed{$role}{'off'} = 1;
 9731:                             }
 9732:                         } else {
 9733:                             $changed{$role}{'off'} = 1;
 9734:                         }
 9735:                     } elsif (@updatedoff) {
 9736:                         $changed{$role}{'off'} = 1;
 9737:                     }
 9738:                 } else {
 9739:                     if (@updatedon) {
 9740:                         $changed{$role}{'on'} = 1;
 9741:                     }
 9742:                     if (@updatedoff) {
 9743:                         $changed{$role}{'off'} = 1;
 9744:                     }
 9745:                 }
 9746:                 if (ref($changed{$role}) eq 'HASH') {
 9747:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 9748:                         my $newpriv;
 9749:                         if (@updatedon) {
 9750:                             $newpriv = 'on='.join(':',@updatedon);
 9751:                         }
 9752:                         if (@updatedoff) {
 9753:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 9754:                         }
 9755:                         if ($newpriv eq '') {
 9756:                             push(@todelete,'internal.adhocpriv.'.$role);
 9757:                         } else {
 9758:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 9759:                         }
 9760:                     }
 9761:                 }
 9762:             }
 9763:         }
 9764:         if (@incrs) {
 9765:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 9766:         } elsif (@todelete) {
 9767:             push(@todelete,'internal.adhocaccess');
 9768:         }
 9769:         if (keys(%changed)) {
 9770:             my ($putres,$delres);
 9771:             if (keys(%storehash)) {
 9772:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 9773:                 my %newenvhash;
 9774:                 foreach my $key (keys(%storehash)) {
 9775:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 9776:                 }
 9777:                 &Apache::lonnet::appenv(\%newenvhash);
 9778:             }
 9779:             if (@todelete) {
 9780:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 9781:                 foreach my $key (@todelete) {
 9782:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 9783:                 }
 9784:             }
 9785:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 9786:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9787:                 my (%domcurrent,%ordered,%description,%domusage);
 9788:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9789:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9790:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9791:                     }
 9792:                 }
 9793:                 my $count = 0;
 9794:                 foreach my $role (sort(keys(%customroles))) {
 9795:                     my ($order,$desc);
 9796:                     if (ref($domcurrent{$role}) eq 'HASH') {
 9797:                         $order = $domcurrent{$role}{'order'};
 9798:                         $desc = $domcurrent{$role}{'desc'};
 9799:                     }
 9800:                     if ($order eq '') {
 9801:                         $order = $count;
 9802:                     }
 9803:                     $ordered{$order} = $role;
 9804:                     if ($desc ne '') {
 9805:                         $description{$role} = $desc;
 9806:                     } else {
 9807:                         $description{$role}= $role;
 9808:                     }
 9809:                     $count++;
 9810:                 }
 9811:                 my @roles_by_num = ();
 9812:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9813:                     push(@roles_by_num,$ordered{$item});
 9814:                 }
 9815:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9816:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 9817:                 $r->print('<ul>');
 9818:                 foreach my $role (@roles_by_num) {
 9819:                     next unless (ref($changed{$role}) eq 'HASH');
 9820:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 9821:                               '<ul>');
 9822:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 9823:                         $r->print('<li>');
 9824:                         if ($env{'form.'.$role.'_incrs'}) {
 9825:                             if ($newsettings{$role}{'access'} eq 'all') {
 9826:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 9827:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 9828:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9829:                                               &Apache::lonnet::plaintext('dh')));
 9830:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 9831:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9832:                                               &Apache::lonnet::plaintext('da')));
 9833:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 9834:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9835:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 9836:                                 if ($newsettings{$role}{'status'}) {
 9837:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 9838:                                     if (split(/,/,$rest) > 1) {
 9839:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 9840:                                                       $newsettings{$role}{'status'}));
 9841:                                     } else {
 9842:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 9843:                                                       $newsettings{$role}{'status'}));
 9844:                                     }
 9845:                                 } else {
 9846:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9847:                                 }
 9848:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 9849:                                 if ($newsettings{$role}{'exc'}) {
 9850:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 9851:                                 } else {
 9852:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9853:                                 }
 9854:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 9855:                                 if ($newsettings{$role}{'inc'}) {
 9856:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 9857:                                 } else {
 9858:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 9859:                                 }
 9860:                             }
 9861:                         } else {
 9862:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 9863:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 9864:                         }
 9865:                         $r->print('</li>');
 9866:                     }
 9867:                     unless ($newsettings{$role}{'access'} eq 'none') {
 9868:                         if ($changed{$role}{'off'}) {
 9869:                             if ($newsettings{$role}{'off'}) {
 9870:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 9871:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 9872:                             } else {
 9873:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 9874:                             }
 9875:                         }
 9876:                         if ($changed{$role}{'on'}) {
 9877:                             if ($newsettings{$role}{'on'}) {
 9878:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 9879:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 9880:                             } else {
 9881:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 9882:                             }
 9883:                         }
 9884:                     }
 9885:                     $r->print('</ul></li>');
 9886:                 }
 9887:                 $r->print('</ul>');
 9888:             }
 9889:         } else {
 9890:             $r->print(&mt('No changes made to helpdesk access settings.'));
 9891:         }
 9892:     }
 9893:     return;
 9894: }
 9895: 
 9896: #-------------------------------------------------- functions for &phase_two
 9897: sub user_search_result {
 9898:     my ($context,$srch) = @_;
 9899:     my %allhomes;
 9900:     my %inst_matches;
 9901:     my %srch_results;
 9902:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 9903:     $srch->{'srchterm'} =~ s/\s+/ /g;
 9904:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 9905:         $response = &mt('Invalid search.');
 9906:     }
 9907:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 9908:         $response = &mt('Invalid search.');
 9909:     }
 9910:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 9911:         $response = &mt('Invalid search.');
 9912:     }
 9913:     if ($srch->{'srchterm'} eq '') {
 9914:         $response = &mt('You must enter a search term.');
 9915:     }
 9916:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 9917:         $response = &mt('Your search term must contain more than just spaces.');
 9918:     }
 9919:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 9920:         if (($srch->{'srchdomain'} eq '') || 
 9921: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 9922:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 9923:         }
 9924:     }
 9925:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 9926:         ($srch->{'srchin'} eq 'alc')) {
 9927:         if ($srch->{'srchby'} eq 'uname') {
 9928:             my $unamecheck = $srch->{'srchterm'};
 9929:             if ($srch->{'srchtype'} eq 'contains') {
 9930:                 if ($unamecheck !~ /^\w/) {
 9931:                     $unamecheck = 'a'.$unamecheck; 
 9932:                 }
 9933:             }
 9934:             if ($unamecheck !~ /^$match_username$/) {
 9935:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 9936:             }
 9937:         }
 9938:     }
 9939:     if ($response ne '') {
 9940:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 9941:     }
 9942:     if ($srch->{'srchin'} eq 'instd') {
 9943:         my $instd_chk = &instdirectorysrch_check($srch);
 9944:         if ($instd_chk ne 'ok') {
 9945:             my $domd_chk = &domdirectorysrch_check($srch);
 9946:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 9947:             if ($domd_chk eq 'ok') {
 9948:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 9949:             }
 9950:             $response .= '<br />';
 9951:         }
 9952:     } else {
 9953:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 9954:             my $domd_chk = &domdirectorysrch_check($srch);
 9955:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 9956:                 my $instd_chk = &instdirectorysrch_check($srch);
 9957:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 9958:                 if ($instd_chk eq 'ok') {
 9959:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 9960:                 }
 9961:                 $response .= '<br />';
 9962:             }
 9963:         }
 9964:     }
 9965:     if ($response ne '') {
 9966:         return ($currstate,$response);
 9967:     }
 9968:     if ($srch->{'srchby'} eq 'uname') {
 9969:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 9970:             if ($env{'form.forcenew'}) {
 9971:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 9972:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9973:                     if ($uhome eq 'no_host') {
 9974:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 9975:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 9976:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 9977:                     } else {
 9978:                         $currstate = 'modify';
 9979:                     }
 9980:                 } else {
 9981:                     $currstate = 'modify';
 9982:                 }
 9983:             } else {
 9984:                 if ($srch->{'srchin'} eq 'dom') {
 9985:                     if ($srch->{'srchtype'} eq 'exact') {
 9986:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9987:                         if ($uhome eq 'no_host') {
 9988:                             ($currstate,$response,$forcenewuser) =
 9989:                                 &build_search_response($context,$srch,%srch_results);
 9990:                         } else {
 9991:                             $currstate = 'modify';
 9992:                             if ($env{'form.action'} eq 'accesslogs') {
 9993:                                 $currstate = 'activity';
 9994:                             }
 9995:                             my $uname = $srch->{'srchterm'};
 9996:                             my $udom = $srch->{'srchdomain'};
 9997:                             $srch_results{$uname.':'.$udom} =
 9998:                                 { &Apache::lonnet::get('environment',
 9999:                                                        ['firstname',
10000:                                                         'lastname',
10001:                                                         'permanentemail'],
10002:                                                          $udom,$uname)
10003:                                 };
10004:                         }
10005:                     } else {
10006:                         %srch_results = &Apache::lonnet::usersearch($srch);
10007:                         ($currstate,$response,$forcenewuser) =
10008:                             &build_search_response($context,$srch,%srch_results);
10009:                     }
10010:                 } else {
10011:                     my $courseusers = &get_courseusers();
10012:                     if ($srch->{'srchtype'} eq 'exact') {
10013:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
10014:                             $currstate = 'modify';
10015:                         } else {
10016:                             ($currstate,$response,$forcenewuser) =
10017:                                 &build_search_response($context,$srch,%srch_results);
10018:                         }
10019:                     } else {
10020:                         foreach my $user (keys(%$courseusers)) {
10021:                             my ($cuname,$cudomain) = split(/:/,$user);
10022:                             if ($cudomain eq $srch->{'srchdomain'}) {
10023:                                 my $matched = 0;
10024:                                 if ($srch->{'srchtype'} eq 'begins') {
10025:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
10026:                                         $matched = 1;
10027:                                     }
10028:                                 } else {
10029:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
10030:                                         $matched = 1;
10031:                                     }
10032:                                 }
10033:                                 if ($matched) {
10034:                                     $srch_results{$user} = 
10035: 					{&Apache::lonnet::get('environment',
10036: 							     ['firstname',
10037: 							      'lastname',
10038: 							      'permanentemail'],
10039: 							      $cudomain,$cuname)};
10040:                                 }
10041:                             }
10042:                         }
10043:                         ($currstate,$response,$forcenewuser) =
10044:                             &build_search_response($context,$srch,%srch_results);
10045:                     }
10046:                 }
10047:             }
10048:         } elsif ($srch->{'srchin'} eq 'alc') {
10049:             $currstate = 'query';
10050:         } elsif ($srch->{'srchin'} eq 'instd') {
10051:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
10052:             if ($dirsrchres eq 'ok') {
10053:                 ($currstate,$response,$forcenewuser) = 
10054:                     &build_search_response($context,$srch,%srch_results);
10055:             } else {
10056:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
10057:                 $response = '<span class="LC_warning">'.
10058:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
10059:                     '</span><br />'.
10060:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
10061:                     '<br />'; 
10062:             }
10063:         }
10064:     } else {
10065:         if ($srch->{'srchin'} eq 'dom') {
10066:             %srch_results = &Apache::lonnet::usersearch($srch);
10067:             ($currstate,$response,$forcenewuser) = 
10068:                 &build_search_response($context,$srch,%srch_results); 
10069:         } elsif ($srch->{'srchin'} eq 'crs') {
10070:             my $courseusers = &get_courseusers(); 
10071:             foreach my $user (keys(%$courseusers)) {
10072:                 my ($uname,$udom) = split(/:/,$user);
10073:                 my %names = &Apache::loncommon::getnames($uname,$udom);
10074:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
10075:                 if ($srch->{'srchby'} eq 'lastname') {
10076:                     if ((($srch->{'srchtype'} eq 'exact') && 
10077:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
10078:                         (($srch->{'srchtype'} eq 'begins') &&
10079:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
10080:                         (($srch->{'srchtype'} eq 'contains') &&
10081:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
10082:                         $srch_results{$user} = {firstname => $names{'firstname'},
10083:                                             lastname => $names{'lastname'},
10084:                                             permanentemail => $emails{'permanentemail'},
10085:                                            };
10086:                     }
10087:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
10088:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
10089:                     $srchlast =~ s/\s+$//;
10090:                     $srchfirst =~ s/^\s+//;
10091:                     if ($srch->{'srchtype'} eq 'exact') {
10092:                         if (($names{'lastname'} eq $srchlast) &&
10093:                             ($names{'firstname'} eq $srchfirst)) {
10094:                             $srch_results{$user} = {firstname => $names{'firstname'},
10095:                                                 lastname => $names{'lastname'},
10096:                                                 permanentemail => $emails{'permanentemail'},
10097: 
10098:                                            };
10099:                         }
10100:                     } elsif ($srch->{'srchtype'} eq 'begins') {
10101:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
10102:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
10103:                             $srch_results{$user} = {firstname => $names{'firstname'},
10104:                                                 lastname => $names{'lastname'},
10105:                                                 permanentemail => $emails{'permanentemail'},
10106:                                                };
10107:                         }
10108:                     } else {
10109:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
10110:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
10111:                             $srch_results{$user} = {firstname => $names{'firstname'},
10112:                                                 lastname => $names{'lastname'},
10113:                                                 permanentemail => $emails{'permanentemail'},
10114:                                                };
10115:                         }
10116:                     }
10117:                 }
10118:             }
10119:             ($currstate,$response,$forcenewuser) = 
10120:                 &build_search_response($context,$srch,%srch_results); 
10121:         } elsif ($srch->{'srchin'} eq 'alc') {
10122:             $currstate = 'query';
10123:         } elsif ($srch->{'srchin'} eq 'instd') {
10124:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
10125:             if ($dirsrchres eq 'ok') {
10126:                 ($currstate,$response,$forcenewuser) = 
10127:                     &build_search_response($context,$srch,%srch_results);
10128:             } else {
10129:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
10130:                 $response = '<span class="LC_warning">'.
10131:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
10132:                     '</span><br />'.
10133:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
10134:                     '<br />';
10135:             }
10136:         }
10137:     }
10138:     return ($currstate,$response,$forcenewuser,\%srch_results);
10139: }
10140: 
10141: sub domdirectorysrch_check {
10142:     my ($srch) = @_;
10143:     my $response;
10144:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10145:                                              ['directorysrch'],$srch->{'srchdomain'});
10146:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10147:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10148:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
10149:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
10150:         }
10151:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
10152:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10153:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
10154:             }
10155:         }
10156:     }
10157:     return 'ok';
10158: }
10159: 
10160: sub instdirectorysrch_check {
10161:     my ($srch) = @_;
10162:     my $can_search = 0;
10163:     my $response;
10164:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10165:                                              ['directorysrch'],$srch->{'srchdomain'});
10166:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10167:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10168:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
10169:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
10170:         }
10171:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
10172:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10173:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
10174:             }
10175:             my @usertypes = split(/:/,$env{'environment.inststatus'});
10176:             if (!@usertypes) {
10177:                 push(@usertypes,'default');
10178:             }
10179:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
10180:                 foreach my $type (@usertypes) {
10181:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
10182:                         $can_search = 1;
10183:                         last;
10184:                     }
10185:                 }
10186:             }
10187:             if (!$can_search) {
10188:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
10189:                 my @longtypes; 
10190:                 foreach my $item (@usertypes) {
10191:                     if (defined($insttypes->{$item})) { 
10192:                         push (@longtypes,$insttypes->{$item});
10193:                     } elsif ($item eq 'default') {
10194:                         push (@longtypes,&mt('other')); 
10195:                     }
10196:                 }
10197:                 my $insttype_str = join(', ',@longtypes); 
10198:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
10199:             }
10200:         } else {
10201:             $can_search = 1;
10202:         }
10203:     } else {
10204:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
10205:     }
10206:     my %longtext = &Apache::lonlocal::texthash (
10207:                        uname     => 'username',
10208:                        lastfirst => 'last name, first name',
10209:                        lastname  => 'last name',
10210:                        contains  => 'contains',
10211:                        exact     => 'as exact match to',
10212:                        begins    => 'begins with',
10213:                    );
10214:     if ($can_search) {
10215:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
10216:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
10217:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
10218:             }
10219:         } else {
10220:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
10221:         }
10222:     }
10223:     if ($can_search) {
10224:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
10225:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
10226:                 return 'ok';
10227:             } else {
10228:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10229:             }
10230:         } else {
10231:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
10232:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
10233:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
10234:                 return 'ok';
10235:             } else {
10236:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10237:             }
10238:         }
10239:     }
10240: }
10241: 
10242: sub get_courseusers {
10243:     my %advhash;
10244:     my $classlist = &Apache::loncoursedata::get_classlist();
10245:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
10246:     foreach my $role (sort(keys(%coursepersonnel))) {
10247:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
10248: 	    if (!exists($classlist->{$user})) {
10249: 		$classlist->{$user} = [];
10250: 	    }
10251:         }
10252:     }
10253:     return $classlist;
10254: }
10255: 
10256: sub build_search_response {
10257:     my ($context,$srch,%srch_results) = @_;
10258:     my ($currstate,$response,$forcenewuser);
10259:     my %names = (
10260:           'uname'     => 'username',
10261:           'lastname'  => 'last name',
10262:           'lastfirst' => 'last name, first name',
10263:           'crs'       => 'this course',
10264:           'dom'       => 'LON-CAPA domain',
10265:           'instd'     => 'the institutional directory for domain',
10266:     );
10267: 
10268:     my %single = (
10269:                    begins   => 'A match',
10270:                    contains => 'A match',
10271:                    exact    => 'An exact match',
10272:                  );
10273:     my %nomatch = (
10274:                    begins   => 'No match',
10275:                    contains => 'No match',
10276:                    exact    => 'No exact match',
10277:                   );
10278:     if (keys(%srch_results) > 1) {
10279:         $currstate = 'select';
10280:     } else {
10281:         if (keys(%srch_results) == 1) {
10282:             if ($env{'form.action'} eq 'accesslogs') {
10283:                 $currstate = 'activity';
10284:             } else {
10285:                 $currstate = 'modify';
10286:             }
10287:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
10288:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10289:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
10290:             }
10291:         } else { # Search has nothing found. Prepare message to user.
10292:             $response = '<span class="LC_warning">';
10293:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10294:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
10295:                                  '<b>'.$srch->{'srchterm'}.'</b>',
10296:                                  &display_domain_info($srch->{'srchdomain'}));
10297:             } else {
10298:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
10299:                                  '<b>'.$srch->{'srchterm'}.'</b>');
10300:             }
10301:             $response .= '</span>';
10302: 
10303:             if ($srch->{'srchin'} ne 'alc') {
10304:                 $forcenewuser = 1;
10305:                 my $cansrchinst = 0; 
10306:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
10307:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
10308:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
10309:                         if ($domconfig{'directorysrch'}{'available'}) {
10310:                             $cansrchinst = 1;
10311:                         } 
10312:                     }
10313:                 }
10314:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
10315:                      ($srch->{'srchby'} eq 'lastname')) &&
10316:                     ($srch->{'srchin'} eq 'dom')) {
10317:                     if ($cansrchinst) {
10318:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
10319:                     }
10320:                 }
10321:                 if ($srch->{'srchin'} eq 'crs') {
10322:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
10323:                 }
10324:             }
10325:             my $createdom = $env{'request.role.domain'};
10326:             if ($context eq 'requestcrs') {
10327:                 if ($env{'form.coursedom'} ne '') {
10328:                     $createdom = $env{'form.coursedom'};
10329:                 }
10330:             }
10331:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
10332:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
10333:                 my $cancreate =
10334:                     &Apache::lonuserutils::can_create_user($createdom,$context);
10335:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
10336:                 if ($cancreate) {
10337:                     my $showdom = &display_domain_info($createdom); 
10338:                     $response .= '<br /><br />'
10339:                                 .'<b>'.&mt('To add a new user:').'</b>'
10340:                                 .'<br />';
10341:                     if ($context eq 'requestcrs') {
10342:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
10343:                     } else {
10344:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
10345:                     }
10346:                     $response .='<ul><li>'
10347:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
10348:                                 .'</li><li>'
10349:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
10350:                                 .'</li><li>'
10351:                                 .&mt('Provide the proposed username')
10352:                                 .'</li><li>'
10353:                                 .&mt("Click 'Search'")
10354:                                 .'</li></ul><br />';
10355:                 } else {
10356:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
10357:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
10358:                         $response .= '<br /><br />';
10359:                         if ($context eq 'requestcrs') {
10360:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
10361:                         } else {
10362:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
10363:                         }
10364:                         $response .= '<br />'
10365:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
10366:                                         ,' <a'.$helplink.'>'
10367:                                         ,'</a>')
10368:                                      .'<br />';
10369:                     }
10370:                 }
10371:             }
10372:         }
10373:     }
10374:     return ($currstate,$response,$forcenewuser);
10375: }
10376: 
10377: sub display_domain_info {
10378:     my ($dom) = @_;
10379:     my $output = $dom;
10380:     if ($dom ne '') { 
10381:         my $domdesc = &Apache::lonnet::domain($dom,'description');
10382:         if ($domdesc ne '') {
10383:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
10384:         }
10385:     }
10386:     return $output;
10387: }
10388: 
10389: sub crumb_utilities {
10390:     my %elements = (
10391:        crtuser => {
10392:            srchterm => 'text',
10393:            srchin => 'selectbox',
10394:            srchby => 'selectbox',
10395:            srchtype => 'selectbox',
10396:            srchdomain => 'selectbox',
10397:        },
10398:        crtusername => {
10399:            srchterm => 'text',
10400:            srchdomain => 'selectbox',
10401:        },
10402:        docustom => {
10403:            rolename => 'selectbox',
10404:            newrolename => 'textbox',
10405:        },
10406:        studentform => {
10407:            srchterm => 'text',
10408:            srchin => 'selectbox',
10409:            srchby => 'selectbox',
10410:            srchtype => 'selectbox',
10411:            srchdomain => 'selectbox',
10412:        },
10413:     );
10414: 
10415:     my $jsback .= qq|
10416: function backPage(formname,prevphase,prevstate) {
10417:     if (typeof prevphase == 'undefined') {
10418:         formname.phase.value = '';
10419:     }
10420:     else {  
10421:         formname.phase.value = prevphase;
10422:     }
10423:     if (typeof prevstate == 'undefined') {
10424:         formname.currstate.value = '';
10425:     }
10426:     else {
10427:         formname.currstate.value = prevstate;
10428:     }
10429:     formname.submit();
10430: }
10431: |;
10432:     return ($jsback,\%elements);
10433: }
10434: 
10435: sub course_level_table {
10436:     my ($inccourses,$showcredits,$defaultcredits) = @_;
10437:     return unless (ref($inccourses) eq 'HASH');
10438:     my $table = '';
10439: # Custom Roles?
10440: 
10441:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10442:     my %lt=&Apache::lonlocal::texthash(
10443:             'exs'  => "Existing sections",
10444:             'new'  => "Define new section",
10445:             'ssd'  => "Set Start Date",
10446:             'sed'  => "Set End Date",
10447:             'crl'  => "Course Level",
10448:             'act'  => "Activate",
10449:             'rol'  => "Role",
10450:             'ext'  => "Extent",
10451:             'grs'  => "Section",
10452:             'crd'  => "Credits",
10453:             'sta'  => "Start",
10454:             'end'  => "End"
10455:     );
10456: 
10457:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
10458: 	my $thiscourse=$protectedcourse;
10459: 	$thiscourse=~s:_:/:g;
10460: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
10461:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
10462: 	my $area=$coursedata{'description'};
10463:         my $crstype=$coursedata{'type'};
10464: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
10465: 	my ($domain,$cnum)=split(/\//,$thiscourse);
10466:         my %sections_count;
10467:         if (defined($env{'request.course.id'})) {
10468:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
10469:                 %sections_count = 
10470: 		    &Apache::loncommon::get_sections($domain,$cnum);
10471:             }
10472:         }
10473:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
10474: 	foreach my $role (@roles) {
10475:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
10476: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
10477:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
10478:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10479:                                             $plrole,\%sections_count,\%lt,
10480:                                             $showcredits,$defaultcredits,$crstype);
10481:             } elsif ($env{'request.course.sec'} ne '') {
10482:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
10483:                                              $env{'request.course.sec'})) {
10484:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10485:                                                 $plrole,\%sections_count,\%lt,
10486:                                                 $showcredits,$defaultcredits,$crstype);
10487:                 }
10488:             }
10489:         }
10490:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
10491:             foreach my $cust (sort(keys(%customroles))) {
10492:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
10493:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
10494:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10495:                                             $cust,\%sections_count,\%lt,
10496:                                             $showcredits,$defaultcredits,$crstype);
10497:             }
10498: 	}
10499:     }
10500:     return '' if ($table eq ''); # return nothing if there is nothing 
10501:                                  # in the table
10502:     my $result;
10503:     if (!$env{'request.course.id'}) {
10504:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
10505:     }
10506:     $result .= 
10507: &Apache::loncommon::start_data_table().
10508: &Apache::loncommon::start_data_table_header_row().
10509: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10510: '<th>'.$lt{'ext'}.'</th><th>'."\n";
10511:     if ($showcredits) {
10512:         $result .= $lt{'crd'}.'</th>';
10513:     }
10514:     $result .=
10515: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
10516: '<th>'.$lt{'end'}.'</th>'.
10517: &Apache::loncommon::end_data_table_header_row().
10518: $table.
10519: &Apache::loncommon::end_data_table();
10520:     return $result;
10521: }
10522: 
10523: sub course_level_row {
10524:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
10525:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
10526:     my $creditem;
10527:     my $row = &Apache::loncommon::start_data_table_row().
10528:               ' <td><input type="checkbox" name="act_'.
10529:               $protectedcourse.'_'.$role.'" /></td>'."\n".
10530:               ' <td>'.$plrole.'</td>'."\n".
10531:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
10532:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
10533:         $row .= 
10534:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
10535:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
10536:     } else {
10537:         $row .= '<td>&nbsp;</td>';
10538:     }
10539:     if (($role eq 'cc') || ($role eq 'co')) {
10540:         $row .= '<td>&nbsp;</td>';
10541:     } elsif ($env{'request.course.sec'} ne '') {
10542:         $row .= ' <td><input type="hidden" value="'.
10543:                 $env{'request.course.sec'}.'" '.
10544:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
10545:                 $env{'request.course.sec'}.'</td>';
10546:     } else {
10547:         if (ref($sections_count) eq 'HASH') {
10548:             my $currsec = 
10549:                 &Apache::lonuserutils::course_sections($sections_count,
10550:                                                        $protectedcourse.'_'.$role);
10551:             $row .= '<td><table class="LC_createuser">'."\n".
10552:                     '<tr class="LC_section_row">'."\n".
10553:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
10554:                        $currsec.'</td>'."\n".
10555:                      ' <td>&nbsp;&nbsp;</td>'."\n".
10556:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
10557:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
10558:                      '" value="" />'.
10559:                      '<input type="hidden" '.
10560:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
10561:                      '</tr></table></td>'."\n";
10562:         } else {
10563:             $row .= '<td><input type="text" size="10" '.
10564:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
10565:         }
10566:     }
10567:     $row .= <<ENDTIMEENTRY;
10568: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
10569: <a href=
10570: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
10571: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
10572: <a href=
10573: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
10574: ENDTIMEENTRY
10575:     $row .= &Apache::loncommon::end_data_table_row();
10576:     return $row;
10577: }
10578: 
10579: sub course_level_dc {
10580:     my ($dcdom,$showcredits) = @_;
10581:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10582:     my @roles = &Apache::lonuserutils::roles_by_context('course');
10583:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
10584:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
10585:                       '<input type="hidden" name="dccourse" value="" />';
10586:     my $courseform=&Apache::loncommon::selectcourse_link
10587:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
10588:     my $credit_elem;
10589:     if ($showcredits) {
10590:         $credit_elem = 'credits';
10591:     }
10592:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
10593:     my %lt=&Apache::lonlocal::texthash(
10594:                     'rol'  => "Role",
10595:                     'grs'  => "Section",
10596:                     'exs'  => "Existing sections",
10597:                     'new'  => "Define new section", 
10598:                     'sta'  => "Start",
10599:                     'end'  => "End",
10600:                     'ssd'  => "Set Start Date",
10601:                     'sed'  => "Set End Date",
10602:                     'scc'  => "Course/Community",
10603:                     'crd'  => "Credits",
10604:                   );
10605:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
10606:                  &Apache::loncommon::start_data_table().
10607:                  &Apache::loncommon::start_data_table_header_row().
10608:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10609:                  '<th>'.$lt{'grs'}.'</th>'."\n";
10610:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
10611:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
10612:                  &Apache::loncommon::end_data_table_header_row();
10613:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
10614:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
10615:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
10616:                      '<td valign="top"><br /><select name="role">'."\n";
10617:     foreach my $role (@roles) {
10618:         my $plrole=&Apache::lonnet::plaintext($role);
10619:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
10620:     }
10621:     if ( keys(%customroles) > 0) {
10622:         foreach my $cust (sort(keys(%customroles))) {
10623:             my $custrole='cr_cr_'.$env{'user.domain'}.
10624:                     '_'.$env{'user.name'}.'_'.$cust;
10625:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
10626:         }
10627:     }
10628:     $otheritems .= '</select></td><td>'.
10629:                      '<table border="0" cellspacing="0" cellpadding="0">'.
10630:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
10631:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
10632:                      '<td>&nbsp;&nbsp;</td>'.
10633:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
10634:                      '<input type="text" name="newsec" value="" />'.
10635:                      '<input type="hidden" name="section" value="" />'.
10636:                      '<input type="hidden" name="groups" value="" />'.
10637:                      '<input type="hidden" name="crstype" value="" /></td>'.
10638:                      '</tr></table></td>'."\n";
10639:     if ($showcredits) {
10640:         $otheritems .= '<td><br />'."\n".
10641:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
10642:     }
10643:     $otheritems .= <<ENDTIMEENTRY;
10644: <td><br /><input type="hidden" name="start" value='' />
10645: <a href=
10646: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
10647: <td><br /><input type="hidden" name="end" value='' />
10648: <a href=
10649: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
10650: ENDTIMEENTRY
10651:     $otheritems .= &Apache::loncommon::end_data_table_row().
10652:                    &Apache::loncommon::end_data_table()."\n";
10653:     return $cb_jscript.$hiddenitems.$header.$otheritems;
10654: }
10655: 
10656: sub update_selfenroll_config {
10657:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
10658:     return unless (ref($currsettings) eq 'HASH');
10659:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
10660:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10661:     my (%changes,%warning);
10662:     my $curr_types;
10663:     my %noedit;
10664:     unless ($context eq 'domain') {
10665:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
10666:     }
10667:     if (ref($row) eq 'ARRAY') {
10668:         foreach my $item (@{$row}) {
10669:             next if ($noedit{$item});
10670:             if ($item eq 'enroll_dates') {
10671:                 my (%currenrolldate,%newenrolldate);
10672:                 foreach my $type ('start','end') {
10673:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
10674:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
10675:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
10676:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
10677:                     }
10678:                 }
10679:             } elsif ($item eq 'access_dates') {
10680:                 my (%currdate,%newdate);
10681:                 foreach my $type ('start','end') {
10682:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
10683:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
10684:                     if ($newdate{$type} ne $currdate{$type}) {
10685:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
10686:                     }
10687:                 }
10688:             } elsif ($item eq 'types') {
10689:                 $curr_types = $currsettings->{'selfenroll_'.$item};
10690:                 if ($env{'form.selfenroll_all'}) {
10691:                     if ($curr_types ne '*') {
10692:                         $changes{'internal.selfenroll_types'} = '*';
10693:                     } else {
10694:                         next;
10695:                     }
10696:                 } else {
10697:                     my %currdoms;
10698:                     my @entries = split(/;/,$curr_types);
10699:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
10700:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
10701:                     my $newnum = 0;
10702:                     my @latesttypes;
10703:                     foreach my $num (@activations) {
10704:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
10705:                         if (@types > 0) {
10706:                             @types = sort(@types);
10707:                             my $typestr = join(',',@types);
10708:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
10709:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10710:                             $currdoms{$typedom} = 1;
10711:                             $newnum ++;
10712:                         }
10713:                     }
10714:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
10715:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
10716:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
10717:                             if (@types > 0) {
10718:                                 @types = sort(@types);
10719:                                 my $typestr = join(',',@types);
10720:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
10721:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
10722:                                 $currdoms{$typedom} = 1;
10723:                                 $newnum ++;
10724:                             }
10725:                         }
10726:                     }
10727:                     if ($env{'form.selfenroll_newdom'} ne '') {
10728:                         my $typedom = $env{'form.selfenroll_newdom'};
10729:                         if ((!defined($currdoms{$typedom})) && 
10730:                             (&Apache::lonnet::domain($typedom) ne '')) {
10731:                             my $typestr;
10732:                             my ($othertitle,$usertypes,$types) = 
10733:                                 &Apache::loncommon::sorted_inst_types($typedom);
10734:                             my $othervalue = 'any';
10735:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
10736:                                 if (@{$types} > 0) {
10737:                                     my @esc_types = map { &escape($_); } @{$types};
10738:                                     $othervalue = 'other';
10739:                                     $typestr = join(',',(@esc_types,$othervalue));
10740:                                 }
10741:                                 $typestr = $othervalue;
10742:                             } else {
10743:                                 $typestr = $othervalue;
10744:                             } 
10745:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10746:                             $newnum ++ ;
10747:                         }
10748:                     }
10749:                     my $selfenroll_types = join(';',@latesttypes);
10750:                     if ($selfenroll_types ne $curr_types) {
10751:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
10752:                     }
10753:                 }
10754:             } elsif ($item eq 'limit') {
10755:                 my $newlimit = $env{'form.selfenroll_limit'};
10756:                 my $newcap = $env{'form.selfenroll_cap'};
10757:                 $newcap =~s/\s+//g;
10758:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10759:                 $currlimit = 'none' if ($currlimit eq '');
10760:                 my $currcap = $currsettings->{'selfenroll_cap'};
10761:                 if ($newlimit ne $currlimit) {
10762:                     if ($newlimit ne 'none') {
10763:                         if ($newcap =~ /^\d+$/) {
10764:                             if ($newcap ne $currcap) {
10765:                                 $changes{'internal.selfenroll_cap'} = $newcap;
10766:                             }
10767:                             $changes{'internal.selfenroll_limit'} = $newlimit;
10768:                         } else {
10769:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10770:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
10771:                         }
10772:                     } elsif ($currcap ne '') {
10773:                         $changes{'internal.selfenroll_cap'} = '';
10774:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
10775:                     }
10776:                 } elsif ($currlimit ne 'none') {
10777:                     if ($newcap =~ /^\d+$/) {
10778:                         if ($newcap ne $currcap) {
10779:                             $changes{'internal.selfenroll_cap'} = $newcap;
10780:                         }
10781:                     } else {
10782:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10783:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
10784:                     }
10785:                 }
10786:             } elsif ($item eq 'approval') {
10787:                 my (@currnotified,@newnotified);
10788:                 my $currapproval = $currsettings->{'selfenroll_approval'};
10789:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
10790:                 if ($currnotifylist ne '') {
10791:                     @currnotified = split(/,/,$currnotifylist);
10792:                     @currnotified = sort(@currnotified);
10793:                 }
10794:                 my $newapproval = $env{'form.selfenroll_approval'};
10795:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
10796:                 @newnotified = sort(@newnotified);
10797:                 if ($newapproval ne $currapproval) {
10798:                     $changes{'internal.selfenroll_approval'} = $newapproval;
10799:                     if (!$newapproval) {
10800:                         if ($currnotifylist ne '') {
10801:                             $changes{'internal.selfenroll_notifylist'} = '';
10802:                         }
10803:                     } else {
10804:                         my @differences =  
10805:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10806:                         if (@differences > 0) {
10807:                             if (@newnotified > 0) {
10808:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10809:                             } else {
10810:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10811:                             }
10812:                         }
10813:                     }
10814:                 } else {
10815:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10816:                     if (@differences > 0) {
10817:                         if (@newnotified > 0) {
10818:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10819:                         } else {
10820:                             $changes{'internal.selfenroll_notifylist'} = '';
10821:                         }
10822:                     }
10823:                 }
10824:             } else {
10825:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
10826:                 my $newval = $env{'form.selfenroll_'.$item};
10827:                 if ($item eq 'section') {
10828:                     $newval = $env{'form.sections'};
10829:                     if (defined($curr_groups{$newval})) {
10830:                         $newval = $curr_val;
10831:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
10832:                                           &mt('Group names and section names must be distinct');
10833:                     } elsif ($newval eq 'all') {
10834:                         $newval = $curr_val;
10835:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
10836:                     }
10837:                     if ($newval eq '') {
10838:                         $newval = 'none';
10839:                     }
10840:                 }
10841:                 if ($newval ne $curr_val) {
10842:                     $changes{'internal.selfenroll_'.$item} = $newval;
10843:                 }
10844:             }
10845:         }
10846:         if (keys(%warning) > 0) {
10847:             foreach my $item (@{$row}) {
10848:                 if (exists($warning{$item})) {
10849:                     $r->print($warning{$item}.'<br />');
10850:                 }
10851:             } 
10852:         }
10853:         if (keys(%changes) > 0) {
10854:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
10855:             if ($putresult eq 'ok') {
10856:                 if ((exists($changes{'internal.selfenroll_types'})) ||
10857:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
10858:                     (exists($changes{'internal.selfenroll_end_date'}))) {
10859:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
10860:                                                                 $cnum,undef,undef,'Course');
10861:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
10862:                     if (ref($crsinfo{$cid}) eq 'HASH') {
10863:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
10864:                             if (exists($changes{'internal.'.$item})) {
10865:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
10866:                             }
10867:                         }
10868:                         my $crsputresult =
10869:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
10870:                                                          $chome,'notime');
10871:                     }
10872:                 }
10873:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
10874:                 foreach my $item (@{$row}) {
10875:                     my $title = $item;
10876:                     if (ref($lt) eq 'HASH') {
10877:                         $title = $lt->{$item};
10878:                     }
10879:                     if ($item eq 'enroll_dates') {
10880:                         foreach my $type ('start','end') {
10881:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
10882:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
10883:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10884:                                           $title,$type,$newdate).'</li>');
10885:                             }
10886:                         }
10887:                     } elsif ($item eq 'access_dates') {
10888:                         foreach my $type ('start','end') {
10889:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
10890:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
10891:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10892:                                           $title,$type,$newdate).'</li>');
10893:                             }
10894:                         }
10895:                     } elsif ($item eq 'limit') {
10896:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
10897:                             (exists($changes{'internal.selfenroll_cap'}))) {
10898:                             my ($newval,$newcap);
10899:                             if ($changes{'internal.selfenroll_cap'} ne '') {
10900:                                 $newcap = $changes{'internal.selfenroll_cap'}
10901:                             } else {
10902:                                 $newcap = $currsettings->{'selfenroll_cap'};
10903:                             }
10904:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
10905:                                 $newval = &mt('No limit');
10906:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
10907:                                      'allstudents') {
10908:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10909:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10910:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10911:                             } else {
10912:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10913:                                 if ($currlimit eq 'allstudents') {
10914:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10915:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10916:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10917:                                 }
10918:                             }
10919:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10920:                         }
10921:                     } elsif ($item eq 'approval') {
10922:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
10923:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
10924:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
10925:                             my ($newval,$newnotify);
10926:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
10927:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
10928:                             } else {   
10929:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
10930:                             }
10931:                             if (exists($changes{'internal.selfenroll_approval'})) {
10932:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
10933:                                     $changes{'internal.selfenroll_approval'} = '0';
10934:                                 }
10935:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
10936:                             } else {
10937:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
10938:                                 if ($currapproval !~ /^[012]$/) {
10939:                                     $currapproval = 0;
10940:                                 }
10941:                                 $newval = $selfdescs{'approval'}{$currapproval};
10942:                             }
10943:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
10944:                             if ($newnotify) {
10945:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
10946:                             } else {
10947:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
10948:                             }
10949:                             $r->print('</li>'."\n");
10950:                         }
10951:                     } else {
10952:                         if (exists($changes{'internal.selfenroll_'.$item})) {
10953:                             my $newval = $changes{'internal.selfenroll_'.$item};
10954:                             if ($item eq 'types') {
10955:                                 if ($newval eq '') {
10956:                                     $newval = &mt('None');
10957:                                 } elsif ($newval eq '*') {
10958:                                     $newval = &mt('Any user in any domain');
10959:                                 }
10960:                             } elsif ($item eq 'registered') {
10961:                                 if ($newval eq '1') {
10962:                                     $newval = &mt('Yes');
10963:                                 } elsif ($newval eq '0') {
10964:                                     $newval = &mt('No');
10965:                                 }
10966:                             }
10967:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10968:                         }
10969:                     }
10970:                 }
10971:                 $r->print('</ul>');
10972:                 if ($env{'course.'.$cid.'.description'} ne '') {
10973:                     my %newenvhash;
10974:                     foreach my $key (keys(%changes)) {
10975:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
10976:                     }
10977:                     &Apache::lonnet::appenv(\%newenvhash);
10978:                 }
10979:             } else {
10980:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
10981:                           &mt('The error was: [_1].',$putresult));
10982:             }
10983:         } else {
10984:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10985:         }
10986:     } else {
10987:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10988:     }
10989:     my $visactions = &cat_visibility($cdom);
10990:     my ($cathash,%cattype);
10991:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
10992:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10993:         $cathash = $domconfig{'coursecategories'}{'cats'};
10994:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
10995:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
10996:     } else {
10997:         $cathash = {};
10998:         $cattype{'auth'} = 'std';
10999:         $cattype{'unauth'} = 'std';
11000:     }
11001:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
11002:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
11003:                   '<br />'.
11004:                   '<br />'.$visactions->{'take'}.'<ul>'.
11005:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
11006:                   '</ul>');
11007:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
11008:         if ($currsettings->{'uniquecode'}) {
11009:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
11010:         } else {
11011:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
11012:                   '<br />'.
11013:                   '<br />'.$visactions->{'take'}.'<ul>'.
11014:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
11015:                   '</ul><br />');
11016:         }
11017:     } else {
11018:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
11019:         if (ref($visactions) eq 'HASH') {
11020:             if (!$visible) {
11021:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
11022:                           '<br />');
11023:                 if (ref($vismsgs) eq 'ARRAY') {
11024:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
11025:                     foreach my $item (@{$vismsgs}) {
11026:                         $r->print('<li>'.$visactions->{$item}.'</li>');
11027:                     }
11028:                     $r->print('</ul>');
11029:                 }
11030:                 $r->print($cansetvis);
11031:             }
11032:         }
11033:     } 
11034:     return;
11035: }
11036: 
11037: #---------------------------------------------- end functions for &phase_two
11038: 
11039: #--------------------------------- functions for &phase_two and &phase_three
11040: 
11041: #--------------------------end of functions for &phase_two and &phase_three
11042: 
11043: 1;
11044: __END__
11045: 
11046: 

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