File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.473: download - view: text, annotated - select for diffs
Sun Nov 5 20:06:04 2023 UTC (6 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5273
- Add icons for User Management Mens in Authoring Space.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.473 2023/11/05 20:06:04 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:                 for (var i=0; i<radioname.length; i++) {
  249:                     if (radioname[i].checked == true) {
  250:                         if (radioname[i].value == 1) {
  251:                             divid.style.display = 'block';
  252:                             setvis = 1;
  253:                         }
  254:                         break;
  255:                     }
  256:                 }
  257:                 if (!setvis) {
  258:                     divid.style.display = 'none';
  259:                 }
  260:             }
  261:         }
  262:     }
  263:     return;
  264: }
  265: // ]]>
  266: </script>
  267: 
  268: END_SCRIPT
  269: 
  270: }
  271: 
  272: sub build_tools_display {
  273:     my ($ccuname,$ccdomain,$context) = @_;
  274:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  275:         $colspan,$isadv,%domconfig,@defaulteditors,@customeditors,@custommanagers,
  276:         @possmanagers,$editorsty,$customsty);
  277:     my %lt = &Apache::lonlocal::texthash (
  278:                    'blog'       => "Personal User Blog",
  279:                    'aboutme'    => "Personal Information Page",
  280:                    'webdav'     => "WebDAV access to Authoring Spaces (https)",
  281:                    'editors'    => "Available Editors",
  282:                    'managers'   => "Co-authors who can add/revoke roles",
  283:                    'portfolio'  => "Personal User Portfolio",
  284:                    'portaccess' => "Portfolio Shareable",
  285:                    'timezone'   => "Can set Time Zone",
  286:                    'avai'       => "Available",
  287:                    'cusa'       => "availability",
  288:                    'chse'       => "Change setting",
  289:                    'usde'       => "Use default",
  290:                    'uscu'       => "Use custom",
  291:                    'official'   => 'Can request creation of official courses',
  292:                    'unofficial' => 'Can request creation of unofficial courses',
  293:                    'community'  => 'Can request creation of communities',
  294:                    'textbook'   => 'Can request creation of textbook courses',
  295:                    'placement'  => 'Can request creation of placement tests',
  296:                    'lti'        => 'Can request creation of LTI courses',
  297:                    'requestauthor'  => 'Can request author space',
  298:                    'edit'       => 'Standard editor (Edit)',
  299:                    'xml'        => 'Text editor (EditXML)',
  300:                    'daxe'       => 'Daxe editor (Daxe)',
  301:     );
  302:     $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  303:     if ($context eq 'requestcourses') {
  304:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  305:                       'requestcourses.official','requestcourses.unofficial',
  306:                       'requestcourses.community','requestcourses.textbook',
  307:                       'requestcourses.placement','requestcourses.lti');
  308:         @usertools = ('official','unofficial','community','textbook','placement','lti');
  309:         @options =('norequest','approval','autolimit','validate');
  310:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  311:         %reqtitles = &courserequest_titles();
  312:         %reqdisplay = &courserequest_display();
  313:         %domconfig =
  314:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  315:     } elsif ($context eq 'requestauthor') {
  316:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'requestauthor');
  317:         @usertools = ('requestauthor');
  318:         @options =('norequest','approval','automatic');
  319:         %reqtitles = &requestauthor_titles();
  320:         %reqdisplay = &requestauthor_display();
  321:         %domconfig =
  322:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  323:     } elsif ($context eq 'authordefaults') {
  324:         %domconfig =
  325:             &Apache::lonnet::get_dom('configuration',['quotas','authordefaults'],$ccdomain);
  326:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'tools.webdav',
  327:                                                     'authoreditors','authormanagers',
  328:                                                     'domcoord.author');
  329:         @usertools = ('webdav','editors','managers');
  330:         $colspan = ' colspan="2"';
  331:     } else {
  332:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  333:                           'tools.aboutme','tools.portfolio','tools.blog',
  334:                           'tools.timezone','tools.portaccess');
  335:         @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
  336:         $colspan = ' colspan="2"';
  337:     }
  338:     foreach my $item (@usertools) {
  339:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  340:             $currdisp,$custdisp,$custradio,$onclick);
  341:         $cust_off = 'checked="checked" ';
  342:         $tool_on = 'checked="checked" ';
  343:         $curr_access =
  344:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  345:                                               $context,\%userenv,'',
  346:                                               {'is_adv' => $isadv});
  347:         if ($context eq 'requestauthor') {
  348:             if ($userenv{$context} ne '') {
  349:                 $cust_on = ' checked="checked" ';
  350:                 $cust_off = '';
  351:             }
  352:         } elsif ($context eq 'authordefaults') {
  353:             if ($item eq 'editors') {
  354:                 if ($userenv{'author'.$item} ne '') {
  355:                     $cust_on = ' checked="checked" ';
  356:                     $cust_off = '';
  357:                 }
  358:             } elsif ($item eq 'webdav') {
  359:                 if ($userenv{'tools.'.$item} ne '') {
  360:                     $cust_on = ' checked="checked" ';
  361:                     $cust_off = '';
  362:                 }
  363:             }
  364:         } elsif ($userenv{$context.'.'.$item} ne '') {
  365:             $cust_on = ' checked="checked" ';
  366:             $cust_off = '';
  367:         }
  368:         if ($context eq 'requestcourses') {
  369:             if ($userenv{$context.'.'.$item} eq '') {
  370:                 $custom_access = &mt('Currently from default setting.');
  371:                 $customsty = ' style="display:none;"';
  372:             } else {
  373:                 $custom_access = &mt('Currently from custom setting.');
  374:                 $customsty = ' style="display:block;"';
  375:             }
  376:         } elsif ($context eq 'requestauthor') {
  377:             if ($userenv{$context} eq '') {
  378:                 $custom_access = &mt('Currently from default setting.');
  379:                 $customsty = ' style="display:none;"';
  380:             } else {
  381:                 $custom_access = &mt('Currently from custom setting.');
  382:                 $customsty = ' style="display:block;"';
  383:             }
  384:         } elsif ($item eq 'editors') {
  385:             if ($userenv{'author'.$item} eq '') {
  386:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
  387:                     @defaulteditors = @{$domconfig{'authordefaults'}{'editors'}};
  388:                 } else {
  389:                     @defaulteditors = ('edit','xml');
  390:                 }
  391:                 $custom_access = &mt('Can use: [_1]',
  392:                                                join(', ', map { $lt{$_} } @defaulteditors));
  393:                 $editorsty = ' style="display:none;"';
  394:             } else {
  395:                 $custom_access = &mt('Currently from custom setting.');
  396:                 foreach my $editor (split(/,/,$userenv{'author'.$item})) {
  397:                     if ($editor =~ /^(edit|daxe|xml)$/) {
  398:                         push(@customeditors,$editor);
  399:                     }
  400:                 }
  401:                 if (@customeditors) {
  402:                     if (@customeditors > 1) {
  403:                         $custom_access .= '<br /><span>';
  404:                     } else {
  405:                         $custom_access .= ' <span class="LC_nobreak">';
  406:                     }
  407:                     $custom_access .= &mt('Can use: [_1]',
  408:                                           join(', ', map { $lt{$_} } @customeditors)).
  409:                                       '</span>';
  410:                 } else {
  411:                     $custom_access .= ' '.&mt('No available editors');
  412:                 }
  413:                 $editorsty = ' style="display:block;"';
  414:             }
  415:         } elsif ($item eq 'managers') {
  416:             my %ca_roles = &Apache::lonnet::get_my_roles($ccuname,$ccdomain,undef,
  417:                                                          ['active','future'],['ca']);
  418:             if (keys(%ca_roles)) {
  419:                 foreach my $entry (sort(keys(%ca_roles))) {
  420:                     if ($entry =~ /^($match_username\:$match_domain):ca$/) {
  421:                         my $user = $1;
  422:                         unless ($user eq "$ccuname:$ccdomain") {
  423:                             push(@possmanagers,$user);
  424:                         }
  425:                     }
  426:                 }
  427:             }
  428:             if ($userenv{'author'.$item} eq '') {
  429:                 $custom_access = &mt('Currently author manages co-author roles');
  430:             } else {
  431:                 if (keys(%ca_roles)) {
  432:                     foreach my $user (split(/,/,$userenv{'author'.$item})) {
  433:                         if ($user =~ /^($match_username):($match_domain)$/) {
  434:                             if (exists($ca_roles{$user.':ca'})) {
  435:                                 unless ($user eq "$ccuname:$ccdomain") {
  436:                                     push(@custommanagers,$user);
  437:                                 }
  438:                             }
  439:                         }
  440:                     }
  441:                 }
  442:                 if (@custommanagers) {
  443:                     $custom_access = &mt('Co-authors who manage co-author roles: [_1]',
  444:                                          join(', ',@custommanagers));
  445:                 } else {
  446:                     $custom_access = &mt('Currently author manages co-author roles');
  447:                 }
  448:             }
  449:         } else {
  450:             my $current = $userenv{$context.'.'.$item};
  451:             if ($item eq 'webdav') {
  452:                 $current = $userenv{'tools.webdav'};
  453:             }
  454:             if ($current eq '') {
  455:                 $custom_access =
  456:                     &mt('Availability determined currently from default setting.');
  457:                 if (!$curr_access) {
  458:                     $tool_off = 'checked="checked" ';
  459:                     $tool_on = '';
  460:                 }
  461:                 $customsty = ' style="display:none;"';
  462:             } else {
  463:                 $custom_access =
  464:                     &mt('Availability determined currently from custom setting.');
  465:                 if ($current == 0) {
  466:                     $tool_off = 'checked="checked" ';
  467:                     $tool_on = '';
  468:                 }
  469:                 $customsty = ' style="display:inline;"';
  470:             }
  471:         }
  472:         $output .= '  <tr class="LC_info_row">'."\n".
  473:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  474:                    '  </tr>'."\n".
  475:                    &Apache::loncommon::start_data_table_row()."\n";
  476:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  477:             my ($curroption,$currlimit,$customsty);
  478:             my $envkey = $context.'.'.$item;
  479:             if ($context eq 'requestauthor') {
  480:                 $envkey = $context;
  481:             }
  482:             if ($userenv{$envkey} ne '') {
  483:                 $curroption = $userenv{$envkey};
  484:                 $customsty = ' style="display:block"';
  485:             } else {
  486:                 $customsty = ' style="display:none"';
  487:                 my (@inststatuses);
  488:                 if ($context eq 'requestcourses') {
  489:                     $curroption =
  490:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  491:                                                                       $isadv,$ccdomain,$item,
  492:                                                                       \@inststatuses,\%domconfig);
  493:                 } else {
  494:                      $curroption = 
  495:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  496:                                                                        $isadv,$ccdomain,undef,
  497:                                                                        \@inststatuses,\%domconfig);
  498:                 }
  499:             }
  500:             if (!$curroption) {
  501:                 $curroption = 'norequest';
  502:             }
  503:             my $name = 'crsreq_'.$item;
  504:             if ($context eq 'requestauthor') {
  505:                 $name = $item;
  506:             }
  507:             $onclick = ' onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');"';
  508:             if ($curroption =~ /^autolimit=(\d*)$/) {
  509:                 $currlimit = $1;
  510:                 if ($currlimit eq '') {
  511:                     $currdisp = &mt('Yes, automatic creation');
  512:                 } else {
  513:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  514:                 }
  515:             } else {
  516:                 $currdisp = $reqdisplay{$curroption};
  517:             }
  518:             $custdisp = '<fieldset id="customtext_'.$item.'"'.$customsty.'>';
  519:             foreach my $option (@options) {
  520:                 my $val = $option;
  521:                 if ($option eq 'norequest') {
  522:                     $val = 0;
  523:                 }
  524:                 if ($option eq 'validate') {
  525:                     my $canvalidate = 0;
  526:                     if (ref($validations{$item}) eq 'HASH') {
  527:                         if ($validations{$item}{'_custom_'}) {
  528:                             $canvalidate = 1;
  529:                         }
  530:                     }
  531:                     next if (!$canvalidate);
  532:                 }
  533:                 my $checked = '';
  534:                 if ($option eq $curroption) {
  535:                     $checked = ' checked="checked"';
  536:                 } elsif ($option eq 'autolimit') {
  537:                     if ($curroption =~ /^autolimit/) {
  538:                         $checked = ' checked="checked"';
  539:                     }
  540:                 }
  541:                 if ($option eq 'autolimit') {
  542:                     $custdisp .= '<br />';
  543:                 }
  544:                 $custdisp .= '<span class="LC_nobreak"><label>'.
  545:                              '<input type="radio" name="'.$name.'" '.
  546:                              'value="'.$val.'"'.$checked.' />'.
  547:                              $reqtitles{$option}.'</label>&nbsp;';
  548:                 if ($option eq 'autolimit') {
  549:                     $custdisp .= '<input type="text" name="'.$name.
  550:                                  '_limit" size="1" '.
  551:                                  'value="'.$currlimit.'" />&nbsp;'.
  552:                                  $reqtitles{'unlimited'}.'</span>';
  553:                 } else {
  554:                     $custdisp .= '</span>';
  555:                 }
  556:                 $custdisp .= ' ';
  557:             }
  558:             $custdisp .= '</fieldset>';
  559:             $custradio = '<br />'.$custdisp;
  560:         } elsif ($item eq 'editors') {
  561:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  562:                        &Apache::loncommon::end_data_table_row()."\n";
  563:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  564:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  565:                           '<td'.$colspan.'><span class="LC_nobreak">'.
  566:                           $lt{'chse'}.': <label>'.
  567:                           '<input type="radio" name="custom'.$item.'" value="0" '.
  568:                           $cust_off.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  569:                           $lt{'usde'}.'</label>'.('&nbsp;' x3).
  570:                           '<label><input type="radio" name="custom'.$item.'" value="1" '.
  571:                           $cust_on.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  572:                           $lt{'uscu'}.'</label></span><br />'.
  573:                           '<fieldset id="customtext_'.$item.'"'.$editorsty.'>';
  574:                 foreach my $editor ('edit','xml','daxe') {
  575:                     my $checked;
  576:                     if ($userenv{'author'.$item} eq '') {
  577:                         if (grep(/^\Q$editor\E$/,@defaulteditors)) {
  578:                             $checked = ' checked="checked"';
  579:                         }
  580:                     } elsif (grep(/^\Q$editor\E$/,@customeditors)) {
  581:                         $checked = ' checked="checked"';
  582:                     }
  583:                     $output .= '<span style="LC_nobreak"><label>'.
  584:                                '<input type="checkbox" name="custom_editor" '.
  585:                                'value="'.$editor.'"'.$checked.' />'.
  586:                                $lt{$editor}.'</label></span> ';
  587:                 }
  588:                 $output .= '</fieldset></td>'.
  589:                            &Apache::loncommon::end_data_table_row()."\n";
  590:             }
  591:         } elsif ($item eq 'managers') {
  592:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  593:                        &Apache::loncommon::end_data_table_row()."\n";
  594:             unless ((&Apache::lonnet::allowed('udp',$ccdomain)) ||
  595:                     (($userenv{'domcoord.author'} eq 'blocked') &&
  596:                      (($env{'user.name'} ne $ccuname) || ($env{'user.domain'} ne $ccdomain)))) {
  597:                 $output .=
  598:                     &Apache::loncommon::start_data_table_row()."\n".
  599:                     '<td'.$colspan.'>';
  600:                 if (@possmanagers) {
  601:                     $output .= &mt('Select manager(s)').': ';
  602:                     foreach my $user (@possmanagers) {
  603:                         my $checked;
  604:                         if (grep(/^\Q$user\E$/,@custommanagers)) {
  605:                             $checked = ' checked="checked"';
  606:                         }
  607:                         $output .= '<span style="LC_nobreak"><label>'.
  608:                                    '<input type="checkbox" name="custommanagers" '.
  609:                                    'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
  610:                                    $user.'</label></span> ';
  611:                     }
  612:                 } else {
  613:                     $output .= &mt('No co-author roles assignable as manager');
  614:                 }
  615:                 $output .= '</td>'.
  616:                            &Apache::loncommon::end_data_table_row()."\n";
  617:             }
  618:         } else {
  619:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  620:             my $name = $context.'_'.$item;
  621:             $onclick = 'onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');" ';
  622:             $custdisp = '<span class="LC_nobreak"><label>'.
  623:                         '<input type="radio" name="'.$name.'"'.
  624:                         ' value="1" '.$tool_on.$onclick.'/>'.&mt('On').'</label>&nbsp;<label>'.
  625:                         '<input type="radio" name="'.$name.'" value="0" '.
  626:                         $tool_off.$onclick.'/>'.&mt('Off').'</label></span>';
  627:             $custradio = '<span id="customtext_'.$item.'"'.$customsty.' class="LC_nobreak">'.
  628:                          '--'.$lt{'cusa'}.':&nbsp;'.$custdisp.'</span>';
  629:         }
  630:         unless (($item eq 'editors') || ($item eq 'managers')) {
  631:             $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  632:                        $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  633:                        &Apache::loncommon::end_data_table_row()."\n";
  634:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  635:                 $output .=
  636:                    &Apache::loncommon::start_data_table_row()."\n".
  637:                    '<td><span class="LC_nobreak">'.
  638:                    $lt{'chse'}.': <label>'.
  639:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  640:                    $cust_off.$onclick.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  641:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  642:                    $cust_on.$onclick.'/>'.$lt{'uscu'}.'</label></span>';
  643:                 if ($colspan) {
  644:                     $output .= '</td><td>';
  645:                 }
  646:                 $output .= $custradio.'</td>'.
  647:                            &Apache::loncommon::end_data_table_row()."\n";
  648:             }
  649:         }
  650:     }
  651:     return $output;
  652: }
  653: 
  654: sub coursereq_externaluser {
  655:     my ($ccuname,$ccdomain,$cdom) = @_;
  656:     my (@usertools,@options,%validations,%userenv,$output);
  657:     my %lt = &Apache::lonlocal::texthash (
  658:                    'official'   => 'Can request creation of official courses',
  659:                    'unofficial' => 'Can request creation of unofficial courses',
  660:                    'community'  => 'Can request creation of communities',
  661:                    'textbook'   => 'Can request creation of textbook courses',
  662:                    'placement'  => 'Can request creation of placement tests',
  663:     );
  664: 
  665:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  666:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  667:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  668:                       'reqcrsotherdom.placement');
  669:     @usertools = ('official','unofficial','community','textbook','placement');
  670:     @options = ('approval','validate','autolimit');
  671:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  672:     my $optregex = join('|',@options);
  673:     my %reqtitles = &courserequest_titles();
  674:     foreach my $item (@usertools) {
  675:         my ($curroption,$currlimit,$tooloff);
  676:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  677:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  678:             foreach my $req (@curr) {
  679:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  680:                     $curroption = $1;
  681:                     $currlimit = $2;
  682:                     last;
  683:                 }
  684:             }
  685:             if (!$curroption) {
  686:                 $curroption = 'norequest';
  687:                 $tooloff = ' checked="checked"';
  688:             }
  689:         } else {
  690:             $curroption = 'norequest';
  691:             $tooloff = ' checked="checked"';
  692:         }
  693:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  694:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  695:                   '<table><tr><td valign="top">'."\n".
  696:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  697:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  698:                   '</label></td>';
  699:         foreach my $option (@options) {
  700:             if ($option eq 'validate') {
  701:                 my $canvalidate = 0;
  702:                 if (ref($validations{$item}) eq 'HASH') {
  703:                     if ($validations{$item}{'_external_'}) {
  704:                         $canvalidate = 1;
  705:                     }
  706:                 }
  707:                 next if (!$canvalidate);
  708:             }
  709:             my $checked = '';
  710:             if ($option eq $curroption) {
  711:                 $checked = ' checked="checked"';
  712:             }
  713:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  714:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  715:                        '" value="'.$option.'"'.$checked.' />'.
  716:                        $reqtitles{$option}.'</label>';
  717:             if ($option eq 'autolimit') {
  718:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  719:                            $item.'_limit" size="1" '.
  720:                            'value="'.$currlimit.'" /></span>'.
  721:                            '<br />'.$reqtitles{'unlimited'};
  722:             } else {
  723:                 $output .= '</span>';
  724:             }
  725:             $output .= '</td>';
  726:         }
  727:         $output .= '</td></tr></table></td>'."\n".
  728:                    &Apache::loncommon::end_data_table_row()."\n";
  729:     }
  730:     return $output;
  731: }
  732: 
  733: sub domainrole_req {
  734:     my ($ccuname,$ccdomain) = @_;
  735:     return '<br /><h3>'.
  736:            &mt('Can Request Assignment of Domain Roles?').
  737:            '</h3>'."\n".
  738:            &Apache::loncommon::start_data_table().
  739:            &build_tools_display($ccuname,$ccdomain,
  740:                                 'requestauthor').
  741:            &Apache::loncommon::end_data_table();
  742: }
  743: 
  744: sub authoring_defaults {
  745:     my ($ccuname,$ccdomain) = @_;
  746:     return '<br /><h3>'.
  747:            &mt('Authoring Space defaults (if role assigned)').
  748:            '</h3>'."\n".
  749:            &Apache::loncommon::start_data_table().
  750:            &build_tools_display($ccuname,$ccdomain,
  751:                                 'authordefaults').
  752:            &user_quotas($ccuname,$ccdomain,'author').
  753:            &Apache::loncommon::end_data_table();
  754: }
  755: 
  756: sub courserequest_titles {
  757:     my %titles = &Apache::lonlocal::texthash (
  758:                                    official   => 'Official',
  759:                                    unofficial => 'Unofficial',
  760:                                    community  => 'Communities',
  761:                                    textbook   => 'Textbook',
  762:                                    placement  => 'Placement Tests',
  763:                                    lti        => 'LTI Provider',
  764:                                    norequest  => 'Not allowed',
  765:                                    approval   => 'Approval by Dom. Coord.',
  766:                                    validate   => 'With validation',
  767:                                    autolimit  => 'Numerical limit',
  768:                                    unlimited  => '(blank for unlimited)',
  769:                  );
  770:     return %titles;
  771: }
  772: 
  773: sub courserequest_display {
  774:     my %titles = &Apache::lonlocal::texthash (
  775:                                    approval   => 'Yes, need approval',
  776:                                    validate   => 'Yes, with validation',
  777:                                    norequest  => 'No',
  778:    );
  779:    return %titles;
  780: }
  781: 
  782: sub requestauthor_titles {
  783:     my %titles = &Apache::lonlocal::texthash (
  784:                                    norequest  => 'Not allowed',
  785:                                    approval   => 'Approval by Dom. Coord.',
  786:                                    automatic  => 'Automatic approval',
  787:                  );
  788:     return %titles;
  789: 
  790: }
  791: 
  792: sub requestauthor_display {
  793:     my %titles = &Apache::lonlocal::texthash (
  794:                                    approval   => 'Yes, need approval',
  795:                                    automatic  => 'Yes, automatic approval',
  796:                                    norequest  => 'No',
  797:    );
  798:    return %titles;
  799: }
  800: 
  801: sub requestchange_display {
  802:     my %titles = &Apache::lonlocal::texthash (
  803:                                    approval   => "availability set to 'on' (approval required)", 
  804:                                    automatic  => "availability set to 'on' (automatic approval)",
  805:                                    norequest  => "availability set to 'off'",
  806:    );
  807:    return %titles;
  808: }
  809: 
  810: sub curr_requestauthor {
  811:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  812:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  813:     if ($uname eq '' || $udom eq '') {
  814:         $uname = $env{'user.name'};
  815:         $udom = $env{'user.domain'};
  816:         $isadv = $env{'user.adv'};
  817:     }
  818:     my (%userenv,%settings,$val);
  819:     my @options = ('automatic','approval');
  820:     %userenv =
  821:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  822:     if ($userenv{'requestauthor'}) {
  823:         $val = $userenv{'requestauthor'};
  824:         @{$inststatuses} = ('_custom_');
  825:     } else {
  826:         my %alltasks;
  827:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  828:             %settings = %{$domconfig->{'requestauthor'}};
  829:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  830:                 $val = $settings{'_LC_adv'};
  831:                 @{$inststatuses} = ('_LC_adv_');
  832:             } else {
  833:                 if ($userenv{'inststatus'} ne '') {
  834:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  835:                 } else {
  836:                     @{$inststatuses} = ('default');
  837:                 }
  838:                 foreach my $status (@{$inststatuses}) {
  839:                     if (exists($settings{$status})) {
  840:                         my $value = $settings{$status};
  841:                         next unless ($value);
  842:                         unless (exists($alltasks{$value})) {
  843:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  844:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  845:                                     push(@{$alltasks{$value}},$status);
  846:                                 }
  847:                             } else {
  848:                                 @{$alltasks{$value}} = ($status);
  849:                             }
  850:                         }
  851:                     }
  852:                 }
  853:                 foreach my $option (@options) {
  854:                     if ($alltasks{$option}) {
  855:                         $val = $option;
  856:                         last;
  857:                     }
  858:                 }
  859:             }
  860:         }
  861:     }
  862:     return $val;
  863: }
  864: 
  865: # =================================================================== Phase one
  866: 
  867: sub print_username_entry_form {
  868:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  869:         $permission) = @_;
  870:     my $defdom=$env{'request.role.domain'};
  871:     my $formtoset = 'crtuser';
  872:     if (exists($env{'form.startrolename'})) {
  873:         $formtoset = 'docustom';
  874:         $env{'form.rolename'} = $env{'form.startrolename'};
  875:     } elsif ($env{'form.origform'} eq 'crtusername') {
  876:         $formtoset =  $env{'form.origform'};
  877:     }
  878: 
  879:     my ($jsback,$elements) = &crumb_utilities();
  880: 
  881:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  882:         '<script type="text/javascript">'."\n".
  883:         '// <![CDATA['."\n".
  884:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  885:         '// ]]>'."\n".
  886:         '</script>'."\n";
  887: 
  888:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  889:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  890:         && (&Apache::lonnet::allowed('mcr','/'))) {
  891:         $jscript .= &customrole_javascript();
  892:     }
  893:     my $helpitem = 'Course_Change_Privileges';
  894:     if ($env{'form.action'} eq 'custom') {
  895:         if ($context eq 'course') {
  896:             $helpitem = 'Course_Editing_Custom_Roles';
  897:         } elsif ($context eq 'domain') {
  898:             $helpitem = 'Domain_Editing_Custom_Roles';
  899:         }
  900:     } elsif ($env{'form.action'} eq 'singlestudent') {
  901:         $helpitem = 'Course_Add_Student';
  902:     } elsif ($env{'form.action'} eq 'accesslogs') {
  903:         $helpitem = 'Domain_User_Access_Logs';
  904:     } elsif ($context eq 'author') {
  905:         $helpitem = 'Author_Change_Privileges';
  906:     } elsif ($context eq 'domain') {
  907:         if ($permission->{'cusr'}) {
  908:             $helpitem = 'Domain_Change_Privileges';
  909:         } elsif ($permission->{'view'}) {
  910:             $helpitem = 'Domain_View_Privileges';
  911:         } else {
  912:             undef($helpitem);
  913:         }
  914:     }
  915:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  916:     if ($env{'form.action'} eq 'custom') {
  917:         push(@{$brcrum},
  918:                  {href=>"javascript:backPage(document.crtuser)",       
  919:                   text=>"Pick custom role",
  920:                   help => $helpitem,}
  921:                  );
  922:     } else {
  923:         push (@{$brcrum},
  924:                   {href => "javascript:backPage(document.crtuser)",
  925:                    text => $breadcrumb_text{'search'},
  926:                    help => $helpitem,
  927:                    faq  => 282,
  928:                    bug  => 'Instructor Interface',}
  929:                   );
  930:     }
  931:     my %loaditems = (
  932:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  933:                     );
  934:     my $args = {bread_crumbs           => $brcrum,
  935:                 bread_crumbs_component => 'User Management',
  936:                 add_entries            => \%loaditems,};
  937:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  938: 
  939:     my %lt=&Apache::lonlocal::texthash(
  940:                     'srst' => 'Search for a user and enroll as a student',
  941:                     'srme' => 'Search for a user and enroll as a member',
  942:                     'srad' => 'Search for a user and modify/add user information or roles',
  943:                     'srvu' => 'Search for a user and view user information and roles',
  944:                     'srva' => 'Search for a user and view access log information',
  945: 		    'usr'  => "Username",
  946:                     'dom'  => "Domain",
  947:                     'ecrp' => "Define or Edit Custom Role",
  948:                     'nr'   => "role name",
  949:                     'cre'  => "Next",
  950: 				       );
  951: 
  952:     if ($env{'form.action'} eq 'custom') {
  953:         if (&Apache::lonnet::allowed('mcr','/')) {
  954:             my $newroletext = &mt('Define new custom role:');
  955:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  956:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  957:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  958:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  959:                       &Apache::loncommon::start_data_table().
  960:                       &Apache::loncommon::start_data_table_row().
  961:                       '<td>');
  962:             if (keys(%existingroles) > 0) {
  963:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  964:             } else {
  965:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  966:             }
  967:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  968:                       &Apache::loncommon::end_data_table_row());
  969:             if (keys(%existingroles) > 0) {
  970:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  971:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  972:                           &mt('View/Modify existing role:').'</b></label></td>'.
  973:                           '<td align="center"><br />'.
  974:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  975:                           '<option value="" selected="selected">'.
  976:                           &mt('Select'));
  977:                 foreach my $role (sort(keys(%existingroles))) {
  978:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  979:                 }
  980:                 $r->print('</select>'.
  981:                           '</td>'.
  982:                           &Apache::loncommon::end_data_table_row());
  983:             }
  984:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  985:                       '<input name="customeditor" type="submit" value="'.
  986:                       $lt{'cre'}.'" /></p>'.
  987:                       '</form>');
  988:         }
  989:     } else {
  990:         my $actiontext = $lt{'srad'};
  991:         my $fixeddom;
  992:         if ($env{'form.action'} eq 'singlestudent') {
  993:             if ($crstype eq 'Community') {
  994:                 $actiontext = $lt{'srme'};
  995:             } else {
  996:                 $actiontext = $lt{'srst'};
  997:             }
  998:         } elsif ($env{'form.action'} eq 'accesslogs') {
  999:             $actiontext = $lt{'srva'};
 1000:             $fixeddom = 1;
 1001:         } elsif (($env{'form.action'} eq 'singleuser') &&
 1002:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
 1003:             $actiontext = $lt{'srvu'};
 1004:             $fixeddom = 1;
 1005:         }
 1006:         $r->print("<h3>$actiontext</h3>");
 1007:         if ($env{'form.origform'} ne 'crtusername') {
 1008:             if ($response) {
 1009:                $r->print("\n<div>$response</div>".
 1010:                          '<br clear="all" />');
 1011:             }
 1012:         }
 1013:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
 1014:     }
 1015: }
 1016: 
 1017: sub customrole_javascript {
 1018:     my $js = <<"END";
 1019: <script type="text/javascript">
 1020: // <![CDATA[
 1021: 
 1022: function setCustomFields() {
 1023:     if (document.docustom.customroleaction.length > 0) {
 1024:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1025:             if (document.docustom.customroleaction[i].checked) {
 1026:                 if (document.docustom.customroleaction[i].value == 'new') {
 1027:                     document.docustom.rolename.selectedIndex = 0;
 1028:                 } else {
 1029:                     document.docustom.newrolename.value = '';
 1030:                 }
 1031:             }
 1032:         }
 1033:     }
 1034:     return;
 1035: }
 1036: 
 1037: function setCustomAction(caller) {
 1038:     if (document.docustom.customroleaction.length > 0) {
 1039:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1040:             if (document.docustom.customroleaction[i].value == caller) {
 1041:                 document.docustom.customroleaction[i].checked = true;
 1042:             }
 1043:         }
 1044:     }
 1045:     setCustomFields();
 1046:     return;
 1047: }
 1048: 
 1049: // ]]>
 1050: </script>
 1051: END
 1052:     return $js;
 1053: }
 1054: 
 1055: sub entry_form {
 1056:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
 1057:     my ($usertype,$inexact);
 1058:     if (ref($srch) eq 'HASH') {
 1059:         if (($srch->{'srchin'} eq 'dom') &&
 1060:             ($srch->{'srchby'} eq 'uname') &&
 1061:             ($srch->{'srchtype'} eq 'exact') &&
 1062:             ($srch->{'srchdomain'} ne '') &&
 1063:             ($srch->{'srchterm'} ne '')) {
 1064:             my (%curr_rules,%got_rules);
 1065:             my ($rules,$ruleorder) =
 1066:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
 1067:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
 1068:         } else {
 1069:             $inexact = 1;
 1070:         }
 1071:     }
 1072:     my ($cancreate,$noinstd);
 1073:     if ($env{'form.action'} eq 'accesslogs') {
 1074:         $noinstd = 1;
 1075:     } else {
 1076:         $cancreate =
 1077:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
 1078:     }
 1079:     my ($userpicker,$cansearch) = 
 1080:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
 1081:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
 1082:     my $srchbutton = &mt('Search');
 1083:     if ($env{'form.action'} eq 'singlestudent') {
 1084:         $srchbutton = &mt('Search and Enroll');
 1085:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1086:         $srchbutton = &mt('Search');
 1087:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
 1088:         $srchbutton = &mt('Search or Add New User');
 1089:     }
 1090:     my $output;
 1091:     if ($cansearch) {
 1092:         $output = <<"ENDBLOCK";
 1093: <form action="/adm/createuser" method="post" name="crtuser">
 1094: <input type="hidden" name="action" value="$env{'form.action'}" />
 1095: <input type="hidden" name="phase" value="get_user_info" />
 1096: $userpicker
 1097: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 1098: </form>
 1099: ENDBLOCK
 1100:     } else {
 1101:         $output = '<p>'.$userpicker.'</p>';
 1102:     }
 1103:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
 1104:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1105:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
 1106:         my $defdom=$env{'request.role.domain'};
 1107:         my ($trusted,$untrusted);
 1108:         if ($context eq 'course') {
 1109:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
 1110:         } elsif ($context eq 'author') {
 1111:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
 1112:         } elsif ($context eq 'domain') {
 1113:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
 1114:         }
 1115:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
 1116:         my %lt=&Apache::lonlocal::texthash(
 1117:                   'enro' => 'Enroll one student',
 1118:                   'enrm' => 'Enroll one member',
 1119:                   'admo' => 'Add/modify a single user',
 1120:                   'crea' => 'create new user if required',
 1121:                   'uskn' => "username is known",
 1122:                   'crnu' => 'Create a new user',
 1123:                   'usr'  => 'Username',
 1124:                   'dom'  => 'in domain',
 1125:                   'enrl' => 'Enroll',
 1126:                   'cram'  => 'Create/Modify user',
 1127:         );
 1128:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
 1129:         my ($title,$buttontext,$showresponse);
 1130:         if ($env{'form.action'} eq 'singlestudent') {
 1131:             if ($crstype eq 'Community') {
 1132:                 $title = $lt{'enrm'};
 1133:             } else {
 1134:                 $title = $lt{'enro'};
 1135:             }
 1136:             $buttontext = $lt{'enrl'};
 1137:         } else {
 1138:             $title = $lt{'admo'};
 1139:             $buttontext = $lt{'cram'};
 1140:         }
 1141:         if ($cancreate) {
 1142:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
 1143:         } else {
 1144:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
 1145:         }
 1146:         if ($env{'form.origform'} eq 'crtusername') {
 1147:             $showresponse = $responsemsg;
 1148:         }
 1149:         $output .= <<"ENDDOCUMENT";
 1150: <br />
 1151: <form action="/adm/createuser" method="post" name="crtusername">
 1152: <input type="hidden" name="action" value="$env{'form.action'}" />
 1153: <input type="hidden" name="phase" value="createnewuser" />
 1154: <input type="hidden" name="srchtype" value="exact" />
 1155: <input type="hidden" name="srchby" value="uname" />
 1156: <input type="hidden" name="srchin" value="dom" />
 1157: <input type="hidden" name="forcenewuser" value="1" />
 1158: <input type="hidden" name="origform" value="crtusername" />
 1159: <h3>$title</h3>
 1160: $showresponse
 1161: <table>
 1162:  <tr>
 1163:   <td>$lt{'usr'}:</td>
 1164:   <td><input type="text" size="15" name="srchterm" /></td>
 1165:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
 1166:   <td>&nbsp;$sellink&nbsp;</td>
 1167:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
 1168:  </tr>
 1169: </table>
 1170: </form>
 1171: ENDDOCUMENT
 1172:     }
 1173:     return $output;
 1174: }
 1175: 
 1176: sub user_modification_js {
 1177:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1178:     
 1179:     return <<END;
 1180: <script type="text/javascript" language="Javascript">
 1181: // <![CDATA[
 1182: 
 1183:     $pjump_def
 1184:     $dc_setcourse_code
 1185: 
 1186:     function dateset() {
 1187:         eval("document.cu."+document.cu.pres_marker.value+
 1188:             ".value=document.cu.pres_value.value");
 1189:         modalWindow.close();
 1190:     }
 1191: 
 1192:     $nondc_setsection_code
 1193: // ]]>
 1194: </script>
 1195: END
 1196: }
 1197: 
 1198: # =================================================================== Phase two
 1199: sub print_user_selection_page {
 1200:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1201:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1202:     my $sortby = $env{'form.sortby'};
 1203: 
 1204:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1205:         $sortby = 'lastname';
 1206:     }
 1207: 
 1208:     my ($jsback,$elements) = &crumb_utilities();
 1209: 
 1210:     my $jscript = (<<ENDSCRIPT);
 1211: <script type="text/javascript">
 1212: // <![CDATA[
 1213: function pickuser(uname,udom) {
 1214:     document.usersrchform.seluname.value=uname;
 1215:     document.usersrchform.seludom.value=udom;
 1216:     document.usersrchform.phase.value="userpicked";
 1217:     document.usersrchform.submit();
 1218: }
 1219: 
 1220: $jsback
 1221: // ]]>
 1222: </script>
 1223: ENDSCRIPT
 1224: 
 1225:     my %lt=&Apache::lonlocal::texthash(
 1226:                                        'usrch'          => "User Search to add/modify roles",
 1227:                                        'stusrch'        => "User Search to enroll student",
 1228:                                        'memsrch'        => "User Search to enroll member",
 1229:                                        'srcva'          => "Search for a user and view access log information",
 1230:                                        'usrvu'          => "User Search to view user roles",
 1231:                                        'usel'           => "Select a user to add/modify roles",
 1232:                                        'suvr'           => "Select a user to view roles",
 1233:                                        'stusel'         => "Select a user to enroll as a student",
 1234:                                        'memsel'         => "Select a user to enroll as a member",
 1235:                                        'vacsel'         => "Select a user to view access log",
 1236:                                        'username'       => "username",
 1237:                                        'domain'         => "domain",
 1238:                                        'lastname'       => "last name",
 1239:                                        'firstname'      => "first name",
 1240:                                        'permanentemail' => "permanent e-mail",
 1241:                                       );
 1242:     if ($context eq 'requestcrs') {
 1243:         $r->print('<div>');
 1244:     } else {
 1245:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1246:         my $helpitem;
 1247:         if ($env{'form.action'} eq 'singleuser') {
 1248:             $helpitem = 'Course_Change_Privileges';
 1249:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1250:             $helpitem = 'Course_Add_Student';
 1251:         } elsif ($context eq 'author') {
 1252:             $helpitem = 'Author_Change_Privileges';
 1253:         } elsif ($context eq 'domain') {
 1254:             $helpitem = 'Domain_Change_Privileges';
 1255:         }
 1256:         push (@{$brcrum},
 1257:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1258:                    text => $breadcrumb_text{'search'},
 1259:                    faq  => 282,
 1260:                    bug  => 'Instructor Interface',},
 1261:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1262:                    text => $breadcrumb_text{'userpicked'},
 1263:                    faq  => 282,
 1264:                    bug  => 'Instructor Interface',
 1265:                    help => $helpitem}
 1266:                   );
 1267:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1268:         if ($env{'form.action'} eq 'singleuser') {
 1269:             my $readonly;
 1270:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1271:                 $readonly = 1;
 1272:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1273:             } else {
 1274:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1275:             }
 1276:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1277:             if ($readonly) {
 1278:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1279:             } else {
 1280:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1281:             }
 1282:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1283:             $r->print($jscript."<b>");
 1284:             if ($crstype eq 'Community') {
 1285:                 $r->print($lt{'memsrch'});
 1286:             } else {
 1287:                 $r->print($lt{'stusrch'});
 1288:             }
 1289:             $r->print("</b><br />");
 1290:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1291:             $r->print('</form><h3>');
 1292:             if ($crstype eq 'Community') {
 1293:                 $r->print($lt{'memsel'});
 1294:             } else {
 1295:                 $r->print($lt{'stusel'});
 1296:             }
 1297:             $r->print('</h3>');
 1298:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1299:             $r->print("<b>$lt{'srcva'}</b><br />");
 1300:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1301:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1302:         }
 1303:     }
 1304:     $r->print('<form name="usersrchform" method="post" action="">'.
 1305:               &Apache::loncommon::start_data_table()."\n".
 1306:               &Apache::loncommon::start_data_table_header_row()."\n".
 1307:               ' <th> </th>'."\n");
 1308:     foreach my $field (@fields) {
 1309:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1310:                   "'".$field."'".';document.usersrchform.submit();">'.
 1311:                   $lt{$field}.'</a></th>'."\n");
 1312:     }
 1313:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1314: 
 1315:     my @sorted_users = sort {
 1316:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1317:             ||
 1318:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1319:             ||
 1320:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1321: 	    ||
 1322: 	lc($a) cmp lc($b)
 1323:         } (keys(%$srch_results));
 1324: 
 1325:     foreach my $user (@sorted_users) {
 1326:         my ($uname,$udom) = split(/:/,$user);
 1327:         my $onclick;
 1328:         if ($context eq 'requestcrs') {
 1329:             $onclick =
 1330:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1331:                                                "'$srch_results->{$user}->{firstname}',".
 1332:                                                "'$srch_results->{$user}->{lastname}',".
 1333:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1334:         } else {
 1335:             $onclick =
 1336:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1337:         }
 1338:         $r->print(&Apache::loncommon::start_data_table_row().
 1339:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1340:                   $onclick.' /></td>'.
 1341:                   '<td><tt>'.$uname.'</tt></td>'.
 1342:                   '<td><tt>'.$udom.'</tt></td>');
 1343:         foreach my $field ('lastname','firstname','permanentemail') {
 1344:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1345:         }
 1346:         $r->print(&Apache::loncommon::end_data_table_row());
 1347:     }
 1348:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1349:     if (ref($srcharray) eq 'ARRAY') {
 1350:         foreach my $item (@{$srcharray}) {
 1351:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1352:         }
 1353:     }
 1354:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1355:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1356:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1357:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1358:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1359:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1360:     if ($context eq 'requestcrs') {
 1361:         $r->print($opener_elements.'</form></div>');
 1362:     } else {
 1363:         $r->print($response.'</form>');
 1364:     }
 1365: }
 1366: 
 1367: sub print_user_query_page {
 1368:     my ($r,$caller,$brcrum) = @_;
 1369: # FIXME - this is for a network-wide name search (similar to catalog search)
 1370: # To use frames with similar behavior to catalog/portfolio search.
 1371: # To be implemented. 
 1372:     return;
 1373: }
 1374: 
 1375: sub print_user_modification_page {
 1376:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1377:         $brcrum,$showcredits) = @_;
 1378:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1379:         my $usermsg = &mt('No username and/or domain provided.');
 1380:         $env{'form.phase'} = '';
 1381: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1382:                                    $permission);
 1383:         return;
 1384:     }
 1385:     my ($form,$formname);
 1386:     if ($env{'form.action'} eq 'singlestudent') {
 1387:         $form = 'document.enrollstudent';
 1388:         $formname = 'enrollstudent';
 1389:     } else {
 1390:         $form = 'document.cu';
 1391:         $formname = 'cu';
 1392:     }
 1393:     my %abv_auth = &auth_abbrev();
 1394:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1395:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1396:     if ($uhome eq 'no_host') {
 1397:         my $usertype;
 1398:         my ($rules,$ruleorder) =
 1399:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1400:             $usertype =
 1401:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1402:                                                       \%curr_rules,\%got_rules);
 1403:         my $cancreate =
 1404:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1405:                                                    $usertype);
 1406:         if (!$cancreate) {
 1407:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1408:             my %usertypetext = (
 1409:                 official   => 'institutional',
 1410:                 unofficial => 'non-institutional',
 1411:             );
 1412:             my $response;
 1413:             if ($env{'form.origform'} eq 'crtusername') {
 1414:                 $response = '<span class="LC_warning">'.
 1415:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1416:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1417:                             '</span><br />';
 1418:             }
 1419:             $response .= '<p class="LC_warning">'
 1420:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1421:                         .' ';
 1422:             if ($context eq 'domain') {
 1423:                 $response .= &mt('Please contact a [_1] for assistance.',
 1424:                                  &Apache::lonnet::plaintext('dc'));
 1425:             } else {
 1426:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1427:                                 ,'<a href="'.$helplink.'">','</a>');
 1428:             }
 1429:             $response .= '</p><br />';
 1430:             $env{'form.phase'} = '';
 1431:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1432:                                        $permission);
 1433:             return;
 1434:         }
 1435:         $newuser = 1;
 1436:         my $checkhash;
 1437:         my $checks = { 'username' => 1 };
 1438:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1439:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1440:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1441:         if (ref($alerts{'username'}) eq 'HASH') {
 1442:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1443:                 my $domdesc =
 1444:                     &Apache::lonnet::domain($ccdomain,'description');
 1445:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1446:                     my $userchkmsg;
 1447:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1448:                         $userchkmsg = 
 1449:                             &Apache::loncommon::instrule_disallow_msg('username',
 1450:                                                                  $domdesc,1).
 1451:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1452:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1453:                             'username');
 1454:                     }
 1455:                     $env{'form.phase'} = '';
 1456:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1457:                                                $permission);
 1458:                     return;
 1459:                 }
 1460:             }
 1461:         }
 1462:     } else {
 1463:         $newuser = 0;
 1464:     }
 1465:     if ($response) {
 1466:         $response = '<br />'.$response;
 1467:     }
 1468: 
 1469:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1470:     my $dc_setcourse_code = '';
 1471:     my $nondc_setsection_code = '';                                        
 1472:     my %loaditem;
 1473: 
 1474:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1475: 
 1476:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1477:                                     $crstype,$groupslist,$newuser,
 1478:                                     $formname,\%loaditem,$permission);
 1479:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1480:     my $helpitem = 'Course_Change_Privileges';
 1481:     if ($env{'form.action'} eq 'singlestudent') {
 1482:         $helpitem = 'Course_Add_Student';
 1483:     } elsif ($context eq 'author') {
 1484:         $helpitem = 'Author_Change_Privileges';
 1485:     } elsif ($context eq 'domain') {
 1486:         $helpitem = 'Domain_Change_Privileges';
 1487:         $js .= &set_custom_js();
 1488:     }
 1489:     push (@{$brcrum},
 1490:         {href => "javascript:backPage($form)",
 1491:          text => $breadcrumb_text{'search'},
 1492:          faq  => 282,
 1493:          bug  => 'Instructor Interface',});
 1494:     if ($env{'form.phase'} eq 'userpicked') {
 1495:        push(@{$brcrum},
 1496:               {href => "javascript:backPage($form,'get_user_info','select')",
 1497:                text => $breadcrumb_text{'userpicked'},
 1498:                faq  => 282,
 1499:                bug  => 'Instructor Interface',});
 1500:     }
 1501:     push(@{$brcrum},
 1502:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1503:              text => $breadcrumb_text{'modify'},
 1504:              faq  => 282,
 1505:              bug  => 'Instructor Interface',
 1506:              help => $helpitem});
 1507:     my $args = {'add_entries'           => \%loaditem,
 1508:                 'bread_crumbs'          => $brcrum,
 1509:                 'bread_crumbs_component' => 'User Management'};
 1510:     if ($env{'form.popup'}) {
 1511:         $args->{'no_nav_bar'} = 1;
 1512:     }
 1513:     if (($context eq 'domain') && ($env{'request.role.domain'} eq $ccdomain)) {
 1514:         my @toggles;
 1515:         if (&Apache::lonnet::allowed('cau',$ccdomain)) {
 1516:             my ($isadv,$isauthor) =
 1517:                 &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1518:             unless ($isauthor) {
 1519:                 push(@toggles,'requestauthor');
 1520:             }
 1521:             push(@toggles,('webdav','editors'));
 1522:         }
 1523:         if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1524:             push(@toggles,('aboutme','blog','portfolio','portaccess','timezone'));
 1525:         }
 1526:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1527:             push(@toggles,('official','unofficial','community','textbook','placement','lti'));
 1528:         }
 1529:         if (@toggles) {
 1530:             my $onload;
 1531:             foreach my $item (@toggles) {
 1532:                 $onload .= "toggleCustom(document.cu,'customtext_$item','custom$item');";
 1533:             }
 1534:             $args->{'add_entries'} = {
 1535:                                        'onload' => $onload,
 1536:                                      };
 1537:         }
 1538:     }
 1539:     my $start_page =
 1540:         &Apache::loncommon::start_page('User Management',$js,$args);
 1541: 
 1542:     my $forminfo =<<"ENDFORMINFO";
 1543: <form action="/adm/createuser" method="post" name="$formname">
 1544: <input type="hidden" name="phase" value="update_user_data" />
 1545: <input type="hidden" name="ccuname" value="$ccuname" />
 1546: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1547: <input type="hidden" name="pres_value"  value="" />
 1548: <input type="hidden" name="pres_type"   value="" />
 1549: <input type="hidden" name="pres_marker" value="" />
 1550: ENDFORMINFO
 1551:     my (%inccourses,$roledom,$defaultcredits);
 1552:     if ($context eq 'course') {
 1553:         $inccourses{$env{'request.course.id'}}=1;
 1554:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1555:         if ($showcredits) {
 1556:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1557:         }
 1558:     } elsif ($context eq 'author') {
 1559:         $roledom = $env{'request.role.domain'};
 1560:     } elsif ($context eq 'domain') {
 1561:         foreach my $key (keys(%env)) {
 1562:             $roledom = $env{'request.role.domain'};
 1563:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1564:                 $inccourses{$1.'_'.$2}=1;
 1565:             }
 1566:         }
 1567:     } else {
 1568:         foreach my $key (keys(%env)) {
 1569: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1570: 	        $inccourses{$1.'_'.$2}=1;
 1571:             }
 1572:         }
 1573:     }
 1574:     my $title = '';
 1575:     my $need_quota_js;
 1576:     if ($newuser) {
 1577:         my ($portfolioform,$domroleform);
 1578:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1579:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1580:             # Current user has quota or user tools modification privileges
 1581:             $portfolioform = '<br /><h3>'.
 1582:                              &mt('User Tools').
 1583:                              '</h3>'."\n".
 1584:                              &Apache::loncommon::start_data_table();
 1585:             if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1586:                 $portfolioform .= &build_tools_display($ccuname,$ccdomain,'tools');
 1587:             }
 1588:             if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1589:                 $portfolioform .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1590:                 $need_quota_js = 1;
 1591:             }
 1592:             $portfolioform .= &Apache::loncommon::end_data_table();
 1593:         }
 1594:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1595:             ($ccdomain eq $env{'request.role.domain'})) {
 1596:             $domroleform = &domainrole_req($ccuname,$ccdomain).
 1597:                            &authoring_defaults($ccuname,$ccdomain);
 1598:             $need_quota_js = 1;
 1599:         }
 1600:         my $readonly;
 1601:         unless ($permission->{'cusr'}) {
 1602:             $readonly = 1;
 1603:         }
 1604:         &initialize_authen_forms($ccdomain,$formname,'','',$readonly);
 1605:         my %lt=&Apache::lonlocal::texthash(
 1606:                 'lg'             => 'Login Data',
 1607:                 'hs'             => "Home Server",
 1608:         );
 1609: 	$r->print(<<ENDTITLE);
 1610: $start_page
 1611: $response
 1612: $forminfo
 1613: <script type="text/javascript" language="Javascript">
 1614: // <![CDATA[
 1615: $loginscript
 1616: // ]]>
 1617: </script>
 1618: <input type='hidden' name='makeuser' value='1' />
 1619: ENDTITLE
 1620:         if ($env{'form.action'} eq 'singlestudent') {
 1621:             if ($crstype eq 'Community') {
 1622:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1623:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1624:             } else {
 1625:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1626:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1627:             }
 1628:         } else {
 1629:                 $title = &mt('Create New User [_1] in domain [_2]',
 1630:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1631:         }
 1632:         $r->print('<h2>'.$title.'</h2>'."\n");
 1633:         $r->print('<div class="LC_left_float">');
 1634:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1635:                                          $inst_results{$ccuname.':'.$ccdomain},$readonly));
 1636:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1637:         my ($home_server_pick,$numlib) = 
 1638:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1639:                                                       'default','hide');
 1640:         if ($numlib > 1) {
 1641:             $r->print("
 1642: <br />
 1643: $lt{'hs'}: $home_server_pick
 1644: <br />");
 1645:         } else {
 1646:             $r->print($home_server_pick);
 1647:         }
 1648:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1649:             $r->print('<br /><h3>'.
 1650:                       &mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1651:                       &Apache::loncommon::start_data_table().
 1652:                       &build_tools_display($ccuname,$ccdomain,
 1653:                                            'requestcourses').
 1654:                       &Apache::loncommon::end_data_table());
 1655:         }
 1656:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1657:                   $lt{'lg'}.'</h3>');
 1658:         my ($fixedauth,$varauth,$authmsg); 
 1659:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1660:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1661:             my ($rules,$ruleorder) = 
 1662:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1663:             if (ref($rules) eq 'HASH') {
 1664:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1665:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1666:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1667:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1668:                     } else { 
 1669:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1670:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1671:                         if ($authtype =~ /^krb(4|5)$/) {
 1672:                             my $ver = $1;
 1673:                             if ($authparm ne '') {
 1674:                                 $fixedauth = <<"KERB"; 
 1675: <input type="hidden" name="login" value="krb" />
 1676: <input type="hidden" name="krbver" value="$ver" />
 1677: <input type="hidden" name="krbarg" value="$authparm" />
 1678: KERB
 1679:                             }
 1680:                         } else {
 1681:                             $fixedauth = 
 1682: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1683:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1684:                                 $fixedauth .=    
 1685: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1686:                             } else {
 1687:                                 if ($authtype eq 'int') {
 1688:                                     $varauth = '<br />'.
 1689: &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>';
 1690:                                 } elsif ($authtype eq 'loc') {
 1691:                                     $varauth = '<br />'.
 1692: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1693:                                 } else {
 1694:                                     $varauth =
 1695: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1696:                                 }
 1697:                             }
 1698:                         }
 1699:                     }
 1700:                 } else {
 1701:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1702:                 }
 1703:             }
 1704:             if ($authmsg) {
 1705:                 $r->print(<<ENDAUTH);
 1706: $fixedauth
 1707: $authmsg
 1708: $varauth
 1709: ENDAUTH
 1710:             }
 1711:         } else {
 1712:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1713:         }
 1714:         $r->print($portfolioform.$domroleform);
 1715:         if ($env{'form.action'} eq 'singlestudent') {
 1716:             $r->print(&date_sections_select($context,$newuser,$formname,
 1717:                                             $permission,$crstype,$ccuname,
 1718:                                             $ccdomain,$showcredits));
 1719:         }
 1720:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1721:     } else { # user already exists
 1722: 	$r->print($start_page.$forminfo);
 1723:         if ($env{'form.action'} eq 'singlestudent') {
 1724:             if ($crstype eq 'Community') {
 1725:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1726:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1727:             } else {
 1728:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1729:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1730:             }
 1731:         } else {
 1732:             if ($permission->{'cusr'}) {
 1733:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1734:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1735:             } else {
 1736:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1737:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1738:             }
 1739:         }
 1740:         $r->print('<h2>'.$title.'</h2>'."\n");
 1741:         $r->print('<div class="LC_left_float">');
 1742:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1743:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1744:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1745:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1746:             $r->print('<br /><h3>'.&mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1747:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1748:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1749:                 $r->print(&Apache::loncommon::start_data_table());
 1750:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1751:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1752:                 } else {
 1753:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1754:                                                       $env{'request.role.domain'}));
 1755:                 }
 1756:                 $r->print(&Apache::loncommon::end_data_table());
 1757:             } else {
 1758:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1759:                               &Apache::lonnet::domain($ccdomain,'description')));
 1760:             }
 1761:         }
 1762:         $r->print('</div>');
 1763:         my @order = ('auth','quota','tools','requestauthor','authordefaults');
 1764:         my %user_text;
 1765:         my ($isadv,$isauthor) = 
 1766:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1767:         if (((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1768:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1769:             ($env{'request.role.domain'} eq $ccdomain)) {
 1770:             if (!$isauthor) {
 1771:                 $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1772:             }
 1773:             $user_text{'authordefaults'} = &authoring_defaults($ccuname,$ccdomain);
 1774:             if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1775:                 $need_quota_js = 1;
 1776:             }
 1777:         }
 1778:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1779:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1780:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1781:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1782:             $user_text{'quota'} = '<br /><h3>'.&mt('User Tools').'</h3>'."\n".
 1783:                                   &Apache::loncommon::start_data_table();
 1784:             if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1785:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1786:                 $user_text{'quota'} .= &build_tools_display($ccuname,$ccdomain,'tools');
 1787:             }
 1788:             # Current user has quota modification privileges
 1789:             if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1790:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1791:                 $user_text{'quota'} .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1792:                 $need_quota_js = 1;
 1793:             }
 1794:             $user_text{'quota'} .= &Apache::loncommon::end_data_table();
 1795:         }
 1796:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1797:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1798:                 my %lt=&Apache::lonlocal::texthash(
 1799:                     'dska'  => "Disk quotas for user's portfolio",
 1800:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1801:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1802:                 );
 1803:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1804: <h3>$lt{'dska'}</h3>
 1805: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1806: ENDNOPORTPRIV
 1807:             }
 1808:         }
 1809:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1810:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1811:                 my %lt=&Apache::lonlocal::texthash(
 1812:                     'utav'  => "User Tools Availability",
 1813:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, Personal Information Page, or Time Zone settings for this user.",
 1814:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1815:                 );
 1816:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1817: <h3>$lt{'utav'}</h3>
 1818: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1819: ENDNOTOOLSPRIV
 1820:             }
 1821:         }
 1822:         my $gotdiv = 0; 
 1823:         foreach my $item (@order) {
 1824:             if ($user_text{$item} ne '') {
 1825:                 unless ($gotdiv) {
 1826:                     $r->print('<div class="LC_left_float">');
 1827:                     $gotdiv = 1;
 1828:                 }
 1829:                 $r->print('<br />'.$user_text{$item});
 1830:             }
 1831:         }
 1832:         if ($env{'form.action'} eq 'singlestudent') {
 1833:             unless ($gotdiv) {
 1834:                 $r->print('<div class="LC_left_float">');
 1835:             }
 1836:             my $credits;
 1837:             if ($showcredits) {
 1838:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1839:                 if ($credits eq '') {
 1840:                     $credits = $defaultcredits;
 1841:                 }
 1842:             }
 1843:             $r->print(&date_sections_select($context,$newuser,$formname,
 1844:                                             $permission,$crstype,$ccuname,
 1845:                                             $ccdomain,$showcredits));
 1846:         }
 1847:         if ($gotdiv) {
 1848:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1849:         }
 1850:         my $statuses;
 1851:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1852:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1853:             $statuses = ['active'];
 1854:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1855:                  ($env{'request.course.sec'} &&
 1856:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1857:             $statuses = ['active'];
 1858:         }
 1859:         if ($env{'form.action'} ne 'singlestudent') {
 1860:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1861:                                     $roledom,$crstype,$showcredits,$statuses);
 1862:         }
 1863:     } ## End of new user/old user logic
 1864:     if ($env{'form.action'} eq 'singlestudent') {
 1865:         my $btntxt;
 1866:         if ($crstype eq 'Community') {
 1867:             $btntxt = &mt('Enroll Member');
 1868:         } else {
 1869:             $btntxt = &mt('Enroll Student');
 1870:         }
 1871:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1872:     } elsif ($permission->{'cusr'}) {
 1873:         $r->print('<div class="LC_left_float">'.
 1874:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1875:         my $addrolesdisplay = 0;
 1876:         if ($context eq 'domain' || $context eq 'author') {
 1877:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1878:         }
 1879:         if ($context eq 'domain') {
 1880:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1881:             if (!$addrolesdisplay) {
 1882:                 $addrolesdisplay = $add_domainroles;
 1883:             }
 1884:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1885:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1886:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1887:         } elsif ($context eq 'author') {
 1888:             if ($addrolesdisplay) {
 1889:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1890:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1891:                 if ($newuser) {
 1892:                     $r->print(' onclick="auth_check()" \>'."\n");
 1893:                 } else {
 1894:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1895:                 }
 1896:             } else {
 1897:                 $r->print('</fieldset></div>'.
 1898:                           '<div class="LC_clear_float_footer"></div>'.
 1899:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1900:                           &mt('Back to previous page').'</a>');
 1901:             }
 1902:         } else {
 1903:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1904:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1905:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1906:         }
 1907:     }
 1908:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1909:     $r->print('<input type="hidden" name="currstate" value="" />');
 1910:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1911:     if ($need_quota_js) {
 1912:         $r->print(&user_quota_js());
 1913:     }
 1914:     return;
 1915: }
 1916: 
 1917: sub singleuser_breadcrumb {
 1918:     my ($crstype,$context,$domain) = @_;
 1919:     my %breadcrumb_text;
 1920:     if ($env{'form.action'} eq 'singlestudent') {
 1921:         if ($crstype eq 'Community') {
 1922:             $breadcrumb_text{'search'} = 'Enroll a member';
 1923:         } else {
 1924:             $breadcrumb_text{'search'} = 'Enroll a student';
 1925:         }
 1926:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1927:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1928:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1929:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1930:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1931:         $breadcrumb_text{'activity'} = 'Activity';
 1932:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1933:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1934:         $breadcrumb_text{'search'} = "View user's roles";
 1935:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1936:         $breadcrumb_text{'modify'} = 'User roles';
 1937:     } else {
 1938:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1939:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1940:         $breadcrumb_text{'modify'} = 'Set user role';
 1941:     }
 1942:     return %breadcrumb_text;
 1943: }
 1944: 
 1945: sub date_sections_select {
 1946:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1947:         $showcredits) = @_;
 1948:     my $credits;
 1949:     if ($showcredits) {
 1950:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1951:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1952:         if ($credits eq '') {
 1953:             $credits = $defaultcredits;
 1954:         }
 1955:     }
 1956:     my $cid = $env{'request.course.id'};
 1957:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1958:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1959:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1960:                                                   undef,$formname,$permission);
 1961:     my $rowtitle = 'Section';
 1962:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1963:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1964:                                               $permission,$context,'',$crstype,
 1965:                                               $showcredits,$credits);
 1966:     my $output = $date_table.$secbox;
 1967:     return $output;
 1968: }
 1969: 
 1970: sub validation_javascript {
 1971:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1972:         $loaditem,$permission) = @_;
 1973:     my $dc_setcourse_code = '';
 1974:     my $nondc_setsection_code = '';
 1975:     if ($context eq 'domain') {
 1976:         if ((ref($permission) eq 'HASH') && ($permission->{'cusr'})) {
 1977:             my $dcdom = $env{'request.role.domain'};
 1978:             $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1979:             $dc_setcourse_code =
 1980:                 &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1981:         }
 1982:     } else {
 1983:         my $checkauth; 
 1984:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1985:             $checkauth = 1;
 1986:         }
 1987:         if ($context eq 'course') {
 1988:             $nondc_setsection_code =
 1989:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1990:                                                               undef,$checkauth,
 1991:                                                               $crstype);
 1992:         }
 1993:         if ($checkauth) {
 1994:             $nondc_setsection_code .= 
 1995:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1996:         }
 1997:     }
 1998:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1999:                                    $nondc_setsection_code,$groupslist);
 2000:     my ($jsback,$elements) = &crumb_utilities();
 2001:     $js .= "\n".
 2002:            '<script type="text/javascript">'."\n".
 2003:            '// <![CDATA['."\n".
 2004:            $jsback."\n".
 2005:            '// ]]>'."\n".
 2006:            '</script>'."\n";
 2007:     return $js;
 2008: }
 2009: 
 2010: sub display_existing_roles {
 2011:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 2012:         $showcredits,$statuses) = @_;
 2013:     my $now=time;
 2014:     my $showall = 1;
 2015:     my ($showexpired,$showactive);
 2016:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 2017:         $showall = 0;
 2018:         if (grep(/^expired$/,@{$statuses})) {
 2019:             $showexpired = 1;
 2020:         }
 2021:         if (grep(/^active$/,@{$statuses})) {
 2022:             $showactive = 1;
 2023:         }
 2024:         if ($showexpired && $showactive) {
 2025:             $showall = 1;
 2026:         }
 2027:     }
 2028:     my %lt=&Apache::lonlocal::texthash(
 2029:                     'rer'  => "Existing Roles",
 2030:                     'rev'  => "Revoke",
 2031:                     'del'  => "Delete",
 2032:                     'ren'  => "Re-Enable",
 2033:                     'rol'  => "Role",
 2034:                     'ext'  => "Extent",
 2035:                     'crd'  => "Credits",
 2036:                     'sta'  => "Start",
 2037:                     'end'  => "End",
 2038:                                        );
 2039:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 2040:     if ($context eq 'course' || $context eq 'author') {
 2041:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 2042:         my %roleshash = 
 2043:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 2044:                               ['active','previous','future'],\@roles,$roledom,1);
 2045:         foreach my $key (keys(%roleshash)) {
 2046:             my ($start,$end) = split(':',$roleshash{$key});
 2047:             next if ($start eq '-1' || $end eq '-1');
 2048:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 2049:             if ($context eq 'course') {
 2050:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 2051:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 2052:             } elsif ($context eq 'author') {
 2053:                 if ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2054:                     my ($audom,$auname) = ($1,$2);
 2055:                     next unless (($rnum eq $auname) && ($rdom eq $audom));
 2056:                 } else {
 2057:                     next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 2058:                 }
 2059:             }
 2060:             my ($newkey,$newvalue,$newrole);
 2061:             $newkey = '/'.$rdom.'/'.$rnum;
 2062:             if ($sec ne '') {
 2063:                 $newkey .= '/'.$sec;
 2064:             }
 2065:             $newvalue = $role;
 2066:             if ($role =~ /^cr/) {
 2067:                 $newrole = 'cr';
 2068:             } else {
 2069:                 $newrole = $role;
 2070:             }
 2071:             $newkey .= '_'.$newrole;
 2072:             if ($start ne '' && $end ne '') {
 2073:                 $newvalue .= '_'.$end.'_'.$start;
 2074:             } elsif ($end ne '') {
 2075:                 $newvalue .= '_'.$end;
 2076:             }
 2077:             $rolesdump{$newkey} = $newvalue;
 2078:         }
 2079:     } else {
 2080:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 2081:     }
 2082:     # Build up table of user roles to allow revocation and re-enabling of roles.
 2083:     my ($tmp) = keys(%rolesdump);
 2084:     return if ($tmp =~ /^(con_lost|error)/i);
 2085:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 2086:                                 my $b1=join('_',(split('_',$b))[1,0]);
 2087:                                 return $a1 cmp $b1;
 2088:                             } keys(%rolesdump)) {
 2089:         next if ($area =~ /^rolesdef/);
 2090:         my $envkey=$area;
 2091:         my $role = $rolesdump{$area};
 2092:         my $thisrole=$area;
 2093:         $area =~ s/\_\w\w$//;
 2094:         my ($role_code,$role_end_time,$role_start_time) =
 2095:             split(/_/,$role);
 2096:         my $active=1;
 2097:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 2098:         if ($active) {
 2099:             next unless($showall || $showactive);
 2100:         } else {
 2101:             next unless($showall || $showexpired);
 2102:         }
 2103: # Is this a custom role? Get role owner and title.
 2104:         my ($croleudom,$croleuname,$croletitle)=
 2105:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 2106:         my $allowed=0;
 2107:         my $delallowed=0;
 2108:         my $sortkey=$role_code;
 2109:         my $class='Unknown';
 2110:         my $credits='';
 2111:         my $csec;
 2112:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 2113:             $class='Course';
 2114:             my ($coursedom,$coursedir) = ($1,$2);
 2115:             my $cid = $1.'_'.$2;
 2116:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 2117:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 2118:             my %coursedata=
 2119:                 &Apache::lonnet::coursedescription($cid);
 2120:             if ($coursedir =~ /^$match_community$/) {
 2121:                 $class='Community';
 2122:             }
 2123:             $sortkey.="\0$coursedom";
 2124:             my $carea;
 2125:             if (defined($coursedata{'description'})) {
 2126:                 $carea=$coursedata{'description'}.
 2127:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 2128:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 2129:                 $sortkey.="\0".$coursedata{'description'};
 2130:             } else {
 2131:                 if ($class eq 'Community') {
 2132:                     $carea=&mt('Unavailable community').': '.$area;
 2133:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 2134:                 } else {
 2135:                     $carea=&mt('Unavailable course').': '.$area;
 2136:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 2137:                 }
 2138:             }
 2139:             $sortkey.="\0$coursedir";
 2140:             $inccourses->{$cid}=1;
 2141:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 2142:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 2143:                 $credits =
 2144:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 2145:                                       $coursedom,$coursedir);
 2146:                 if ($credits eq '') {
 2147:                     $credits = $defaultcredits;
 2148:                 }
 2149:             }
 2150:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 2151:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2152:                 $allowed=1;
 2153:             }
 2154:             unless ($allowed) {
 2155:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 2156:                 if ($isowner) {
 2157:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 2158:                         $allowed = 1;
 2159:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 2160:                         $allowed = 1;
 2161:                     }
 2162:                 }
 2163:             } 
 2164:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 2165:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 2166:                 $delallowed=1;
 2167:             }
 2168: # - custom role. Needs more info, too
 2169:             if ($croletitle) {
 2170:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 2171:                     $allowed=1;
 2172:                     $thisrole.='.'.$role_code;
 2173:                 }
 2174:             }
 2175:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 2176:                 $csec = $2;
 2177:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 2178:                 $sortkey.="\0$csec";
 2179:                 if (!$allowed) {
 2180:                     if ($env{'request.course.sec'} eq $csec) {
 2181:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 2182:                             $allowed = 1;
 2183:                         }
 2184:                     }
 2185:                 }
 2186:             }
 2187:             $area=$carea;
 2188:         } else {
 2189:             $sortkey.="\0".$area;
 2190:             # Determine if current user is able to revoke privileges
 2191:             if ($area=~m{^/($match_domain)/}) {
 2192:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 2193:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2194:                    $allowed=1;
 2195:                 }
 2196:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 2197:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 2198:                     ($role_code ne 'dc')) {
 2199:                     $delallowed=1;
 2200:                 }
 2201:             } else {
 2202:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 2203:                     $allowed=1;
 2204:                 }
 2205:             }
 2206:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 2207:                 $class='Authoring Space';
 2208:             } elsif ($role_code eq 'su') {
 2209:                 $class='System';
 2210:             } else {
 2211:                 $class='Domain';
 2212:             }
 2213:         }
 2214:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 2215:             $area=~m{/($match_domain)/($match_username)};
 2216:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 2217:                 $allowed=1;
 2218:             } elsif (&Apache::lonuserutils::coauthorpriv($2,$1)) {
 2219:                 $allowed=1;
 2220:             } else {
 2221:                 $allowed=0;
 2222:             }
 2223:         }
 2224:         my $row = '';
 2225:         if ($showall) {
 2226:             $row.= '<td>';
 2227:             if (($active) && ($allowed)) {
 2228:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 2229:             } else {
 2230:                 if ($active) {
 2231:                     $row.='&nbsp;';
 2232:                 } else {
 2233:                     $row.=&mt('expired or revoked');
 2234:                 }
 2235:             }
 2236:             $row.='</td><td>';
 2237:             if ($allowed && !$active) {
 2238:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 2239:             } else {
 2240:                 $row.='&nbsp;';
 2241:             }
 2242:             $row.='</td><td>';
 2243:             if ($delallowed) {
 2244:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 2245:             } else {
 2246:                 $row.='&nbsp;';
 2247:             }
 2248:             $row.= '</td>';
 2249:         }
 2250:         my $plaintext='';
 2251:         if (!$croletitle) {
 2252:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2253:             if (($showcredits) && ($credits ne '')) {
 2254:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2255:                               '<span class="LC_fontsize_small">'.
 2256:                               &mt('Credits: [_1]',$credits).
 2257:                               '</span></span>';
 2258:             }
 2259:         } else {
 2260:             $plaintext=
 2261:                 &mt('Custom role [_1][_2]defined by [_3]',
 2262:                         '"'.$croletitle.'"',
 2263:                         '<br />',
 2264:                         $croleuname.':'.$croleudom);
 2265:         }
 2266:         $row.= '<td>'.$plaintext.'</td>'.
 2267:                '<td>'.$area.'</td>'.
 2268:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2269:                                             : '&nbsp;' ).'</td>'.
 2270:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2271:                                             : '&nbsp;' ).'</td>';
 2272:         $sortrole{$sortkey}=$envkey;
 2273:         $roletext{$envkey}=$row;
 2274:         $roleclass{$envkey}=$class;
 2275:         if ($allowed) {
 2276:             $rolepriv{$envkey}='edit';
 2277:         } else {
 2278:             if ($context eq 'domain') {
 2279:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2280:                     ($envkey=~m{^/$ccdomain/})) {
 2281:                     $rolepriv{$envkey}='view';
 2282:                 }
 2283:             } elsif ($context eq 'course') {
 2284:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2285:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2286:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2287:                     $rolepriv{$envkey}='view';
 2288:                 }
 2289:             }
 2290:         }
 2291:     } # end of foreach        (table building loop)
 2292: 
 2293:     my $rolesdisplay = 0;
 2294:     my %output = ();
 2295:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2296:         $output{$type} = '';
 2297:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2298:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2299:                  $output{$type}.=
 2300:                       &Apache::loncommon::start_data_table_row().
 2301:                       $roletext{$sortrole{$which}}.
 2302:                       &Apache::loncommon::end_data_table_row();
 2303:             }
 2304:         }
 2305:         unless($output{$type} eq '') {
 2306:             $output{$type} = '<tr class="LC_info_row">'.
 2307:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2308:                       $output{$type};
 2309:             $rolesdisplay = 1;
 2310:         }
 2311:     }
 2312:     if ($rolesdisplay == 1) {
 2313:         my $contextrole='';
 2314:         if ($env{'request.course.id'}) {
 2315:             if (&Apache::loncommon::course_type() eq 'Community') {
 2316:                 $contextrole = &mt('Existing Roles in this Community');
 2317:             } else {
 2318:                 $contextrole = &mt('Existing Roles in this Course');
 2319:             }
 2320:         } elsif ($env{'request.role'} =~ /^au\./) {
 2321:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2322:         } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)/$}) {
 2323:             $contextrole = &mt('Existing Co-Author Roles in [_1] Authoring Space',
 2324:                                '<i>'.$1.'_'.$2.'</i>');
 2325:         } else {
 2326:             if ($showall) {
 2327:                 $contextrole = &mt('Existing Roles in this Domain');
 2328:             } elsif ($showactive) {
 2329:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2330:             } elsif ($showexpired) {
 2331:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2332:             }
 2333:         }
 2334:         $r->print('<div class="LC_left_float">'.
 2335: '<fieldset><legend>'.$contextrole.'</legend>'.
 2336: &Apache::loncommon::start_data_table("LC_createuser").
 2337: &Apache::loncommon::start_data_table_header_row());
 2338:         if ($showall) {
 2339:             $r->print(
 2340: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2341:             );
 2342:         } elsif ($showexpired) {
 2343:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2344:         }
 2345:         $r->print(
 2346: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2347: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2348: &Apache::loncommon::end_data_table_header_row());
 2349:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2350:             if ($output{$type}) {
 2351:                 $r->print($output{$type}."\n");
 2352:             }
 2353:         }
 2354:         $r->print(&Apache::loncommon::end_data_table().
 2355:                   '</fieldset></div>');
 2356:     }
 2357:     return;
 2358: }
 2359: 
 2360: sub new_coauthor_roles {
 2361:     my ($r,$ccuname,$ccdomain) = @_;
 2362:     my $addrolesdisplay = 0;
 2363:     #
 2364:     # Co-Author
 2365:     #
 2366:     my ($cuname,$cudom);
 2367:     if (($env{'request.role'} eq "au./$env{'user.domain'}/") ||
 2368:         ($env{'request.role'} eq "dc./$env{'user.domain'}/")) {
 2369:         $cuname=$env{'user.name'};
 2370:         $cudom=$env{'request.role.domain'};
 2371:         # No sense in assigning co-author role to yourself
 2372:         if ((&Apache::lonuserutils::authorpriv($cuname,$cudom)) &&
 2373:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2374:             $addrolesdisplay = 1;
 2375:         }
 2376:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2377:         ($cudom,$cuname) = ($1,$2);
 2378:         if ((&Apache::lonuserutils::coauthorpriv($cuname,$cudom)) &&
 2379:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain) &&
 2380:             ($cudom ne $ccdomain || $cuname ne $ccuname)) {
 2381:             $addrolesdisplay = 1;
 2382:         }
 2383:     }
 2384:     if ($addrolesdisplay) {
 2385:         my %lt=&Apache::lonlocal::texthash(
 2386:                     'cs'   => "Authoring Space",
 2387:                     'act'  => "Activate",
 2388:                     'rol'  => "Role",
 2389:                     'ext'  => "Extent",
 2390:                     'sta'  => "Start",
 2391:                     'end'  => "End",
 2392:                     'cau'  => "Co-Author",
 2393:                     'caa'  => "Assistant Co-Author",
 2394:                     'ssd'  => "Set Start Date",
 2395:                     'sed'  => "Set End Date"
 2396:                                        );
 2397:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2398:                   &Apache::loncommon::start_data_table()."\n".
 2399:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2400:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2401:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2402:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2403:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2404:                   &Apache::loncommon::start_data_table_row().'
 2405:            <td>
 2406:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2407:            </td>
 2408:            <td>'.$lt{'cau'}.'</td>
 2409:            <td>'.$cudom.'_'.$cuname.'</td>
 2410:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2411:              <a href=
 2412: "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>
 2413: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2414: <a href=
 2415: "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".
 2416:               &Apache::loncommon::end_data_table_row()."\n".
 2417:               &Apache::loncommon::start_data_table_row()."\n".
 2418: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2419: <td>'.$lt{'caa'}.'</td>
 2420: <td>'.$cudom.'_'.$cuname.'</td>
 2421: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2422: <a href=
 2423: "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>
 2424: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2425: <a href=
 2426: "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".
 2427:              &Apache::loncommon::end_data_table_row()."\n".
 2428:              &Apache::loncommon::end_data_table());
 2429:     } elsif ($env{'request.role'} =~ /^au\./) {
 2430:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2431:                                                 $env{'request.role.domain'}))) {
 2432:             $r->print('<span class="LC_error">'.
 2433:                       &mt('You do not have privileges to assign co-author roles.').
 2434:                       '</span>');
 2435:         } elsif (($env{'user.name'} eq $ccuname) &&
 2436:              ($env{'user.domain'} eq $ccdomain)) {
 2437:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2438:         }
 2439:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2440:         if (!(&Apache::lonuserutils::coauthorpriv($2,$1))) {
 2441:             $r->print('<span class="LC_error">'.
 2442:                       &mt('You do not have privileges to assign co-author roles.').
 2443:                       '</span>');
 2444:         } elsif (($env{'user.name'} eq $ccuname) &&
 2445:              ($env{'user.domain'} eq $ccdomain)) {
 2446:             $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'));
 2447:         } elsif (($cudom eq $ccdomain) && ($cuname eq $ccuname)) {
 2448:             $r->print(&mt("Assigning a co-author or assistant co-author role to an Authoring Space's author is not permitted"));
 2449:         }
 2450:     }
 2451:     return $addrolesdisplay;;
 2452: }
 2453: 
 2454: sub new_domain_roles {
 2455:     my ($r,$ccdomain) = @_;
 2456:     my $addrolesdisplay = 0;
 2457:     #
 2458:     # Domain level
 2459:     #
 2460:     my $num_domain_level = 0;
 2461:     my $domaintext =
 2462:     '<h4>'.&mt('Domain Level').'</h4>'.
 2463:     &Apache::loncommon::start_data_table().
 2464:     &Apache::loncommon::start_data_table_header_row().
 2465:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2466:     &mt('Extent').'</th>'.
 2467:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2468:     &Apache::loncommon::end_data_table_header_row();
 2469:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2470:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2471:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2472:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2473:         foreach my $role (@allroles) {
 2474:             next if ($role eq 'ad');
 2475:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2476:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2477:                if ($role eq 'dc') {
 2478:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2479:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2480:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2481:                        next unless ($uintdom eq $intdom);
 2482:                    }
 2483:                }
 2484:                my $plrole=&Apache::lonnet::plaintext($role);
 2485:                my %lt=&Apache::lonlocal::texthash(
 2486:                     'ssd'  => "Set Start Date",
 2487:                     'sed'  => "Set End Date"
 2488:                                        );
 2489:                $num_domain_level ++;
 2490:                $domaintext .=
 2491: &Apache::loncommon::start_data_table_row().
 2492: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2493: <td>'.$plrole.'</td>
 2494: <td>'.$thisdomain.'</td>
 2495: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2496: <a href=
 2497: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2498: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2499: <a href=
 2500: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2501: &Apache::loncommon::end_data_table_row();
 2502:             }
 2503:         }
 2504:     }
 2505:     $domaintext.= &Apache::loncommon::end_data_table();
 2506:     if ($num_domain_level > 0) {
 2507:         $r->print($domaintext);
 2508:         $addrolesdisplay = 1;
 2509:     }
 2510:     return $addrolesdisplay;
 2511: }
 2512: 
 2513: sub user_authentication {
 2514:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2515:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2516:     my $outcome;
 2517:     my %lt=&Apache::lonlocal::texthash(
 2518:                    'err'   => "ERROR",
 2519:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2520:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2521:                    'sldb'  => "Please specify login data below",
 2522:                    'ld'    => "Login Data"
 2523:     );
 2524:     # Check for a bad authentication type
 2525:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2526:         # bad authentication scheme
 2527:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2528:             &initialize_authen_forms($ccdomain,$formname);
 2529: 
 2530:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2531:             $outcome = <<ENDBADAUTH;
 2532: <script type="text/javascript" language="Javascript">
 2533: // <![CDATA[
 2534: $loginscript
 2535: // ]]>
 2536: </script>
 2537: <span class="LC_error">$lt{'err'}:
 2538: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2539: <h3>$lt{'ld'}</h3>
 2540: $choices
 2541: ENDBADAUTH
 2542:         } else {
 2543:             # This user is not allowed to modify the user's
 2544:             # authentication scheme, so just notify them of the problem
 2545:             $outcome = <<ENDBADAUTH;
 2546: <span class="LC_error"> $lt{'err'}: 
 2547: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2548: </span>
 2549: ENDBADAUTH
 2550:         }
 2551:     } else { # Authentication type is valid
 2552:         
 2553:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2554:         my ($authformcurrent,$can_modify,@authform_others) =
 2555:             &modify_login_block($ccdomain,$currentauth);
 2556:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2557:             # Current user has login modification privileges
 2558:             $outcome =
 2559:                        '<script type="text/javascript" language="Javascript">'."\n".
 2560:                        '// <![CDATA['."\n".
 2561:                        $loginscript."\n".
 2562:                        '// ]]>'."\n".
 2563:                        '</script>'."\n".
 2564:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2565:                        &Apache::loncommon::start_data_table().
 2566:                        &Apache::loncommon::start_data_table_row().
 2567:                        '<td>'.$authformnop;
 2568:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2569:                 $outcome .= '</td>'."\n".
 2570:                             &Apache::loncommon::end_data_table_row().
 2571:                             &Apache::loncommon::start_data_table_row().
 2572:                             '<td>'.$authformcurrent.'</td>'.
 2573:                             &Apache::loncommon::end_data_table_row()."\n";
 2574:             } else {
 2575:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2576:                             &Apache::loncommon::end_data_table_row()."\n";
 2577:             }
 2578:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2579:                 foreach my $item (@authform_others) { 
 2580:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2581:                                 '<td>'.$item.'</td>'.
 2582:                                 &Apache::loncommon::end_data_table_row()."\n";
 2583:                 }
 2584:             }
 2585:             $outcome .= &Apache::loncommon::end_data_table();
 2586:         } else {
 2587:             if (($currentauth =~ /^internal:/) &&
 2588:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2589:                 $outcome = <<"ENDJS";
 2590: <script type="text/javascript">
 2591: // <![CDATA[
 2592: function togglePwd(form) {
 2593:     if (form.newintpwd.length) {
 2594:         if (document.getElementById('LC_ownersetpwd')) {
 2595:             for (var i=0; i<form.newintpwd.length; i++) {
 2596:                 if (form.newintpwd[i].checked) {
 2597:                     if (form.newintpwd[i].value == 1) {
 2598:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2599:                     } else {
 2600:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2601:                     }
 2602:                 }
 2603:             }
 2604:         }
 2605:     }
 2606: }
 2607: // ]]>
 2608: </script>
 2609: ENDJS
 2610: 
 2611:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2612:                             &Apache::loncommon::start_data_table().
 2613:                             &Apache::loncommon::start_data_table_row().
 2614:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2615:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2616:                             &mt('No').'</label>'.('&nbsp;'x2).
 2617:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2618:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2619:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2620:                             '<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>'.
 2621:                             &Apache::loncommon::end_data_table_row().
 2622:                             &Apache::loncommon::end_data_table();
 2623:             }
 2624:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2625:                 # Current user has rights to view domain preferences for user's domain
 2626:                 my $result;
 2627:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2628:                     my ($krbver,$krbrealm) = ($1,$2);
 2629:                     if ($krbrealm eq '') {
 2630:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2631:                     } else {
 2632:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2633:                                       $krbrealm,$krbver);
 2634:                     }
 2635:                 } elsif ($currentauth =~ /^internal:/) {
 2636:                     $result = &mt('Currently internally authenticated.');
 2637:                 } elsif ($currentauth =~ /^localauth:/) {
 2638:                     $result = &mt('Currently using local (institutional) authentication.');
 2639:                 } elsif ($currentauth =~ /^unix:/) {
 2640:                     $result = &mt('Currently Filesystem Authenticated.');
 2641:                 } elsif ($currentauth =~ /^lti:/) {
 2642:                     $result = &mt('Currently LTI authenticated.');
 2643:                 }
 2644:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2645:                            &Apache::loncommon::start_data_table().
 2646:                            &Apache::loncommon::start_data_table_row().
 2647:                            '<td>'.$result.'</td>'.
 2648:                            &Apache::loncommon::end_data_table_row()."\n".
 2649:                            &Apache::loncommon::end_data_table();
 2650:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2651:                 my %lt=&Apache::lonlocal::texthash(
 2652:                            'ccld'  => "Change Current Login Data",
 2653:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2654:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2655:                 );
 2656:                 $outcome .= <<ENDNOPRIV;
 2657: <h3>$lt{'ccld'}</h3>
 2658: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2659: <input type="hidden" name="login" value="nochange" />
 2660: ENDNOPRIV
 2661:             }
 2662:         }
 2663:     }  ## End of "check for bad authentication type" logic
 2664:     return $outcome;
 2665: }
 2666: 
 2667: sub modify_login_block {
 2668:     my ($dom,$currentauth) = @_;
 2669:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2670:     my ($authnum,%can_assign) =
 2671:         &Apache::loncommon::get_assignable_auth($dom);
 2672:     my ($authformcurrent,@authform_others,$show_override_msg);
 2673:     if ($currentauth=~/^krb(4|5):/) {
 2674:         $authformcurrent=$authformkrb;
 2675:         if ($can_assign{'int'}) {
 2676:             push(@authform_others,$authformint);
 2677:         }
 2678:         if ($can_assign{'loc'}) {
 2679:             push(@authform_others,$authformloc);
 2680:         }
 2681:         if ($can_assign{'lti'}) {
 2682:             push(@authform_others,$authformlti);
 2683:         }
 2684:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2685:             $show_override_msg = 1;
 2686:         }
 2687:     } elsif ($currentauth=~/^internal:/) {
 2688:         $authformcurrent=$authformint;
 2689:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2690:             push(@authform_others,$authformkrb);
 2691:         }
 2692:         if ($can_assign{'loc'}) {
 2693:             push(@authform_others,$authformloc);
 2694:         }
 2695:         if ($can_assign{'lti'}) {
 2696:             push(@authform_others,$authformlti);
 2697:         }
 2698:         if ($can_assign{'int'}) {
 2699:             $show_override_msg = 1;
 2700:         }
 2701:     } elsif ($currentauth=~/^unix:/) {
 2702:         $authformcurrent=$authformfsys;
 2703:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2704:             push(@authform_others,$authformkrb);
 2705:         }
 2706:         if ($can_assign{'int'}) {
 2707:             push(@authform_others,$authformint);
 2708:         }
 2709:         if ($can_assign{'loc'}) {
 2710:             push(@authform_others,$authformloc);
 2711:         }
 2712:         if ($can_assign{'lti'}) {
 2713:             push(@authform_others,$authformlti);
 2714:         }
 2715:         if ($can_assign{'fsys'}) {
 2716:             $show_override_msg = 1;
 2717:         }
 2718:     } elsif ($currentauth=~/^localauth:/) {
 2719:         $authformcurrent=$authformloc;
 2720:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2721:             push(@authform_others,$authformkrb);
 2722:         }
 2723:         if ($can_assign{'int'}) {
 2724:             push(@authform_others,$authformint);
 2725:         }
 2726:         if ($can_assign{'lti'}) {
 2727:             push(@authform_others,$authformlti);
 2728:         }
 2729:         if ($can_assign{'loc'}) {
 2730:             $show_override_msg = 1;
 2731:         }
 2732:     } elsif ($currentauth=~/^lti:/) {
 2733:         $authformcurrent=$authformlti;
 2734:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2735:             push(@authform_others,$authformkrb);
 2736:         }
 2737:         if ($can_assign{'int'}) {
 2738:             push(@authform_others,$authformint);
 2739:         }
 2740:         if ($can_assign{'loc'}) {
 2741:             push(@authform_others,$authformloc);
 2742:         }
 2743:     }
 2744:     if ($show_override_msg) {
 2745:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2746:                            '</td></tr>'."\n".
 2747:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2748:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2749:                            '<td align="right"><span class="LC_cusr_emph">'.
 2750:                             &mt('will override current values').
 2751:                             '</span></td></tr></table>';
 2752:     }
 2753:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2754: }
 2755: 
 2756: sub personal_data_display {
 2757:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$readonly,$rolesarray,$now,
 2758:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2759:     my ($output,%userenv,%canmodify,%canmodify_status,$disabled);
 2760:     my @userinfo = ('firstname','middlename','lastname','generation',
 2761:                     'permanentemail','id');
 2762:     my $rowcount = 0;
 2763:     my $editable = 0;
 2764:     my %textboxsize = (
 2765:                        firstname      => '15',
 2766:                        middlename     => '15',
 2767:                        lastname       => '15',
 2768:                        generation     => '5',
 2769:                        permanentemail => '25',
 2770:                        id             => '15',
 2771:                       );
 2772: 
 2773:     my %lt=&Apache::lonlocal::texthash(
 2774:                 'pd'             => "Personal Data",
 2775:                 'firstname'      => "First Name",
 2776:                 'middlename'     => "Middle Name",
 2777:                 'lastname'       => "Last Name",
 2778:                 'generation'     => "Generation",
 2779:                 'permanentemail' => "Permanent e-mail address",
 2780:                 'id'             => "Student/Employee ID",
 2781:                 'lg'             => "Login Data",
 2782:                 'inststatus'     => "Affiliation",
 2783:                 'email'          => 'E-mail address',
 2784:                 'valid'          => 'Validation',
 2785:                 'username'       => 'Username',
 2786:     );
 2787: 
 2788:     %canmodify_status =
 2789:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2790:                                                    ['inststatus'],$rolesarray);
 2791:     if (!$newuser) {
 2792:         # Get the users information
 2793:         %userenv = &Apache::lonnet::get('environment',
 2794:                    ['firstname','middlename','lastname','generation',
 2795:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2796:         %canmodify =
 2797:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2798:                                                        \@userinfo,$rolesarray);
 2799:     } elsif ($context eq 'selfcreate') {
 2800:         if ($newuser eq 'email') {
 2801:             if (ref($emailusername) eq 'HASH') {
 2802:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2803:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2804:                     @userinfo = ();
 2805:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2806:                         foreach my $field (@{$infofields}) { 
 2807:                             if ($emailusername->{$usertype}->{$field}) {
 2808:                                 push(@userinfo,$field);
 2809:                                 $canmodify{$field} = 1;
 2810:                                 unless ($textboxsize{$field}) {
 2811:                                     $textboxsize{$field} = 25;
 2812:                                 }
 2813:                                 unless ($lt{$field}) {
 2814:                                     $lt{$field} = $infotitles->{$field};
 2815:                                 }
 2816:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2817:                                     $lt{$field} .= '<b>*</b>';
 2818:                                 }
 2819:                             }
 2820:                         }
 2821:                     }
 2822:                 }
 2823:             }
 2824:         } else {
 2825:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2826:                                                $inst_results,$rolesarray);
 2827:         }
 2828:     } elsif ($readonly) {
 2829:         $disabled = ' disabled="disabled"';
 2830:     }
 2831: 
 2832:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2833:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2834:               &Apache::lonhtmlcommon::start_pick_box();
 2835:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2836:         my $size = 25;
 2837:         if ($condition) {
 2838:             if ($condition =~ /^\@[^\@]+$/) {
 2839:                 $size = 10;
 2840:             } else {
 2841:                 undef($condition);
 2842:             }
 2843:         } 
 2844:         if ($excluded) {
 2845:             unless ($excluded =~ /^\@[^\@]+$/) {
 2846:                 undef($condition);
 2847:             }
 2848:         }
 2849:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2850:                                                      'LC_oddrow_value')."\n".
 2851:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2852:         if ($condition) {
 2853:             $output .= $condition;
 2854:         } elsif ($excluded) {
 2855:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2856:                                                                      $excluded).'</span>';
 2857:         }
 2858:         if ($usernameset eq 'first') {
 2859:             $output .= '<br /><span style="font-size: smaller">';
 2860:             if ($condition) {
 2861:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2862:                                       $condition);
 2863:             } else {
 2864:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2865:             }
 2866:             $output .= '</span>';
 2867:         }
 2868:         $rowcount ++;
 2869:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2870:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2871:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2872:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2873:                                                     'LC_pick_box_title',
 2874:                                                     'LC_oddrow_value')."\n".
 2875:                    $upassone."\n".
 2876:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2877:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2878:                                                      'LC_pick_box_title',
 2879:                                                      'LC_oddrow_value')."\n".
 2880:                    $upasstwo.
 2881:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2882:         if ($usernameset eq 'free') {
 2883:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2884:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2885:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2886:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2887:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2888:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2889:                        &mt('No').'</label></span>'."\n".
 2890:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2891:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2892:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2893:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2894:             $rowcount ++;
 2895:         }
 2896:     }
 2897:     foreach my $item (@userinfo) {
 2898:         my $rowtitle = $lt{$item};
 2899:         my $hiderow = 0;
 2900:         if ($item eq 'generation') {
 2901:             $rowtitle = $genhelp.$rowtitle;
 2902:         }
 2903:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2904:         if ($newuser) {
 2905:             if (ref($inst_results) eq 'HASH') {
 2906:                 if ($inst_results->{$item} ne '') {
 2907:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2908:                 } else {
 2909:                     if ($context eq 'selfcreate') {
 2910:                         if ($canmodify{$item}) {
 2911:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2912:                             $editable ++;
 2913:                         } else {
 2914:                             $hiderow = 1;
 2915:                         }
 2916:                     } else {
 2917:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2918:                     }
 2919:                 }
 2920:             } else {
 2921:                 if ($context eq 'selfcreate') {
 2922:                     if ($canmodify{$item}) {
 2923:                         if ($newuser eq 'email') {
 2924:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2925:                         } else {
 2926:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2927:                         }
 2928:                         $editable ++;
 2929:                     } else {
 2930:                         $hiderow = 1;
 2931:                     }
 2932:                 } else {
 2933:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2934:                 }
 2935:             }
 2936:         } else {
 2937:             if ($canmodify{$item}) {
 2938:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2939:                 if (($item eq 'id') && (!$newuser)) {
 2940:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2941:                 }
 2942:             } else {
 2943:                 $row .= $userenv{$item};
 2944:             }
 2945:         }
 2946:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2947:         if (!$hiderow) {
 2948:             $output .= $row;
 2949:             $rowcount ++;
 2950:         }
 2951:     }
 2952:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2953:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2954:         if (ref($types) eq 'ARRAY') {
 2955:             if (@{$types} > 0) {
 2956:                 my ($hiderow,$shown);
 2957:                 if ($canmodify_status{'inststatus'}) {
 2958:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2959:                 } else {
 2960:                     if ($userenv{'inststatus'} eq '') {
 2961:                         $hiderow = 1;
 2962:                     } else {
 2963:                         my @showitems;
 2964:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2965:                             if (exists($usertypes->{$item})) {
 2966:                                 push(@showitems,$usertypes->{$item});
 2967:                             } else {
 2968:                                 push(@showitems,$item);
 2969:                             }
 2970:                         }
 2971:                         if (@showitems) {
 2972:                             $shown = join(', ',@showitems);
 2973:                         } else {
 2974:                             $hiderow = 1;
 2975:                         }
 2976:                     }
 2977:                 }
 2978:                 if (!$hiderow) {
 2979:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2980:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2981:                     if ($context eq 'selfcreate') {
 2982:                         $rowcount ++;
 2983:                     }
 2984:                     $output .= $row;
 2985:                 }
 2986:             }
 2987:         }
 2988:     }
 2989:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2990:         if ($captchaform) {
 2991:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2992:                                                          'LC_pick_box_title')."\n".
 2993:                        $captchaform."\n".'<br /><br />'.
 2994:                        &Apache::lonhtmlcommon::row_closure(1); 
 2995:             $rowcount ++;
 2996:         }
 2997:         if ($showsubmit) {
 2998:             my $submit_text = &mt('Create account');
 2999:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 3000:                        '<br /><input type="submit" name="createaccount" value="'.
 3001:                        $submit_text.'" />';
 3002:             if ($usertype ne '') {
 3003:                 $output .= '<input type="hidden" name="type" value="'.
 3004:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 3005:             }
 3006:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 3007:         }
 3008:     }
 3009:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 3010:     if (wantarray) {
 3011:         if ($context eq 'selfcreate') {
 3012:             return($output,$rowcount,$editable);
 3013:         } else {
 3014:             return $output;
 3015:         }
 3016:     } else {
 3017:         return $output;
 3018:     }
 3019: }
 3020: 
 3021: sub pick_inst_statuses {
 3022:     my ($curr,$usertypes,$types) = @_;
 3023:     my ($output,$rem,@currtypes);
 3024:     if ($curr ne '') {
 3025:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 3026:     }
 3027:     my $numinrow = 2;
 3028:     if (ref($types) eq 'ARRAY') {
 3029:         $output = '<table>';
 3030:         my $lastcolspan; 
 3031:         for (my $i=0; $i<@{$types}; $i++) {
 3032:             if (defined($usertypes->{$types->[$i]})) {
 3033:                 my $rem = $i%($numinrow);
 3034:                 if ($rem == 0) {
 3035:                     if ($i<@{$types}-1) {
 3036:                         if ($i > 0) { 
 3037:                             $output .= '</tr>';
 3038:                         }
 3039:                         $output .= '<tr>';
 3040:                     }
 3041:                 } elsif ($i==@{$types}-1) {
 3042:                     my $colsleft = $numinrow - $rem;
 3043:                     if ($colsleft > 1) {
 3044:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 3045:                     }
 3046:                 }
 3047:                 my $check = ' ';
 3048:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 3049:                     $check = ' checked="checked" ';
 3050:                 }
 3051:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 3052:                            '<span class="LC_nobreak"><label>'.
 3053:                            '<input type="checkbox" name="inststatus" '.
 3054:                            'value="'.$types->[$i].'"'.$check.'/>'.
 3055:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 3056:             }
 3057:         }
 3058:         $output .= '</tr></table>';
 3059:     }
 3060:     return $output;
 3061: }
 3062: 
 3063: sub selfcreate_canmodify {
 3064:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 3065:     if (ref($inst_results) eq 'HASH') {
 3066:         my @inststatuses = &get_inststatuses($inst_results);
 3067:         if (@inststatuses == 0) {
 3068:             @inststatuses = ('default');
 3069:         }
 3070:         $rolesarray = \@inststatuses;
 3071:     }
 3072:     my %canmodify =
 3073:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 3074:                                                    $rolesarray);
 3075:     return %canmodify;
 3076: }
 3077: 
 3078: sub get_inststatuses {
 3079:     my ($insthashref) = @_;
 3080:     my @inststatuses = ();
 3081:     if (ref($insthashref) eq 'HASH') {
 3082:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 3083:             @inststatuses = @{$insthashref->{'inststatus'}};
 3084:         }
 3085:     }
 3086:     return @inststatuses;
 3087: }
 3088: 
 3089: # ================================================================= Phase Three
 3090: sub update_user_data {
 3091:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 3092:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 3093:                                           $env{'form.ccdomain'});
 3094:     # Error messages
 3095:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 3096:     my $end       = '</span><br /><br />';
 3097:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 3098:                     "'$env{'form.prevphase'}','modify')".'" />'.
 3099:                     &mt('Return to previous page').'</a>'.
 3100:                     &Apache::loncommon::end_page();
 3101:     my $now = time;
 3102:     my $title;
 3103:     if (exists($env{'form.makeuser'})) {
 3104: 	$title='Set Privileges for New User';
 3105:     } else {
 3106:         $title='Modify User Privileges';
 3107:     }
 3108:     my $newuser = 0;
 3109:     my ($jsback,$elements) = &crumb_utilities();
 3110:     my $jscript = '<script type="text/javascript">'."\n".
 3111:                   '// <![CDATA['."\n".
 3112:                   $jsback."\n".
 3113:                   '// ]]>'."\n".
 3114:                   '</script>'."\n";
 3115:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 3116:     push (@{$brcrum},
 3117:              {href => "javascript:backPage(document.userupdate)",
 3118:               text => $breadcrumb_text{'search'},
 3119:               faq  => 282,
 3120:               bug  => 'Instructor Interface',}
 3121:              );
 3122:     if ($env{'form.prevphase'} eq 'userpicked') {
 3123:         push(@{$brcrum},
 3124:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 3125:                 text => $breadcrumb_text{'userpicked'},
 3126:                 faq  => 282,
 3127:                 bug  => 'Instructor Interface',});
 3128:     }
 3129:     my $helpitem = 'Course_Change_Privileges';
 3130:     if ($env{'form.action'} eq 'singlestudent') {
 3131:         $helpitem = 'Course_Add_Student';
 3132:     } elsif ($context eq 'author') {
 3133:         $helpitem = 'Author_Change_Privileges';
 3134:     } elsif ($context eq 'domain') {
 3135:         $helpitem = 'Domain_Change_Privileges';
 3136:     }
 3137:     push(@{$brcrum}, 
 3138:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 3139:              text => $breadcrumb_text{'modify'},
 3140:              faq  => 282,
 3141:              bug  => 'Instructor Interface',},
 3142:             {href => "/adm/createuser",
 3143:              text => "Result",
 3144:              faq  => 282,
 3145:              bug  => 'Instructor Interface',
 3146:              help => $helpitem});
 3147:     my $args = {bread_crumbs          => $brcrum,
 3148:                 bread_crumbs_component => 'User Management'};
 3149:     if ($env{'form.popup'}) {
 3150:         $args->{'no_nav_bar'} = 1;
 3151:     }
 3152:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 3153:     $r->print(&update_result_form($uhome));
 3154:     # Check Inputs
 3155:     if (! $env{'form.ccuname'} ) {
 3156: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 3157: 	return;
 3158:     }
 3159:     if (  $env{'form.ccuname'} ne 
 3160: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 3161: 	$r->print($error.&mt('Invalid login name.').'  '.
 3162: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 3163: 		  $end.$rtnlink);
 3164: 	return;
 3165:     }
 3166:     if (! $env{'form.ccdomain'}       ) {
 3167: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 3168: 	return;
 3169:     }
 3170:     if (  $env{'form.ccdomain'} ne
 3171: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 3172: 	$r->print($error.&mt('Invalid domain name.').'  '.
 3173: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 3174: 		  $end.$rtnlink);
 3175: 	return;
 3176:     }
 3177:     if ($uhome eq 'no_host') {
 3178:         $newuser = 1;
 3179:     }
 3180:     if (! exists($env{'form.makeuser'})) {
 3181:         # Modifying an existing user, so check the validity of the name
 3182:         if ($uhome eq 'no_host') {
 3183:             $r->print(
 3184:                 $error
 3185:                .'<p class="LC_error">'
 3186:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 3187:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 3188:                .'</p>');
 3189:             return;
 3190:         }
 3191:     }
 3192:     # Determine authentication method and password for the user being modified
 3193:     my $amode='';
 3194:     my $genpwd='';
 3195:     if ($env{'form.login'} eq 'krb') {
 3196: 	$amode='krb';
 3197: 	$amode.=$env{'form.krbver'};
 3198: 	$genpwd=$env{'form.krbarg'};
 3199:     } elsif ($env{'form.login'} eq 'int') {
 3200: 	$amode='internal';
 3201: 	$genpwd=$env{'form.intarg'};
 3202:     } elsif ($env{'form.login'} eq 'fsys') {
 3203: 	$amode='unix';
 3204: 	$genpwd=$env{'form.fsysarg'};
 3205:     } elsif ($env{'form.login'} eq 'loc') {
 3206: 	$amode='localauth';
 3207: 	$genpwd=$env{'form.locarg'};
 3208: 	$genpwd=" " if (!$genpwd);
 3209:     } elsif ($env{'form.login'} eq 'lti') {
 3210:         $amode='lti';
 3211:         $genpwd=" ";
 3212:     } elsif (($env{'form.login'} eq 'nochange') ||
 3213:              ($env{'form.login'} eq ''        )) { 
 3214:         # There is no need to tell the user we did not change what they
 3215:         # did not ask us to change.
 3216:         # If they are creating a new user but have not specified login
 3217:         # information this will be caught below.
 3218:     } else {
 3219:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 3220:             return;
 3221:     }
 3222: 
 3223:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 3224:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 3225:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 3226:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 3227: 
 3228:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 3229:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3230:     my @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
 3231:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 3232:     my @requestauthor = ('requestauthor');
 3233:     my @authordefaults = ('webdav','editors');
 3234:     my ($othertitle,$usertypes,$types) = 
 3235:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 3236:     my %canmodify_status =
 3237:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 3238:                                                    ['inststatus']);
 3239:     if ($env{'form.makeuser'}) {
 3240: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 3241:         # Check for the authentication mode and password
 3242:         if (! $amode || ! $genpwd) {
 3243: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 3244: 	    return;
 3245: 	}
 3246:         # Determine desired host
 3247:         my $desiredhost = $env{'form.hserver'};
 3248:         if (lc($desiredhost) eq 'default') {
 3249:             $desiredhost = undef;
 3250:         } else {
 3251:             my %home_servers = 
 3252: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 3253:             if (! exists($home_servers{$desiredhost})) {
 3254:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 3255:                 return;
 3256:             }
 3257:         }
 3258:         # Check ID format
 3259:         my %checkhash;
 3260:         my %checks = ('id' => 1);
 3261:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 3262:             'newuser' => $newuser, 
 3263:             'id' => $env{'form.cid'},
 3264:         );
 3265:         if ($env{'form.cid'} ne '') {
 3266:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 3267:                                           \%rulematch,\%inst_results,\%curr_rules);
 3268:             if (ref($alerts{'id'}) eq 'HASH') {
 3269:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3270:                     my $domdesc =
 3271:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 3272:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 3273:                         my $userchkmsg;
 3274:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 3275:                             $userchkmsg  = 
 3276:                                 &Apache::loncommon::instrule_disallow_msg('id',
 3277:                                                                     $domdesc,1).
 3278:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 3279:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 3280:                         }
 3281:                         $r->print($error.&mt('Invalid ID format').$end.
 3282:                                   $userchkmsg.$rtnlink);
 3283:                         return;
 3284:                     }
 3285:                 }
 3286:             }
 3287:         }
 3288:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 3289: 	# Call modifyuser
 3290: 	my $result = &Apache::lonnet::modifyuser
 3291: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 3292:              $amode,$genpwd,$env{'form.cfirstname'},
 3293:              $env{'form.cmiddlename'},$env{'form.clastname'},
 3294:              $env{'form.cgeneration'},undef,$desiredhost,
 3295:              $env{'form.cpermanentemail'});
 3296: 	$r->print(&mt('Generating user').': '.$result);
 3297:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 3298:                                                $env{'form.ccdomain'});
 3299:         my (%changeHash,%newcustom,%changed,%changedinfo);
 3300:         if ($uhome ne 'no_host') {
 3301:             if ($context eq 'domain') {
 3302:                 foreach my $name ('portfolio','author') {
 3303:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3304:                         if ($env{'form.'.$name.'quota'} eq '') {
 3305:                             $newcustom{$name.'quota'} = 0;
 3306:                         } else {
 3307:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 3308:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 3309:                         }
 3310:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 3311:                             $changed{$name.'quota'} = 1;
 3312:                         }
 3313:                     }
 3314:                 }
 3315:                 foreach my $item (@usertools) {
 3316:                     if ($env{'form.custom'.$item} == 1) {
 3317:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3318:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3319:                                                      \%changeHash,'tools');
 3320:                     }
 3321:                 }
 3322:                 foreach my $item (@requestcourses) {
 3323:                     if ($env{'form.custom'.$item} == 1) {
 3324:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3325:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3326:                             $newcustom{$item} .= '=';
 3327:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3328:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3329:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3330:                             }
 3331:                         }
 3332:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3333:                                                       \%changeHash,'requestcourses');
 3334:                     }
 3335:                 }
 3336:                 if ($env{'form.customrequestauthor'} == 1) {
 3337:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3338:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3339:                                                     $newcustom{'requestauthor'},
 3340:                                                     \%changeHash,'requestauthor');
 3341:                 }
 3342:                 if ($env{'form.customeditors'} == 1) {
 3343:                     my @editors;
 3344:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 3345:                     if (@posseditors) {
 3346:                         foreach my $editor (@posseditors) {
 3347:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 3348:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 3349:                                     push(@editors,$editor);
 3350:                                 }
 3351:                             }
 3352:                         }
 3353:                     }
 3354:                     if (@editors) {
 3355:                         @editors = sort(@editors);
 3356:                         $changed{'editors'} = &tool_admin('editors',join(',',@editors),
 3357:                                                           \%changeHash,'authordefaults');
 3358:                     }
 3359:                 }
 3360:                 if ($env{'form.customwebdav'} == 1) {
 3361:                     $newcustom{'webdav'} = $env{'form.authordefaults_webdav'};
 3362:                     $changed{'webdav'} = &tool_admin('webdav',$newcustom{'webdav'},
 3363:                                                   \%changeHash,'authordefaults');
 3364:                 }
 3365:             }
 3366:             if ($canmodify_status{'inststatus'}) {
 3367:                 if (exists($env{'form.inststatus'})) {
 3368:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3369:                     if (@inststatuses > 0) {
 3370:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3371:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3372:                     }
 3373:                 }
 3374:             }
 3375:             if (keys(%changed)) {
 3376:                 foreach my $item (@userinfo) {
 3377:                     $changeHash{$item}  = $env{'form.c'.$item};
 3378:                 }
 3379:                 my $chgresult =
 3380:                      &Apache::lonnet::put('environment',\%changeHash,
 3381:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3382:             }
 3383:         }
 3384:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3385:                   &Apache::lonnet::hostname($uhome));
 3386:     } elsif (($env{'form.login'} ne 'nochange') &&
 3387:              ($env{'form.login'} ne ''        )) {
 3388: 	# Modify user privileges
 3389:         if (! $amode || ! $genpwd) {
 3390: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3391: 	    return;
 3392: 	}
 3393: 	# Only allow authentication modification if the person has authority
 3394: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3395: 	    $r->print('Modifying authentication: '.
 3396:                       &Apache::lonnet::modifyuserauth(
 3397: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3398:                        $amode,$genpwd));
 3399:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3400: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3401: 	} else {
 3402: 	    # Okay, this is a non-fatal error.
 3403: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3404: 	}
 3405:     } elsif (($env{'form.intarg'} ne '') &&
 3406:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3407:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3408:         $r->print('Modifying authentication: '.
 3409:                   &Apache::lonnet::modifyuserauth(
 3410:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3411:                   'internal',$env{'form.intarg'}));
 3412:     }
 3413:     $r->rflush(); # Finish display of header before time consuming actions start
 3414:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3415:     ##
 3416:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3417:     if ($context eq 'course') {
 3418:         ($cnum,$cdom) =
 3419:             &Apache::lonuserutils::get_course_identity();
 3420:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3421:         if ($showcredits) {
 3422:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3423:         }
 3424:     }
 3425:     if (! $env{'form.makeuser'} ) {
 3426:         # Check for need to change
 3427:         my %userenv = &Apache::lonnet::get
 3428:             ('environment',['firstname','middlename','lastname','generation',
 3429:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3430:              'tools.aboutme','tools.blog','tools.webdav',
 3431:              'tools.portfolio','tools.timezone','tools.portaccess',
 3432:              'authormanagers','authoreditors','requestauthor',
 3433:              'requestcourses.official','requestcourses.unofficial',
 3434:              'requestcourses.community','requestcourses.textbook',
 3435:              'requestcourses.placement','requestcourses.lti',
 3436:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3437:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3438:              'reqcrsotherdom.placement','domcoord.author'],
 3439:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3440:         my ($tmp) = keys(%userenv);
 3441:         if ($tmp =~ /^(con_lost|error)/i) { 
 3442:             %userenv = ();
 3443:         }
 3444:         unless (($userenv{'domcoord.author'} eq 'blocked') &&
 3445:                 (($env{'user.name'} ne $env{'form.ccuname'}) ||
 3446:                  ($env{'user.domain'} ne $env{'form.ccdomain'}))) {
 3447:             push(@authordefaults,'managers');
 3448:         }
 3449:         my $no_forceid_alert;
 3450:         # Check to see if user information can be changed
 3451:         my %domconfig =
 3452:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3453:                                      $env{'form.ccdomain'});
 3454:         my @statuses = ('active','future');
 3455:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3456:         my ($auname,$audom);
 3457:         if ($context eq 'author') {
 3458:             $auname = $env{'user.name'};
 3459:             $audom = $env{'user.domain'};     
 3460:         }
 3461:         foreach my $item (keys(%roles)) {
 3462:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3463:             if ($context eq 'course') {
 3464:                 if ($cnum ne '' && $cdom ne '') {
 3465:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3466:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3467:                             push(@userroles,$role);
 3468:                         }
 3469:                     }
 3470:                 }
 3471:             } elsif ($context eq 'author') {
 3472:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3473:                     if (!grep(/^\Q$role\E$/,@userroles)) {
 3474:                         push(@userroles,$role);
 3475:                     }
 3476:                 }
 3477:             }
 3478:         }
 3479:         if ($env{'form.action'} eq 'singlestudent') {
 3480:             if (!grep(/^st$/,@userroles)) {
 3481:                 push(@userroles,'st');
 3482:             }
 3483:         } else {
 3484:             # Check for course or co-author roles being activated or re-enabled
 3485:             if ($context eq 'author' || $context eq 'course') {
 3486:                 foreach my $key (keys(%env)) {
 3487:                     if ($context eq 'author') {
 3488:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3489:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3490:                                 push(@userroles,$1);
 3491:                             }
 3492:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3493:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3494:                                 push(@userroles,$1);
 3495:                             }
 3496:                         }
 3497:                     } elsif ($context eq 'course') {
 3498:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3499:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3500:                                 push(@userroles,$1);
 3501:                             }
 3502:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3503:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3504:                                 push(@userroles,$1);
 3505:                             }
 3506:                         }
 3507:                     }
 3508:                 }
 3509:             }
 3510:         }
 3511:         #Check to see if we can change personal data for the user 
 3512:         my (@mod_disallowed,@longroles);
 3513:         foreach my $role (@userroles) {
 3514:             if ($role eq 'cr') {
 3515:                 push(@longroles,'Custom');
 3516:             } else {
 3517:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3518:             }
 3519:         }
 3520:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3521:         foreach my $item (@userinfo) {
 3522:             # Strip leading and trailing whitespace
 3523:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3524:             if (!$canmodify{$item}) {
 3525:                 if (defined($env{'form.c'.$item})) {
 3526:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3527:                         push(@mod_disallowed,$item);
 3528:                     }
 3529:                 }
 3530:                 $env{'form.c'.$item} = $userenv{$item};
 3531:             }
 3532:         }
 3533:         # Check to see if we can change the Student/Employee ID
 3534:         my $forceid = $env{'form.forceid'};
 3535:         my $recurseid = $env{'form.recurseid'};
 3536:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3537:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3538:                                             $env{'form.ccuname'});
 3539:         if (($uidhash{$env{'form.ccuname'}}) && 
 3540:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3541:             (!$forceid)) {
 3542:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3543:                 $env{'form.cid'} = $userenv{'id'};
 3544:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3545:                                    .'<br />'
 3546:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3547:                                    .'<br />'."\n";
 3548:             }
 3549:         }
 3550:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3551:             my $checkhash;
 3552:             my $checks = { 'id' => 1 };
 3553:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3554:                    { 'newuser' => $newuser,
 3555:                      'id'  => $env{'form.cid'}, 
 3556:                    };
 3557:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3558:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3559:             if (ref($alerts{'id'}) eq 'HASH') {
 3560:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3561:                    $env{'form.cid'} = $userenv{'id'};
 3562:                 }
 3563:             }
 3564:         }
 3565:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3566:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3567:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3568:             %oldsettingstatus,%newsettingstatus);
 3569:         @disporder = ('inststatus');
 3570:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3571:             push(@disporder,('requestcourses','requestauthor','authordefaults'));
 3572:         } else {
 3573:             push(@disporder,'reqcrsotherdom');
 3574:         }
 3575:         push(@disporder,('quota','tools'));
 3576:         $oldinststatus = $userenv{'inststatus'};
 3577:         foreach my $name ('portfolio','author') {
 3578:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3579:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3580:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3581:         }
 3582:         my %canshow;
 3583:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3584:             $canshow{'quota'} = 1;
 3585:         }
 3586:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3587:             $canshow{'tools'} = 1;
 3588:         }
 3589:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3590:             $canshow{'requestcourses'} = 1;
 3591:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3592:             $canshow{'reqcrsotherdom'} = 1;
 3593:         }
 3594:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3595:             $canshow{'inststatus'} = 1;
 3596:         }
 3597:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3598:             $canshow{'requestauthor'} = 1;
 3599:             $canshow{'authordefaults'} = 1;
 3600:         }
 3601:         my (%changeHash,%changed);
 3602:         if ($oldinststatus eq '') {
 3603:             $oldsettings{'inststatus'} = $othertitle; 
 3604:         } else {
 3605:             if (ref($usertypes) eq 'HASH') {
 3606:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3607:             } else {
 3608:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3609:             }
 3610:         }
 3611:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3612:         if ($canmodify_status{'inststatus'}) {
 3613:             $canshow{'inststatus'} = 1;
 3614:             if (exists($env{'form.inststatus'})) {
 3615:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3616:                 if (@inststatuses > 0) {
 3617:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3618:                     $changeHash{'inststatus'} = $newinststatus;
 3619:                     if ($newinststatus ne $oldinststatus) {
 3620:                         $changed{'inststatus'} = $newinststatus;
 3621:                         foreach my $name ('portfolio','author') {
 3622:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3623:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3624:                         }
 3625:                     }
 3626:                     if (ref($usertypes) eq 'HASH') {
 3627:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3628:                     } else {
 3629:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3630:                     }
 3631:                 }
 3632:             } else {
 3633:                 $newinststatus = '';
 3634:                 $changeHash{'inststatus'} = $newinststatus;
 3635:                 $newsettings{'inststatus'} = $othertitle;
 3636:                 if ($newinststatus ne $oldinststatus) {
 3637:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3638:                     foreach my $name ('portfolio','author') {
 3639:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3640:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3641:                     }
 3642:                 }
 3643:             }
 3644:         } elsif ($context ne 'selfcreate') {
 3645:             $canshow{'inststatus'} = 1;
 3646:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3647:         }
 3648:         foreach my $name ('portfolio','author') {
 3649:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3650:         }
 3651:         if ($context eq 'domain') {
 3652:             foreach my $name ('portfolio','author') {
 3653:                 if ($userenv{$name.'quota'} ne '') {
 3654:                     $oldquota{$name} = $userenv{$name.'quota'};
 3655:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3656:                         if ($env{'form.'.$name.'quota'} eq '') {
 3657:                             $newquota{$name} = 0;
 3658:                         } else {
 3659:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3660:                             $newquota{$name} =~ s/[^\d\.]//g;
 3661:                         }
 3662:                         if ($newquota{$name} != $oldquota{$name}) {
 3663:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3664:                                 $changed{$name.'quota'} = 1;
 3665:                             }
 3666:                         }
 3667:                     } else {
 3668:                         if (&quota_admin('',\%changeHash,$name)) {
 3669:                             $changed{$name.'quota'} = 1;
 3670:                             $newquota{$name} = $newdefquota{$name};
 3671:                             $newisdefault{$name} = 1;
 3672:                         }
 3673:                     }
 3674:                 } else {
 3675:                     $oldisdefault{$name} = 1;
 3676:                     $oldquota{$name} = $olddefquota{$name};
 3677:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3678:                         if ($env{'form.'.$name.'quota'} eq '') {
 3679:                             $newquota{$name} = 0;
 3680:                         } else {
 3681:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3682:                             $newquota{$name} =~ s/[^\d\.]//g;
 3683:                         }
 3684:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3685:                             $changed{$name.'quota'} = 1;
 3686:                         }
 3687:                     } else {
 3688:                         $newquota{$name} = $newdefquota{$name};
 3689:                         $newisdefault{$name} = 1;
 3690:                     }
 3691:                 }
 3692:                 if ($oldisdefault{$name}) {
 3693:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3694:                 }  else {
 3695:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3696:                 }
 3697:                 if ($newisdefault{$name}) {
 3698:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3699:                 } else {
 3700:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3701:                 }
 3702:             }
 3703:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3704:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3705:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3706:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3707:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3708:                 my ($isadv,$isauthor) =
 3709:                     &Apache::lonnet::is_advanced_user($env{'form.ccdomain'},$env{'form.ccuname'});
 3710:                 unless ($isauthor) {
 3711:                     &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3712:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3713:                 }
 3714:                 &tool_changes('authordefaults',\@authordefaults,\%oldsettings,\%oldsettingstext,
 3715:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3716:             } else {
 3717:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3718:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3719:             }
 3720:         }
 3721:         foreach my $item (@userinfo) {
 3722:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3723:                 $namechanged{$item} = 1;
 3724:             }
 3725:         }
 3726:         foreach my $name ('portfolio','author') {
 3727:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3728:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3729:         }
 3730:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3731:             my ($chgresult,$namechgresult);
 3732:             if (keys(%changed) > 0) {
 3733:                 $chgresult =
 3734:                     &Apache::lonnet::put('environment',\%changeHash,
 3735:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3736:                 if ($chgresult eq 'ok') {
 3737:                     my ($ca_mgr_del,%ca_mgr_add);
 3738:                     if ($changed{'managers'}) {
 3739:                         my (@adds,@dels);
 3740:                         if ($changeHash{'authormanagers'} eq '') {
 3741:                             @dels = split(/,/,$userenv{'authormanagers'});
 3742:                         } elsif ($userenv{'authormanagers'} eq '') {
 3743:                             @adds = split(/,/,$changeHash{'authormanagers'});
 3744:                         } else {
 3745:                             my @old = split(/,/,$userenv{'authormanagers'});
 3746:                             my @new = split(/,/,$changeHash{'authormanagers'});
 3747:                             my @diffs = &Apache::loncommon::compare_arrays(\@old,\@new);
 3748:                             if (@diffs) {
 3749:                                 foreach my $user (@diffs) {
 3750:                                     if (grep(/^\Q$user\E$/,@old)) {
 3751:                                         push(@dels,$user);
 3752:                                     } elsif (grep(/^\Q$user\E$/,@new)) {
 3753:                                         push(@adds,$user);
 3754:                                     }
 3755:                                 }
 3756:                             }
 3757:                         }
 3758:                         my $key = "internal.manager./$env{'form.ccdomain'}/$env{'form.ccuname'}";
 3759:                         if (@dels) {
 3760:                             foreach my $user (@dels) {
 3761:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3762:                                     &Apache::lonnet::del('environment',[$key],$2,$1);
 3763:                                 }
 3764:                             }
 3765:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3766:                             if (grep(/^\Q$curruser\E$/,@dels)) {
 3767:                                 $ca_mgr_del = $key;
 3768:                             }
 3769:                         }
 3770:                         if (@adds) {
 3771:                             foreach my $user (@adds) {
 3772:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3773:                                     &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 3774:                                 }
 3775:                             }
 3776:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3777:                             if (grep(/^\Q$curruser\E$/,@adds)) {
 3778:                                 $ca_mgr_add{$key} = 1;
 3779:                             }
 3780:                         }
 3781:                     }
 3782:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3783:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3784:                         my %newenvhash;
 3785:                         foreach my $key (keys(%changed)) {
 3786:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3787:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3788:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3789:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3790:                                     $changeHash{'requestcourses.'.$key};
 3791:                                 if ($changeHash{'requestcourses.'.$key}) {
 3792:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3793:                                 } else {
 3794:                                     $newenvhash{'environment.canrequest.'.$key} =
 3795:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3796:                                             $key,'reload','requestcourses');
 3797:                                 }
 3798:                             } elsif ($key eq 'requestauthor') {
 3799:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3800:                                 if ($changeHash{$key}) {
 3801:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3802:                                 } else {
 3803:                                     $newenvhash{'environment.canrequest.author'} =
 3804:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3805:                                             $key,'reload','requestauthor');
 3806:                                 }
 3807:                             } elsif ($key eq 'editors') {
 3808:                                 $newenvhash{'environment.author'.$key} = $changeHash{'author'.$key};
 3809:                                 if ($key eq 'editors') {
 3810:                                     if ($env{'form.customeditors'}) {
 3811:                                         $newenvhash{'environment.editors'} = $changeHash{'author'.$key};
 3812:                                     } else {
 3813:                                         $newenvhash{'environment.editors'} =
 3814:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3815:                                             $key,'reload','authordefaults');
 3816:                                     }
 3817:                                 }
 3818:                             } elsif ($key ne 'quota') {
 3819:                                 $newenvhash{'environment.tools.'.$key} = 
 3820:                                     $changeHash{'tools.'.$key};
 3821:                                 if ($changeHash{'tools.'.$key} ne '') {
 3822:                                     $newenvhash{'environment.availabletools.'.$key} =
 3823:                                         $changeHash{'tools.'.$key};
 3824:                                 } else {
 3825:                                     $newenvhash{'environment.availabletools.'.$key} =
 3826:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3827:                                             $key,'reload','tools');
 3828:                                 }
 3829:                             }
 3830:                         }
 3831:                         if (keys(%newenvhash)) {
 3832:                             &Apache::lonnet::appenv(\%newenvhash);
 3833:                         }
 3834:                     } else {
 3835:                         if ($ca_mgr_del) {
 3836:                             &Apache::lonnet::delenv($ca_mgr_del);
 3837:                         }
 3838:                         if (keys(%ca_mgr_add)) {
 3839:                             &Apache::lonnet::appenv(\%ca_mgr_add);
 3840:                         }
 3841:                     }
 3842:                     if ($changed{'aboutme'}) {
 3843:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3844:                                                                      $env{'form.ccdomain'});
 3845:                     }
 3846:                 }
 3847:             }
 3848:             if (keys(%namechanged) > 0) {
 3849:                 foreach my $field (@userinfo) {
 3850:                     $changeHash{$field}  = $env{'form.c'.$field};
 3851:                 }
 3852: # Make the change
 3853:                 $namechgresult =
 3854:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3855:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3856:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3857:                         $changeHash{'lastname'},$changeHash{'generation'},
 3858:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3859:                 %userupdate = (
 3860:                                lastname   => $env{'form.clastname'},
 3861:                                middlename => $env{'form.cmiddlename'},
 3862:                                firstname  => $env{'form.cfirstname'},
 3863:                                generation => $env{'form.cgeneration'},
 3864:                                id         => $env{'form.cid'},
 3865:                              );
 3866:             }
 3867:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3868:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3869:             # Tell the user we changed the name
 3870:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3871:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3872:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3873:                                   \%newsettingstext);
 3874:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3875:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3876:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3877:                     if (($recurseid) &&
 3878:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3879:                         my $idresult = 
 3880:                             &Apache::lonuserutils::propagate_id_change(
 3881:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3882:                                 \%userupdate);
 3883:                         $r->print('<br />'.$idresult.'<br />');
 3884:                     }
 3885:                 }
 3886:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3887:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3888:                     my %newenvhash;
 3889:                     foreach my $key (keys(%changeHash)) {
 3890:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3891:                     }
 3892:                     &Apache::lonnet::appenv(\%newenvhash);
 3893:                 }
 3894:             } else { # error occurred
 3895:                 $r->print(
 3896:                     '<p class="LC_error">'
 3897:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3898:                             '"'.$env{'form.ccuname'}.'"',
 3899:                             '"'.$env{'form.ccdomain'}.'"')
 3900:                    .'</p>');
 3901:             }
 3902:         } else { # End of if ($env ... ) logic
 3903:             # They did not want to change the users name, quota, tool availability,
 3904:             # or ability to request creation of courses, 
 3905:             # but we can still tell them what the name and quota and availabilities are  
 3906:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3907:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3908:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3909:         }
 3910:         if (@mod_disallowed) {
 3911:             my ($rolestr,$contextname);
 3912:             if (@longroles > 0) {
 3913:                 $rolestr = join(', ',@longroles);
 3914:             } else {
 3915:                 $rolestr = &mt('No roles');
 3916:             }
 3917:             if ($context eq 'course') {
 3918:                 $contextname = 'course';
 3919:             } elsif ($context eq 'author') {
 3920:                 $contextname = 'co-author';
 3921:             }
 3922:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3923:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3924:             foreach my $field (@mod_disallowed) {
 3925:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3926:             }
 3927:             $r->print('</ul>');
 3928:             if (@mod_disallowed == 1) {
 3929:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3930:             } else {
 3931:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3932:             }
 3933:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3934:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3935:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3936:                          ,'<a href="'.$helplink.'">','</a>')
 3937:                       .'<br />');
 3938:         }
 3939:         $r->print('<span class="LC_warning">'
 3940:                   .$no_forceid_alert
 3941:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3942:                   .'</span>');
 3943:     }
 3944:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3945:     if ($env{'form.action'} eq 'singlestudent') {
 3946:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3947:                                $crstype,$showcredits,$defaultcredits);
 3948:         my $linktext = ($crstype eq 'Community' ?
 3949:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3950:         $r->print(
 3951:             &Apache::lonhtmlcommon::actionbox([
 3952:                 '<a href="javascript:backPage(document.userupdate)">'
 3953:                .($crstype eq 'Community' ? 
 3954:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3955:                .'</a>']));
 3956:     } else {
 3957:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3958:         if (keys(%namechanged) > 0) {
 3959:             if ($context eq 'course') {
 3960:                 if (@userroles > 0) {
 3961:                     if ((@rolechanges == 0) || 
 3962:                         (!(grep(/^st$/,@rolechanges)))) {
 3963:                         if (grep(/^st$/,@userroles)) {
 3964:                             my $classlistupdated =
 3965:                                 &Apache::lonuserutils::update_classlist($cdom,
 3966:                                               $cnum,$env{'form.ccdomain'},
 3967:                                        $env{'form.ccuname'},\%userupdate);
 3968:                         }
 3969:                     }
 3970:                 }
 3971:             }
 3972:         }
 3973:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3974:                                                      $env{'form.ccdomain'});
 3975:         if ($env{'form.popup'}) {
 3976:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3977:         } else {
 3978:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3979:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3980:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3981:         }
 3982:     }
 3983: }
 3984: 
 3985: sub display_userinfo {
 3986:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3987:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3988:         $newsetting,$newsettingtext) = @_;
 3989:     return unless (ref($order) eq 'ARRAY' &&
 3990:                    ref($canshow) eq 'HASH' && 
 3991:                    ref($requestcourses) eq 'ARRAY' && 
 3992:                    ref($requestauthor) eq 'ARRAY' &&
 3993:                    ref($usertools) eq 'ARRAY' && 
 3994:                    ref($userenv) eq 'HASH' &&
 3995:                    ref($changedhash) eq 'HASH' &&
 3996:                    ref($oldsetting) eq 'HASH' &&
 3997:                    ref($oldsettingtext) eq 'HASH' &&
 3998:                    ref($newsetting) eq 'HASH' &&
 3999:                    ref($newsettingtext) eq 'HASH');
 4000:     my %lt=&Apache::lonlocal::texthash(
 4001:          'ui'             => 'User Information',
 4002:          'uic'            => 'User Information Changed',
 4003:          'firstname'      => 'First Name',
 4004:          'middlename'     => 'Middle Name',
 4005:          'lastname'       => 'Last Name',
 4006:          'generation'     => 'Generation',
 4007:          'id'             => 'Student/Employee ID',
 4008:          'permanentemail' => 'Permanent e-mail address',
 4009:          'portfolioquota' => 'Disk space allocated to portfolio files',
 4010:          'authorquota'    => 'Disk space allocated to Authoring Space',
 4011:          'blog'           => 'Blog Availability',
 4012:          'webdav'         => 'WebDAV Availability',
 4013:          'aboutme'        => 'Personal Information Page Availability',
 4014:          'portfolio'      => 'Portfolio Availability',
 4015:          'portaccess'     => 'Portfolio Shareable',
 4016:          'timezone'       => 'Can set own Time Zone',
 4017:          'official'       => 'Can Request Official Courses',
 4018:          'unofficial'     => 'Can Request Unofficial Courses',
 4019:          'community'      => 'Can Request Communities',
 4020:          'textbook'       => 'Can Request Textbook Courses',
 4021:          'placement'      => 'Can Request Placement Tests',
 4022:          'lti'            => 'Can Request LTI Courses',
 4023:          'requestauthor'  => 'Can Request Author Role',
 4024:          'inststatus'     => "Affiliation",
 4025:          'prvs'           => 'Previous Value:',
 4026:          'chto'           => 'Changed To:',
 4027:          'editors'        => "Available Editors in Authoring Space",
 4028:          'managers'       => "Co-authors who can add/revoke roles",
 4029:          'edit'           => 'Standard editor (Edit)',
 4030:          'xml'            => 'Text editor (EditXML)',
 4031:          'daxe'           => 'Daxe editor (Daxe)',
 4032:     );
 4033:     if ($changed) {
 4034:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 4035:                 &Apache::loncommon::start_data_table().
 4036:                 &Apache::loncommon::start_data_table_header_row());
 4037:         $r->print("<th>&nbsp;</th>\n");
 4038:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 4039:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 4040:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4041:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 4042: 
 4043:         foreach my $item (@userinfo) {
 4044:             my $value = $env{'form.c'.$item};
 4045:             #show changes only:
 4046:             unless ($value eq $userenv->{$item}){
 4047:                 $r->print(&Apache::loncommon::start_data_table_row());
 4048:                 $r->print("<td>$lt{$item}</td>\n");
 4049:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 4050:                 $r->print("<td>$value </td>\n");
 4051:                 $r->print(&Apache::loncommon::end_data_table_row());
 4052:             }
 4053:         }
 4054:         foreach my $entry (@{$order}) {
 4055:             if ($canshow->{$entry}) {
 4056:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') ||
 4057:                     ($entry eq 'requestauthor') || ($entry eq 'authordefaults')) {
 4058:                     my @items;
 4059:                     if ($entry eq 'requestauthor') {
 4060:                         @items = ($entry);
 4061:                     } elsif ($entry eq 'authordefaults') {
 4062:                         @items = ('webdav','managers','editors');
 4063:                     } else {
 4064:                         @items = @{$requestcourses};
 4065:                     }
 4066:                     foreach my $item (@items) {
 4067:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 4068:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 4069:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 4070:                             $r->print("<td>$lt{$item}</td><td>\n");
 4071:                             unless ($item eq 'managers') {
 4072:                                 $r->print($oldsetting->{$item});
 4073:                             }
 4074:                             if ($oldsettingtext->{$item}) {
 4075:                                 if ($oldsetting->{$item}) {
 4076:                                     unless ($item eq 'managers') {
 4077:                                         $r->print(' -- ');
 4078:                                     }
 4079:                                 }
 4080:                                 $r->print($oldsettingtext->{$item});
 4081:                             }
 4082:                             $r->print("</td>\n<td>");
 4083:                             unless ($item eq 'managers') {
 4084:                                 $r->print($newsetting->{$item});
 4085:                             }
 4086:                             if ($newsettingtext->{$item}) {
 4087:                                 if ($newsetting->{$item}) {
 4088:                                     unless ($item eq 'managers') {
 4089:                                         $r->print(' -- ');
 4090:                                     }
 4091:                                 }
 4092:                                 $r->print($newsettingtext->{$item});
 4093:                             }
 4094:                             $r->print("</td>\n");
 4095:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4096:                         }
 4097:                     }
 4098:                 } elsif ($entry eq 'tools') {
 4099:                     foreach my $item (@{$usertools}) {
 4100:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 4101:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4102:                             $r->print("<td>$lt{$item}</td>\n");
 4103:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 4104:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 4105:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4106:                         }
 4107:                     }
 4108:                 } elsif ($entry eq 'quota') {
 4109:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 4110:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 4111:                         foreach my $name ('portfolio','author') {
 4112:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 4113:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4114:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 4115:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 4116:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 4117:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4118:                             }
 4119:                         }
 4120:                     }
 4121:                 } else {
 4122:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 4123:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4124:                         $r->print("<td>$lt{$entry}</td>\n");
 4125:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 4126:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 4127:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4128:                     }
 4129:                 }
 4130:             }
 4131:         }
 4132:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 4133:     } else {
 4134:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 4135:                   '<p>'.&mt('No changes made to user information').'</p>');
 4136:     }
 4137:     return;
 4138: }
 4139: 
 4140: sub tool_changes {
 4141:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 4142:         $changed,$newaccess,$newaccesstext) = @_;
 4143:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 4144:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 4145:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 4146:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 4147:         return;
 4148:     }
 4149:     my %reqdisplay = &requestchange_display();
 4150:     if ($context eq 'reqcrsotherdom') {
 4151:         my @options = ('approval','validate','autolimit');
 4152:         my $optregex = join('|',@options);
 4153:         my $cdom = $env{'request.role.domain'};
 4154:         foreach my $tool (@{$usertools}) {
 4155:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4156:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4157:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 4158:             my ($newop,$limit);
 4159:             if ($env{'form.'.$context.'_'.$tool}) {
 4160:                 $newop = $env{'form.'.$context.'_'.$tool};
 4161:                 if ($newop eq 'autolimit') {
 4162:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4163:                     $limit =~ s/\D+//g;
 4164:                     $newop .= '='.$limit;
 4165:                 }
 4166:             }
 4167:             if ($userenv->{$context.'.'.$tool} eq '') {
 4168:                 if ($newop) {
 4169:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 4170:                                                   $changeHash,$context);
 4171:                     if ($changed->{$tool}) {
 4172:                         if ($newop =~ /^autolimit/) {
 4173:                             if ($limit) {
 4174:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4175:                             } else {
 4176:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4177:                             }
 4178:                         } else {
 4179:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 4180:                         }
 4181:                     } else {
 4182:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4183:                     }
 4184:                 }
 4185:             } else {
 4186:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 4187:                 my @new;
 4188:                 my $changedoms;
 4189:                 foreach my $req (@curr) {
 4190:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 4191:                         my $oldop = $1;
 4192:                         if ($oldop =~ /^autolimit=(\d*)/) {
 4193:                             my $limit = $1;
 4194:                             if ($limit) {
 4195:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4196:                             } else {
 4197:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4198:                             }
 4199:                         } else {
 4200:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 4201:                         }
 4202:                         if ($oldop ne $newop) {
 4203:                             $changedoms = 1;
 4204:                             foreach my $item (@curr) {
 4205:                                 my ($reqdom,$option) = split(':',$item);
 4206:                                 unless ($reqdom eq $cdom) {
 4207:                                     push(@new,$item);
 4208:                                 }
 4209:                             }
 4210:                             if ($newop) {
 4211:                                 push(@new,$cdom.':'.$newop);
 4212:                             }
 4213:                             @new = sort(@new);
 4214:                         }
 4215:                         last;
 4216:                     }
 4217:                 }
 4218:                 if ((!$changedoms) && ($newop)) {
 4219:                     $changedoms = 1;
 4220:                     @new = sort(@curr,$cdom.':'.$newop);
 4221:                 }
 4222:                 if ($changedoms) {
 4223:                     my $newdomstr;
 4224:                     if (@new) {
 4225:                         $newdomstr = join(',',@new);
 4226:                     }
 4227:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 4228:                                                   $context);
 4229:                     if ($changed->{$tool}) {
 4230:                         if ($env{'form.'.$context.'_'.$tool}) {
 4231:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 4232:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4233:                                 $limit =~ s/\D+//g;
 4234:                                 if ($limit) {
 4235:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4236:                                 } else {
 4237:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4238:                                 }
 4239:                             } else {
 4240:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 4241:                             }
 4242:                         } else {
 4243:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4244:                         }
 4245:                     }
 4246:                 }
 4247:             }
 4248:         }
 4249:         return;
 4250:     }
 4251:     my %tooldesc = &Apache::lonlocal::texthash(
 4252:         'edit' => 'Standard editor (Edit)',
 4253:         'xml'  => 'Text editor (EditXML)',
 4254:         'daxe' => 'Daxe editor (Daxe)',
 4255:     );
 4256:     foreach my $tool (@{$usertools}) {
 4257:         my ($newval,$limit,$envkey);
 4258:         $envkey = $context.'.'.$tool;
 4259:         if ($context eq 'requestcourses') {
 4260:             $newval = $env{'form.crsreq_'.$tool};
 4261:             if ($newval eq 'autolimit') {
 4262:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 4263:                 $limit =~ s/\D+//g;
 4264:                 $newval .= '='.$limit;
 4265:             }
 4266:         } elsif ($context eq 'requestauthor') {
 4267:             $newval = $env{'form.'.$context};
 4268:             $envkey = $context;
 4269:         } elsif ($context eq 'authordefaults') {
 4270:             if ($tool eq 'editors') {
 4271:                 $envkey = 'authoreditors';
 4272:                 if ($env{'form.customeditors'} == 1) {
 4273:                     my @editors;
 4274:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 4275:                     if (@posseditors) {
 4276:                         foreach my $editor (@posseditors) {
 4277:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 4278:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 4279:                                     push(@editors,$editor);
 4280:                                 }
 4281:                             }
 4282:                         }
 4283:                     }
 4284:                     if (@editors) {
 4285:                         $newval = join(',',(sort(@editors)));
 4286:                     }
 4287:                 }
 4288:             } elsif ($tool eq 'managers') {
 4289:                 $envkey = 'authormanagers';
 4290:                 my @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 4291:                 if (@possibles) {
 4292:                     my %ca_roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},
 4293:                                                                  undef,['active','future'],['ca']);
 4294:                     if (keys(%ca_roles)) {
 4295:                         my @custommanagers;
 4296:                         foreach my $user (@possibles) {
 4297:                             if ($user =~ /^($match_username):($match_domain)$/) {
 4298:                                 if (exists($ca_roles{$user.':ca'})) {
 4299:                                     unless ($user eq $env{'form.ccuname'}.':'.$env{'form.ccdomain'}) {
 4300:                                         push(@custommanagers,$user);
 4301:                                     }
 4302:                                 }
 4303:                             }
 4304:                         }
 4305:                         if (@custommanagers) {
 4306:                             $newval = join(',',sort(@custommanagers));
 4307:                         }
 4308:                     }
 4309:                 }
 4310:             } elsif ($tool eq 'webdav') {
 4311:                 $envkey = 'tools.webdav';
 4312:                 $newval = $env{'form.'.$context.'_'.$tool};
 4313:             }
 4314:         } else {
 4315:             $newval = $env{'form.'.$context.'_'.$tool};
 4316:         }
 4317:         if ($userenv->{$envkey} ne '') {
 4318:             $oldaccess->{$tool} = &mt('custom');
 4319:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4320:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 4321:                     my $currlimit = $1;
 4322:                     if ($currlimit eq '') {
 4323:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4324:                     } else {
 4325:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 4326:                     }
 4327:                 } elsif ($userenv->{$envkey}) {
 4328:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4329:                 } else {
 4330:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4331:                 }
 4332:             } elsif ($context eq 'authordefaults') {
 4333:                 if ($tool eq 'managers') {
 4334:                     if ($userenv->{$envkey} eq '') {
 4335:                         $oldaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4336:                     } else {
 4337:                         my $managers = $userenv->{$envkey};
 4338:                         $managers =~ s/,/, /g;
 4339:                         $oldaccesstext->{$tool} = $managers;
 4340:                     }
 4341:                 } elsif ($tool eq 'editors') {
 4342:                     $oldaccesstext->{$tool} = &mt('can use: [_1]',
 4343:                                                   join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4344:                 } elsif ($tool eq 'webdav') {
 4345:                     if ($userenv->{$envkey}) {
 4346:                         $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4347:                     } else {
 4348:                         $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4349:                     }
 4350:                 }
 4351:             } else {
 4352:                 if ($userenv->{$envkey}) {
 4353:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4354:                 } else {
 4355:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4356:                 }
 4357:             }
 4358:             $changeHash->{$envkey} = $userenv->{$envkey};
 4359:             if (($env{'form.custom'.$tool} == 1) ||
 4360:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4361:                 if ($newval ne $userenv->{$envkey}) {
 4362:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4363:                                                     $context);
 4364:                     if ($changed->{$tool}) {
 4365:                         $newaccess->{$tool} = &mt('custom');
 4366:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4367:                             if ($newval =~ /^autolimit/) {
 4368:                                 if ($limit) {
 4369:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4370:                                 } else {
 4371:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4372:                                 }
 4373:                             } elsif ($newval) {
 4374:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 4375:                             } else {
 4376:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4377:                             }
 4378:                         } elsif ($context eq 'authordefaults') {
 4379:                             if ($tool eq 'editors') {
 4380:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4381:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$changeHash->{$envkey})));
 4382:                             } elsif ($tool eq 'managers') {
 4383:                                 if ($changeHash->{$envkey} eq '') {
 4384:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4385:                                 } else {
 4386:                                     my $managers = $changeHash->{$envkey};
 4387:                                     $managers =~ s/,/, /g;
 4388:                                     $newaccesstext->{$tool} = $managers;
 4389:                                 }
 4390:                             } elsif ($tool eq 'webdav') {
 4391:                                 if ($newval) {
 4392:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4393:                                 } else {
 4394:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4395:                                 }
 4396:                             }
 4397:                         } else {
 4398:                             if ($newval) {
 4399:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4400:                             } else {
 4401:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4402:                             }
 4403:                         }
 4404:                     } else {
 4405:                         $newaccess->{$tool} = $oldaccess->{$tool};
 4406:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4407:                             if ($userenv->{$envkey} =~ /^autolimit/) {
 4408:                                 if ($limit) {
 4409:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4410:                                 } else {
 4411:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4412:                                 }
 4413:                             } elsif ($userenv->{$envkey}) {
 4414:                                 $newaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4415:                             } else {
 4416:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4417:                             }
 4418:                         } elsif ($context eq 'authordefaults') {
 4419:                             if ($tool eq 'editors') {
 4420:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4421:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4422:                             } elsif ($tool eq 'managers') {
 4423:                                 if ($userenv->{$envkey} eq '') {
 4424:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4425:                                 } else {
 4426:                                     my $managers = $userenv->{$envkey};
 4427:                                     $managers =~ s/,/, /g;
 4428:                                     $newaccesstext->{$tool} = $managers;
 4429:                                 }
 4430:                             } elsif ($tool eq 'webdav') {
 4431:                                 if ($userenv->{$envkey}) {
 4432:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4433:                                 } else {
 4434:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4435:                                 }
 4436:                             }
 4437:                         } else {
 4438:                             if ($userenv->{$context.'.'.$tool}) {
 4439:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4440:                             } else {
 4441:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4442:                             }
 4443:                         }
 4444:                     }
 4445:                 } else {
 4446:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4447:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4448:                 }
 4449:             } else {
 4450:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 4451:                 if ($changed->{$tool}) {
 4452:                     $newaccess->{$tool} = &mt('default');
 4453:                 } else {
 4454:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4455:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4456:                         if ($newval =~ /^autolimit/) {
 4457:                             if ($limit) {
 4458:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4459:                             } else {
 4460:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4461:                             }
 4462:                         } elsif ($newval) {
 4463:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4464:                         } else {
 4465:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4466:                         }
 4467:                     } elsif ($context eq 'authordefaults') {
 4468:                         if ($tool eq 'editors') {
 4469:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4470:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4471:                         } elsif ($tool eq 'managers') {
 4472:                             if ($newval eq '') {
 4473:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4474:                             } else {
 4475:                                 my $managers = $newval;
 4476:                                 $managers =~ s/,/, /g;
 4477:                                 $newaccesstext->{$tool} = $managers;
 4478:                             }
 4479:                         } elsif ($tool eq 'webdav') {
 4480:                             if ($userenv->{$envkey}) {
 4481:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4482:                             } else {
 4483:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4484:                             }
 4485:                         }
 4486:                     } else {
 4487:                         if ($userenv->{$context.'.'.$tool}) {
 4488:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4489:                         } else {
 4490:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4491:                         }
 4492:                     }
 4493:                 }
 4494:             }
 4495:         } else {
 4496:             $oldaccess->{$tool} = &mt('default');
 4497:             if (($env{'form.custom'.$tool} == 1) ||
 4498:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4499:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4500:                                                 $context);
 4501:                 if ($changed->{$tool}) {
 4502:                     $newaccess->{$tool} = &mt('custom');
 4503:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4504:                         if ($newval =~ /^autolimit/) {
 4505:                             if ($limit) {
 4506:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4507:                             } else {
 4508:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4509:                             }
 4510:                         } elsif ($newval) {
 4511:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4512:                         } else {
 4513:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4514:                         }
 4515:                     } elsif ($context eq 'authordefaults') {
 4516:                         if ($tool eq 'managers') {
 4517:                             if ($newval eq '') {
 4518:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4519:                             } else {
 4520:                                 my $managers = $newval;
 4521:                                 $managers =~ s/,/, /g;
 4522:                                 $newaccesstext->{$tool} = $managers;
 4523:                             }
 4524:                         } elsif ($tool eq 'editors') {
 4525:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4526:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4527:                         } elsif ($tool eq 'webdav') {
 4528:                             if ($newval) {
 4529:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4530:                             } else {
 4531:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4532:                             }
 4533:                         }
 4534:                     } else {
 4535:                         if ($newval) {
 4536:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4537:                         } else {
 4538:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4539:                         }
 4540:                     }
 4541:                 } else {
 4542:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4543:                 }
 4544:             } else {
 4545:                 $newaccess->{$tool} = $oldaccess->{$tool};
 4546:             }
 4547:         }
 4548:     }
 4549:     return;
 4550: }
 4551: 
 4552: sub update_roles {
 4553:     my ($r,$context,$showcredits) = @_;
 4554:     my $now=time;
 4555:     my @rolechanges;
 4556:     my (%disallowed,%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 4557:         %pending,%reject,%notifydc,%status,%unauthorized,%currqueued);
 4558:     $got_role_approvals{$context} = '';
 4559:     $process_by{$context} = {};
 4560:     my @domroles = &Apache::lonuserutils::domain_roles();
 4561:     my @cstrroles = &Apache::lonuserutils::construction_space_roles();
 4562:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
 4563:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 4564:     foreach my $key (keys(%env)) {
 4565: 	next if (! $env{$key});
 4566:         next if ($key eq 'form.action');
 4567: 	# Revoke roles
 4568: 	if ($key=~/^form\.rev/) {
 4569: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 4570: # Revoke standard role
 4571: 		my ($scope,$role) = ($1,$2);
 4572: 		my $result =
 4573: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 4574: 						$env{'form.ccuname'},
 4575: 						$scope,$role,'','',$context);
 4576:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4577:                             &mt('Revoking [_1] in [_2]',
 4578:                                 &Apache::lonnet::plaintext($role),
 4579:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4580:                                 $result ne "ok").'<br />');
 4581:                 if ($result ne "ok") {
 4582:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4583:                 }
 4584: 		if ($role eq 'st') {
 4585: 		    my $result = 
 4586:                         &Apache::lonuserutils::classlist_drop($scope,
 4587:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4588: 			    $now);
 4589:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4590: 		}
 4591:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4592:                     push(@rolechanges,$role);
 4593:                 }
 4594: 	    }
 4595: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4596: # Revoke custom role
 4597:                 my $result = &Apache::lonnet::revokecustomrole(
 4598:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4599:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4600:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4601:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4602:                             $result ne 'ok').'<br />');
 4603:                 if ($result ne "ok") {
 4604:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4605:                 }
 4606:                 if (!grep(/^cr$/,@rolechanges)) {
 4607:                     push(@rolechanges,'cr');
 4608:                 }
 4609: 	    }
 4610: 	} elsif ($key=~/^form\.del/) {
 4611: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4612: # Delete standard role
 4613: 		my ($scope,$role) = ($1,$2);
 4614: 		my $result =
 4615: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4616: 						$env{'form.ccuname'},
 4617: 						$scope,$role,$now,0,1,'',
 4618:                                                 $context);
 4619:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4620:                             &mt('Deleting [_1] in [_2]',
 4621:                                 &Apache::lonnet::plaintext($role),
 4622:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4623:                             $result ne 'ok').'<br />');
 4624:                 if ($result ne "ok") {
 4625:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4626:                 }
 4627: 
 4628: 		if ($role eq 'st') {
 4629: 		    my $result = 
 4630:                         &Apache::lonuserutils::classlist_drop($scope,
 4631:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4632: 			    $now);
 4633: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4634: 		}
 4635:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4636:                     push(@rolechanges,$role);
 4637:                 }
 4638:             }
 4639: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4640:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4641: # Delete custom role
 4642:                 my $result =
 4643:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4644:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4645:                         0,1,$context);
 4646:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4647:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4648:                       $result ne "ok").'<br />');
 4649:                 if ($result ne "ok") {
 4650:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4651:                 }
 4652: 
 4653:                 if (!grep(/^cr$/,@rolechanges)) {
 4654:                     push(@rolechanges,'cr');
 4655:                 }
 4656:             }
 4657: 	} elsif ($key=~/^form\.ren/) {
 4658:             my $udom = $env{'form.ccdomain'};
 4659:             my $uname = $env{'form.ccuname'};
 4660: # Re-enable standard role
 4661: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4662:                 my $url = $1;
 4663:                 my $role = $2;
 4664:                 my $id = $url.'_'.$role;
 4665:                 my $logmsg;
 4666:                 my $output;
 4667:                 if ($role eq 'st') {
 4668:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4669:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4670:                         my $credits;
 4671:                         if ($showcredits) {
 4672:                             my $defaultcredits =
 4673:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4674:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4675:                         }
 4676:                         unless ($udom eq $cdom) {
 4677:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4678:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,$credits,
 4679:                                          \%process_by,\%instdoms,\%got_role_approvals,
 4680:                                          \%got_instdoms,\%reject,\%pending,\%notifydc,
 4681:                                          \%status,\%unauthorized,\%currqueued));
 4682:                         }
 4683:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4684:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4685:                             if ($result eq 'refused' && $logmsg) {
 4686:                                 $output = $logmsg;
 4687:                             } else { 
 4688:                                 $output = &mt('Error: [_1]',$result)."\n";
 4689:                             }
 4690:                         } else {
 4691:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4692:                                         &Apache::lonnet::plaintext($role),
 4693:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4694:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4695:                         }
 4696:                     }
 4697:                 } else {
 4698:                     my ($cdom,$cnum,$csec);
 4699:                     if (grep(/^\Q$role\E$/,@cstrroles)) {
 4700:                         ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_username)$});
 4701:                     } elsif (grep(/^\Q$role\E$/,@domroles)) {
 4702:                         ($cdom) = ($url =~ m{^/($match_domain)/$});
 4703:                     } elsif ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4704:                         ($cdom,$cnum,$csec) = ($1,$2,$3);
 4705:                     }
 4706:                     if ($cdom ne '') {
 4707:                         unless ($udom eq $cdom) {
 4708:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4709:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4710:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4711:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4712:                         }
 4713:                     }
 4714: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4715:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4716:                                $context);
 4717:                     $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4718:                                     &Apache::lonnet::plaintext($role),
 4719:                                     &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4720:                     if ($result ne "ok") {
 4721:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4722:                     }
 4723:                 }
 4724:                 $r->print($output);
 4725:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4726:                     push(@rolechanges,$role);
 4727:                 }
 4728: 	    }
 4729: # Re-enable custom role
 4730: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4731:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4732:                 my $id = $url.'_cr'."/$rdom/$rnam/$rolename";
 4733:                 my $role = "cr/$rdom/$rnam/$rolename";
 4734:                 if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4735:                     my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4736:                     unless ($udom eq $cdom) {
 4737:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4738:                                      $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4739:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4740:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4741:                     }
 4742:                 }
 4743:                 my $result = &Apache::lonnet::assigncustomrole(
 4744:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4745:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4746:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4747:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4748:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4749:                     $result ne "ok").'<br />');
 4750:                 if ($result ne "ok") {
 4751:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4752:                 }
 4753:                 if (!grep(/^cr$/,@rolechanges)) {
 4754:                     push(@rolechanges,'cr');
 4755:                 }
 4756:             }
 4757: 	} elsif ($key=~/^form\.act/) {
 4758:             my $udom = $env{'form.ccdomain'};
 4759:             my $uname = $env{'form.ccuname'};
 4760: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4761:                 # Activate a custom role
 4762: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4763: 		my $url='/'.$one.'/'.$two;
 4764:                 my $id = $url.'_cr/'."$three/$four/$five";
 4765:                 my $role = "cr/$three/$four/$five";
 4766: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4767: 
 4768:                 my $start = ( $env{'form.start_'.$full} ?
 4769:                               $env{'form.start_'.$full} :
 4770:                               $now );
 4771:                 my $end   = ( $env{'form.end_'.$full} ?
 4772:                               $env{'form.end_'.$full} :
 4773:                               0 );
 4774: 
 4775:                 # split multiple sections
 4776:                 my %sections = ();
 4777:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$five);
 4778:                 if ($num_sections == 0) {
 4779:                     unless ($udom eq $one) {
 4780:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4781:                                      $uname,$role,$start,$end,$one,$two,'','',\%process_by,
 4782:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4783:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4784:                     }
 4785:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4786:                 } else {
 4787: 		    my %curr_groups =
 4788: 			&Apache::longroup::coursegroups($one,$two);
 4789:                     my ($restricted,$numchanges);
 4790:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4791:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4792:                             exists($curr_groups{$sec})) {
 4793:                             $disallowed{$sec} = $url;
 4794:                             next;
 4795:                         }
 4796:                         my $securl = $url.'/'.$sec;
 4797:                         my $secid = $securl.'_cr'."/$three/$four/$five";
 4798:                         undef($restricted);
 4799:                         unless ($udom eq $one) {
 4800:                             next if (&Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4801:                                          $uname,$role,$start,$end,$one,$two,$sec,'',\%process_by,
 4802:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4803:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4804:                         }
 4805:                         $numchanges ++;
 4806: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4807:                     }
 4808:                     next unless ($numchanges);
 4809:                 }
 4810:                 if (!grep(/^cr$/,@rolechanges)) {
 4811:                     push(@rolechanges,'cr');
 4812:                 }
 4813: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4814: 		# Activate roles for sections with 3 id numbers
 4815: 		# set start, end times, and the url for the class
 4816: 		my ($one,$two,$three)=($1,$2,$3);
 4817: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ?
 4818: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} :
 4819: 			      $now );
 4820: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ?
 4821: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4822: 			      0 );
 4823: 		my $url='/'.$one.'/'.$two;
 4824:                 my $id = $url.'_'.$three;
 4825:                 # split multiple sections
 4826:                 my %sections = ();
 4827:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4828:                 my ($credits,$numchanges);
 4829:                 if ($three eq 'st') {
 4830:                     if ($showcredits) {
 4831:                         my $defaultcredits = 
 4832:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4833:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4834:                         $credits =~ s/[^\d\.]//g;
 4835:                         if ($credits eq $defaultcredits) {
 4836:                             undef($credits);
 4837:                         }
 4838:                     }
 4839:                 }
 4840:                 if ($num_sections == 0) {
 4841:                     unless ($udom eq $one) {
 4842:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4843:                                      $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4844:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4845:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4846:                     }
 4847:                     $numchanges ++;
 4848:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4849:                 } else {
 4850:                     my %curr_groups = 
 4851: 			&Apache::longroup::coursegroups($one,$two);
 4852:                     my $emptysec = 0;
 4853:                     my $restricted;
 4854:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4855:                         $sec =~ s/\W//g;
 4856:                         if ($sec ne '') {
 4857:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4858:                                 exists($curr_groups{$sec})) {
 4859:                                 $disallowed{$sec} = $url;
 4860:                                 next;
 4861:                             }
 4862:                             my $securl = $url.'/'.$sec;
 4863:                             my $secid = $securl.'_'.$three;
 4864:                             unless ($udom eq $one) {
 4865:                                 undef($restricted);
 4866:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4867:                                                   $uname,$three,$start,$end,$one,$two,$sec,$credits,\%process_by,
 4868:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4869:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4870:                                 next if ($restricted);
 4871:                             }
 4872:                             $numchanges ++;
 4873:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4874:                         } else {
 4875:                             $emptysec = 1;
 4876:                         }
 4877:                     }
 4878:                     if ($emptysec) {
 4879:                         unless ($udom eq $one) {
 4880:                             undef($restricted);
 4881:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4882:                                               $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4883:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4884:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4885:                             next if ($restricted);
 4886:                         }
 4887:                         $numchanges ++;
 4888:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4889:                     }
 4890:                     next unless ($numchanges);
 4891:                 }
 4892:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4893:                     push(@rolechanges,$three);
 4894:                 }
 4895: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4896: 		# Activate roles for sections with two id numbers
 4897: 		# set start, end times, and the url for the class
 4898: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ?
 4899: 			      $env{'form.start_'.$1.'_'.$2} :
 4900: 			      $now );
 4901: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ?
 4902: 			      $env{'form.end_'.$1.'_'.$2} :
 4903: 			      0 );
 4904:                 my $one = $1;
 4905:                 my $two = $2;
 4906: 		my $url='/'.$one.'/';
 4907:                 my $id = $url.'_'.$two;
 4908:                 my ($cdom,$cnum) = split(/\//,$one);
 4909:                 # split multiple sections
 4910:                 my %sections = ();
 4911:                 my ($restricted,$numchanges);
 4912:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4913:                 if ($num_sections == 0) {
 4914:                     unless ($udom eq $one) {
 4915:                         $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4916:                                           $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4917:                                           \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4918:                                           \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4919:                         next if ($restricted);
 4920:                     }
 4921:                     $numchanges ++;
 4922:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4923:                 } else {
 4924:                     my $emptysec = 0;
 4925:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4926:                         if ($sec ne '') {
 4927:                             my $securl = $url.'/'.$sec;
 4928:                             my $secid = $securl.'_'.$two;
 4929:                             unless ($udom eq $one) {
 4930:                                 undef($restricted);
 4931:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4932:                                                   $uname,$two,$start,$end,$cdom,$cnum,$sec,'',\%process_by,
 4933:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4934:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4935:                                 next if ($restricted);
 4936:                             }
 4937:                             $numchanges ++;
 4938:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4939:                         } else {
 4940:                             $emptysec = 1;
 4941:                         }
 4942:                     }
 4943:                     if ($emptysec) {
 4944:                         unless ($udom eq $one) {
 4945:                             undef($restricted);
 4946:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4947:                                               $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4948:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4949:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4950:                             next if ($restricted);
 4951:                         }
 4952:                         $numchanges ++;
 4953:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4954:                     }
 4955:                     next unless ($numchanges); 
 4956:                 }
 4957:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4958:                     push(@rolechanges,$two);
 4959:                 }
 4960: 	    } else {
 4961: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4962:             }
 4963:             foreach my $key (sort(keys(%disallowed))) {
 4964:                 $r->print('<p class="LC_warning">');
 4965:                 if (($key eq 'none') || ($key eq 'all')) {  
 4966:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4967:                 } else {
 4968:                     $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>'));
 4969:                 }
 4970:                 $r->print('</p><p>'
 4971:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4972:                              ,'<a href="javascript:history.go(-1)'
 4973:                              ,'</a>')
 4974:                          .'</p><br />'
 4975:                 );
 4976:             }
 4977: 	}
 4978:     } # End of foreach (keys(%env))
 4979:     if ((keys(%reject)) || (keys(%unauthorized))) {
 4980:         $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 4981:     }
 4982:     if ((keys(%pending)) || (keys(%currqueued))) {
 4983:         $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 4984:     }
 4985: # Flush the course logs so reverse user roles immediately updated
 4986:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4987:     if (@rolechanges == 0) {
 4988:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4989:     }
 4990:     return @rolechanges;
 4991: }
 4992: 
 4993: sub get_user_credits {
 4994:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4995:     if ($cdom eq '' || $cnum eq '') {
 4996:         return unless ($env{'request.course.id'});
 4997:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4998:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4999:     }
 5000:     my $credits;
 5001:     my %currhash =
 5002:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 5003:     if (keys(%currhash) > 0) {
 5004:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 5005:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 5006:         $credits = $items[$crdidx];
 5007:         $credits =~ s/[^\d\.]//g;
 5008:     }
 5009:     if ($credits eq $defaultcredits) {
 5010:         undef($credits);
 5011:     }
 5012:     return $credits;
 5013: }
 5014: 
 5015: sub enroll_single_student {
 5016:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 5017:         $showcredits,$defaultcredits) = @_;
 5018:     $r->print('<h3>');
 5019:     if ($crstype eq 'Community') {
 5020:         $r->print(&mt('Enrolling Member'));
 5021:     } else {
 5022:         $r->print(&mt('Enrolling Student'));
 5023:     }
 5024:     $r->print('</h3>');
 5025: 
 5026:     # Remove non alphanumeric values from section
 5027:     $env{'form.sections'}=~s/\W//g;
 5028: 
 5029:     my $credits;
 5030:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 5031:         $credits = $env{'form.credits'};
 5032:         $credits =~ s/[^\d\.]//g;
 5033:         if ($credits ne '') {
 5034:             if ($credits eq $defaultcredits) {
 5035:                 undef($credits);
 5036:             }
 5037:         }
 5038:     }
 5039:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 5040:     my (%got_role_approvals,%got_instdoms,%process_by,%instdoms,%pending,%reject,%notifydc,
 5041:         %status,%unauthorized,%currqueued);
 5042:     unless ($env{'form.ccdomain'} eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 5043:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5044:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5045:         my $csec = $env{'form.sections'};
 5046:         my $id = "/$cdom/$cnum";
 5047:         if ($csec ne '') {
 5048:             $id .= "/$csec";
 5049:         }
 5050:         $id .= '_st';
 5051:         if (&Apache::lonuserutils::restricted_dom($context,$id,$env{'form.ccdomain'},$env{'form.ccuname'},
 5052:                                                   'st',$startdate,$enddate,$cdom,$cnum,$csec,$credits,
 5053:                                                   \%process_by,\%instdoms,\%got_role_approvals,\%got_instdoms,
 5054:                                                   \%reject,\%pending,\%notifydc,\%status,\%unauthorized,\%currqueued)) {
 5055:             if ((keys(%reject)) || (keys(%unauthorized))) {
 5056:                 $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5057:             }
 5058:             if ((keys(%pending)) || (keys(%currqueued))) {
 5059:                 $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5060:             }
 5061:             return;
 5062:         }
 5063:     }
 5064: 
 5065:     # Clean out any old student roles the user has in this class.
 5066:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 5067:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 5068:     my $enroll_result =
 5069:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 5070:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 5071:             $env{'form.cmiddlename'},$env{'form.clastname'},
 5072:             $env{'form.generation'},$env{'form.sections'},$enddate,
 5073:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 5074:             $credits);
 5075:     if ($enroll_result =~ /^ok/) {
 5076:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 5077:         if ($env{'form.sections'} ne '') {
 5078:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 5079:         }
 5080:         my ($showstart,$showend);
 5081:         if ($startdate <= $now) {
 5082:             $showstart = &mt('Access starts immediately');
 5083:         } else {
 5084:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 5085:         }
 5086:         if ($enddate == 0) {
 5087:             $showend = &mt('ends: no ending date');
 5088:         } else {
 5089:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 5090:         }
 5091:         $r->print('.<br />'.$showstart.'; '.$showend);
 5092:         if ($startdate <= $now && !$newuser) {
 5093:             $r->print('<p class="LC_info">');
 5094:             if ($crstype eq 'Community') {
 5095:                 $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.'));
 5096:             } else {
 5097:                 $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.'));
 5098:            }
 5099:            $r->print('</p>');
 5100:         }
 5101:     } else {
 5102:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 5103:     }
 5104:     return;
 5105: }
 5106: 
 5107: sub get_defaultquota_text {
 5108:     my ($settingstatus) = @_;
 5109:     my $defquotatext; 
 5110:     if ($settingstatus eq '') {
 5111:         $defquotatext = &mt('default');
 5112:     } else {
 5113:         my ($usertypes,$order) =
 5114:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 5115:         if ($usertypes->{$settingstatus} eq '') {
 5116:             $defquotatext = &mt('default');
 5117:         } else {
 5118:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 5119:         }
 5120:     }
 5121:     return $defquotatext;
 5122: }
 5123: 
 5124: sub update_result_form {
 5125:     my ($uhome) = @_;
 5126:     my $outcome = 
 5127:     '<form name="userupdate" method="post" action="">'."\n";
 5128:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 5129:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5130:     }
 5131:     if ($env{'form.origname'} ne '') {
 5132:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 5133:     }
 5134:     foreach my $item ('sortby','seluname','seludom') {
 5135:         if (exists($env{'form.'.$item})) {
 5136:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5137:         }
 5138:     }
 5139:     if ($uhome eq 'no_host') {
 5140:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 5141:     }
 5142:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 5143:                 '<input type="hidden" name="currstate" value="" />'."\n".
 5144:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5145:                 '</form>';
 5146:     return $outcome;
 5147: }
 5148: 
 5149: sub quota_admin {
 5150:     my ($setquota,$changeHash,$name) = @_;
 5151:     my $quotachanged;
 5152:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 5153:         # Current user has quota modification privileges
 5154:         if (ref($changeHash) eq 'HASH') {
 5155:             $quotachanged = 1;
 5156:             $changeHash->{$name.'quota'} = $setquota;
 5157:         }
 5158:     }
 5159:     return $quotachanged;
 5160: }
 5161: 
 5162: sub tool_admin {
 5163:     my ($tool,$settool,$changeHash,$context) = @_;
 5164:     my $canchange = 0; 
 5165:     if ($context eq 'requestcourses') {
 5166:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 5167:             $canchange = 1;
 5168:         }
 5169:     } elsif ($context eq 'reqcrsotherdom') {
 5170:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 5171:             $canchange = 1;
 5172:         }
 5173:     } elsif ($context eq 'requestauthor') {
 5174:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5175:             $canchange = 1;
 5176:         }
 5177:     } elsif ($context eq 'authordefaults') {
 5178:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5179:             $canchange = 1;
 5180:         }
 5181:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 5182:         # Current user has quota modification privileges
 5183:         $canchange = 1;
 5184:     }
 5185:     my $toolchanged;
 5186:     if ($canchange) {
 5187:         if (ref($changeHash) eq 'HASH') {
 5188:             $toolchanged = 1;
 5189:             if ($tool eq 'requestauthor') {
 5190:                 $changeHash->{$context} = $settool;
 5191:             } elsif (($tool eq 'managers') || ($tool eq 'editors')) {
 5192:                 $changeHash->{'author'.$tool} = $settool;
 5193:             } elsif ($tool eq 'webdav') {
 5194:                 $changeHash->{'tools.'.$tool} = $settool;
 5195:             } else {
 5196:                 $changeHash->{$context.'.'.$tool} = $settool;
 5197:             }
 5198:         }
 5199:     }
 5200:     return $toolchanged;
 5201: }
 5202: 
 5203: sub build_roles {
 5204:     my ($sectionstr,$sections,$role) = @_;
 5205:     my $num_sections = 0;
 5206:     if ($sectionstr=~ /,/) {
 5207:         my @secnums = split/,/,$sectionstr;
 5208:         if ($role eq 'st') {
 5209:             $secnums[0] =~ s/\W//g;
 5210:             $$sections{$secnums[0]} = 1;
 5211:             $num_sections = 1;
 5212:         } else {
 5213:             foreach my $sec (@secnums) {
 5214:                 $sec =~ ~s/\W//g;
 5215:                 if (!($sec eq "")) {
 5216:                     if (exists($$sections{$sec})) {
 5217:                         $$sections{$sec} ++;
 5218:                     } else {
 5219:                         $$sections{$sec} = 1;
 5220:                         $num_sections ++;
 5221:                     }
 5222:                 }
 5223:             }
 5224:         }
 5225:     } else {
 5226:         $sectionstr=~s/\W//g;
 5227:         unless ($sectionstr eq '') {
 5228:             $$sections{$sectionstr} = 1;
 5229:             $num_sections ++;
 5230:         }
 5231:     }
 5232: 
 5233:     return $num_sections;
 5234: }
 5235: 
 5236: # ========================================================== Custom Role Editor
 5237: 
 5238: sub custom_role_editor {
 5239:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5240:     my $action = $env{'form.customroleaction'};
 5241:     my ($rolename,$helpitem);
 5242:     if ($action eq 'new') {
 5243:         $rolename=$env{'form.newrolename'};
 5244:     } else {
 5245:         $rolename=$env{'form.rolename'};
 5246:     }
 5247: 
 5248:     my ($crstype,$context);
 5249:     if ($env{'request.course.id'}) {
 5250:         $crstype = &Apache::loncommon::course_type();
 5251:         $context = 'course';
 5252:         $helpitem = 'Course_Editing_Custom_Roles';
 5253:     } else {
 5254:         $context = 'domain';
 5255:         $crstype = 'course';
 5256:         $helpitem = 'Domain_Editing_Custom_Roles';
 5257:     }
 5258: 
 5259:     $rolename=~s/[^A-Za-z0-9]//gs;
 5260:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 5261: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 5262:                                    $permission);
 5263:         return;
 5264:     }
 5265: 
 5266:     my $formname = 'form1';
 5267:     my %privs=();
 5268:     my $body_top = '<h2>';
 5269: # ------------------------------------------------------- Does this role exist?
 5270:     my ($rdummy,$roledef)=
 5271: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5272:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5273:         $body_top .= &mt('Existing Role').' "';
 5274: # ------------------------------------------------- Get current role privileges
 5275:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 5276:         if ($privs{'system'} =~ /bre\&S/) {
 5277:             if ($context eq 'domain') {
 5278:                 $crstype = 'Course';
 5279:             } elsif ($crstype eq 'Community') {
 5280:                 $privs{'system'} =~ s/bre\&S//;
 5281:             }
 5282:         } elsif ($context eq 'domain') {
 5283:             $crstype = 'Course';
 5284:         }
 5285:     } else {
 5286:         $body_top .= &mt('New Role').' "';
 5287:         $roledef='';
 5288:     }
 5289:     $body_top .= $rolename.'"</h2>';
 5290: 
 5291: # ------------------------------------------------------- What can be assigned?
 5292:     my %full=();
 5293:     my %levels=(
 5294:                  course => {},
 5295:                  domain => {},
 5296:                  system => {},
 5297:                );
 5298:     my %levelscurrent=(
 5299:                         course => {},
 5300:                         domain => {},
 5301:                         system => {},
 5302:                       );
 5303:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5304:     my ($jsback,$elements) = &crumb_utilities();
 5305:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5306:     my $head_script =
 5307:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 5308:                                                   \%full,\@templateroles,$jsback);
 5309:     push (@{$brcrum},
 5310:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 5311:                text => "Pick custom role",
 5312:                faq  => 282,bug=>'Instructor Interface',},
 5313:               {href => "javascript:backPage(document.$formname,'','')",
 5314:                text => "Edit custom role",
 5315:                faq  => 282,
 5316:                bug  => 'Instructor Interface',
 5317:                help => $helpitem}
 5318:               );
 5319:     my $args = { bread_crumbs          => $brcrum,
 5320:                  bread_crumbs_component => 'User Management'};
 5321:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 5322:                                              $head_script,$args).
 5323:               $body_top);
 5324:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 5325:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 5326:                                                         \@templateroles,$prefix));
 5327: 
 5328:     $r->print(<<ENDCCF);
 5329: <input type="hidden" name="phase" value="set_custom_roles" />
 5330: <input type="hidden" name="rolename" value="$rolename" />
 5331: ENDCCF
 5332:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5333:                                                        \%levelscurrent,$prefix));
 5334:     $r->print(&Apache::loncommon::end_data_table().
 5335:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 5336:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 5337:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 5338:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 5339:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 5340: }
 5341: 
 5342: # ---------------------------------------------------------- Call to definerole
 5343: sub set_custom_role {
 5344:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5345:     my $rolename=$env{'form.rolename'};
 5346:     $rolename=~s/[^A-Za-z0-9]//gs;
 5347:     if (!$rolename) {
 5348: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5349:         return;
 5350:     }
 5351:     my ($jsback,$elements) = &crumb_utilities();
 5352:     my $jscript = '<script type="text/javascript">'
 5353:                  .'// <![CDATA['."\n"
 5354:                  .$jsback."\n"
 5355:                  .'// ]]>'."\n"
 5356:                  .'</script>'."\n";
 5357:     my $helpitem = 'Course_Editing_Custom_Roles';
 5358:     if ($context eq 'domain') {
 5359:         $helpitem = 'Domain_Editing_Custom_Roles';
 5360:     }
 5361:     push(@{$brcrum},
 5362:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 5363:          text => "Pick custom role",
 5364:          faq  => 282,
 5365:          bug  => 'Instructor Interface',},
 5366:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 5367:          text => "Edit custom role",
 5368:          faq  => 282,
 5369:          bug  => 'Instructor Interface',},
 5370:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 5371:          text => "Result",
 5372:          faq  => 282,
 5373:          bug  => 'Instructor Interface',
 5374:          help => $helpitem,}
 5375:         );
 5376:     my $args = { bread_crumbs           => $brcrum,
 5377:                  bread_crumbs_component => 'User Management'};
 5378:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 5379: 
 5380:     my $newrole;
 5381:     my ($rdummy,$roledef)=
 5382: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5383: 
 5384: # ------------------------------------------------------- Does this role exist?
 5385:     $r->print('<h3>');
 5386:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5387: 	$r->print(&mt('Existing Role').' "');
 5388:     } else {
 5389: 	$r->print(&mt('New Role').' "');
 5390: 	$roledef='';
 5391:         $newrole = 1;
 5392:     }
 5393:     $r->print($rolename.'"</h3>');
 5394: # ------------------------------------------------- Assign role and show result
 5395: 
 5396:     my $errmsg;
 5397:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 5398:     # Assign role and return result
 5399:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 5400:                                              $newprivs{'c'});
 5401:     if ($result ne 'ok') {
 5402:         $errmsg = ': '.$result;
 5403:     }
 5404:     my $message =
 5405:         &Apache::lonhtmlcommon::confirm_success(
 5406:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 5407:     if ($env{'request.course.id'}) {
 5408:         my $url='/'.$env{'request.course.id'};
 5409:         $url=~s/\_/\//g;
 5410:         $result =
 5411:             &Apache::lonnet::assigncustomrole(
 5412:                 $env{'user.domain'},$env{'user.name'},
 5413:                 $url,
 5414:                 $env{'user.domain'},$env{'user.name'},
 5415:                 $rolename,undef,undef,undef,$context);
 5416:         if ($result ne 'ok') {
 5417:             $errmsg = ': '.$result;
 5418:         }
 5419:         $message .=
 5420:             '<br />'
 5421:            .&Apache::lonhtmlcommon::confirm_success(
 5422:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 5423:     }
 5424:     $r->print(
 5425:         &Apache::loncommon::confirmwrapper($message)
 5426:        .'<br />'
 5427:        .&Apache::lonhtmlcommon::actionbox([
 5428:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 5429:            .&mt('Create or edit another custom role')
 5430:            .'</a>'])
 5431:        .'<form name="customresult" method="post" action="">'
 5432:        .&Apache::lonhtmlcommon::echo_form_input([])
 5433:        .'</form>'
 5434:     );
 5435: }
 5436: 
 5437: sub show_role_requests {
 5438:     my ($caller,$dom) = @_;
 5439:     my $showrolereqs;
 5440:     my %domconfig = &Apache::lonnet::get_dom('configuration',['privacy'],$dom);
 5441:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 5442:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 5443:             my %approvalconf = %{$domconfig{'privacy'}{'approval'}};
 5444:             foreach my $key ('instdom','extdom') {
 5445:                 if (ref($approvalconf{$key}) eq 'HASH') {
 5446:                     if (keys(%{$approvalconf{$key}})) {
 5447:                         foreach my $context ('domain','author','course','community') {
 5448:                             if ($approvalconf{$key}{$context} eq $caller) {
 5449:                                 $showrolereqs = 1;
 5450:                                 last if ($showrolereqs);
 5451:                             }
 5452:                         }
 5453:                     }
 5454:                 }
 5455:                 last if ($showrolereqs);
 5456:             }
 5457:         }
 5458:     }
 5459:     return $showrolereqs;
 5460: }
 5461: 
 5462: sub display_coauthor_managers {
 5463:     my ($permission) = @_;
 5464:     my $output;
 5465:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5466:         $output = '<form action="/adm/createuser" method="post" name="camanagers">'.
 5467:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5468:                   '<p>';
 5469:         my (@possmanagers,@custommanagers);
 5470:         my %userenv =
 5471:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5472:                                              $env{'user.name'},
 5473:                                              'authormanagers');
 5474:         my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5475:                                                      ['active','future'],['ca']);
 5476:         if (keys(%ca_roles)) {
 5477:             foreach my $entry (sort(keys(%ca_roles))) {
 5478:                 if ($entry =~ /^($match_username\:$match_domain):ca$/) {
 5479:                     my $user = $1;
 5480:                     unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5481:                         push(@possmanagers,$user);
 5482:                     }
 5483:                 }
 5484:             }
 5485:         }
 5486:         if ($userenv{'authormanagers'} eq '') {
 5487:             $output .= &mt('Currently author manages co-author roles');
 5488:         } else {
 5489:             if (keys(%ca_roles)) {
 5490:                 foreach my $user (split(/,/,$userenv{'authormanagers'})) {
 5491:                     if ($user =~ /^($match_username)\:($match_domain)$/) {
 5492:                         if (exists($ca_roles{$user.':ca'})) {
 5493:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5494:                                 push(@custommanagers,$user);
 5495:                             }
 5496:                         }
 5497:                     }
 5498:                 }
 5499:             }
 5500:             if (@custommanagers) {
 5501:                 $output .= &mt('Co-authors with active or future roles who currently manage co-author roles: [_1]',
 5502:                               '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @custommanagers));
 5503:             } else {
 5504:                 $output .= &mt('Currently author manages co-author roles');
 5505:             }
 5506:         }
 5507:         $output .= "</p>\n";
 5508:         if (@possmanagers) {
 5509:             $output .= '<p>'.&mt('If checked, can manage').': ';
 5510:             foreach my $user (@possmanagers) {
 5511:                  my $checked;
 5512:                  if (grep(/^\Q$user\E$/,@custommanagers)) {
 5513:                      $checked = ' checked="checked"';
 5514:                  }
 5515:                  $output .= '<span style="LC_nobreak"><label>'.
 5516:                             '<input type="checkbox" name="custommanagers" '.
 5517:                             'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
 5518:                             &Apache::loncommon::plainname(split(/:/,$user))." ($user)".'</label></span> '."\n";
 5519:             }
 5520:             $output .= '<input type="hidden" name="state" value="process" /></p>'."\n".
 5521:                        '<p><input type="submit" value="'.&mt('Save changes').'" /></p>'."\n";
 5522:         } else {
 5523:             $output .= '<p>'.&mt('No co-author roles assignable as manager').'</p>';
 5524:         }
 5525:         $output .= '</form>';
 5526:     } else {
 5527:         $output = '<span class="LC_warning">'.
 5528:                   &mt('You do not have permission to perform this action').
 5529:                   '</span>';
 5530:     }
 5531:     return $output;
 5532: }
 5533: 
 5534: sub update_coauthor_managers {
 5535:     my ($permission) = @_;
 5536:     my $output;
 5537:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5538:         my ($current,$newval,@possibles,@managers);
 5539:         my %userenv =
 5540:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5541:                                              $env{'user.name'},
 5542:                                              'authormanagers');
 5543:         $current = $userenv{'authormanagers'};
 5544:         @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 5545:         if (@possibles) {
 5546:             my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5547:                                                          ['active','future'],['ca']);
 5548:             if (keys(%ca_roles)) {
 5549:                 foreach my $user (@possibles) {
 5550:                     if ($user =~ /^($match_username):($match_domain)$/) {
 5551:                         if (exists($ca_roles{$user.':ca'})) {
 5552:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5553:                                 push(@managers,$user);
 5554:                             }
 5555:                         }
 5556:                     }
 5557:                 }
 5558:                 if (@managers) {
 5559:                     $newval = join(',',sort(@managers));
 5560:                 }
 5561:             }
 5562:         }
 5563:         if ($current eq $newval) {
 5564:             $output = &mt('No changes made to management of co-author roles');
 5565:         } else {
 5566:             my $chgresult =
 5567:                 &Apache::lonnet::put('environment',{'authormanagers' => $newval},
 5568:                                      $env{'user.domain'},$env{'user.name'});
 5569:             if ($chgresult eq 'ok') {
 5570:                 &Apache::lonnet::appenv({'environment.authormanagers' => $newval});
 5571:                 my (@adds,@dels);
 5572:                 if ($newval eq '') {
 5573:                     @dels = split(/,/,$current);
 5574:                 } elsif ($current eq '') {
 5575:                     @adds = @managers;
 5576:                 } else {
 5577:                     my @old = split(/,/,$current);
 5578:                     my @diffs = &Apache::loncommon::compare_arrays(\@old,\@managers);
 5579:                     if (@diffs) {
 5580:                         foreach my $user (@diffs) {
 5581:                             if (grep(/^\Q$user\E$/,@old)) {
 5582:                                 push(@dels,$user);
 5583:                             } elsif (grep(/^\Q$user\E$/,@managers)) {
 5584:                                 push(@adds,$user);
 5585:                             }
 5586:                         }
 5587:                     }
 5588:                 }
 5589:                 my $key = "internal.manager./$env{'user.domain'}/$env{'user.name'}";
 5590:                 if (@dels) {
 5591:                     foreach my $user (@dels) {
 5592:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5593:                             &Apache::lonnet::del('environment',[$key],$2,$1);
 5594:                         }
 5595:                     }
 5596:                 }
 5597:                 if (@adds) {
 5598:                     foreach my $user (@adds) {
 5599:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5600:                             &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 5601:                         }
 5602:                     }
 5603:                 }
 5604:                 if ($newval eq '') {
 5605:                     $output = &mt('Management of co-authors set to be author-only');
 5606:                 } else {
 5607:                     $output .= &mt('Co-authors who can manage co-author roles set to: [_1]',
 5608:                                    '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @managers));
 5609:                 }
 5610:             }
 5611:         }
 5612:     } else {
 5613:         $output = '<span class="LC_warning">'.
 5614:                   &mt('You do not have permission to perform this action').
 5615:                   '</span>';
 5616:     }
 5617:     return $output;
 5618: }
 5619: 
 5620: # ================================================================ Main Handler
 5621: sub handler {
 5622:     my $r = shift;
 5623:     if ($r->header_only) {
 5624:        &Apache::loncommon::content_type($r,'text/html');
 5625:        $r->send_http_header;
 5626:        return OK;
 5627:     }
 5628:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 5629: 
 5630:     if ($env{'request.course.id'}) {
 5631:         $context = 'course';
 5632:         $crstype = &Apache::loncommon::course_type();
 5633:     } elsif ($env{'request.role'} =~ /^au\./) {
 5634:         $context = 'author';
 5635:     } elsif ($env{'request.role'} =~ m{^(ca|aa)\./$match_domain/$match_username$}) {
 5636:         $context = 'coauthor';
 5637:     } else {
 5638:         $context = 'domain';
 5639:     }
 5640: 
 5641:     my ($permission,$allowed) =
 5642:         &Apache::lonuserutils::get_permission($context,$crstype);
 5643:     if (($context eq 'coauthor') && ($allowed)) {
 5644:         $context = 'author';
 5645:     }
 5646: 
 5647:     if ($allowed) {
 5648:         my @allhelp;
 5649:         if ($context eq 'course') {
 5650:             $cid = $env{'request.course.id'};
 5651:             $cdom = $env{'course.'.$cid.'.domain'};
 5652:             $cnum = $env{'course.'.$cid.'.num'};
 5653: 
 5654:             if ($permission->{'cusr'}) {
 5655:                 push(@allhelp,'Course_Create_Class_List');
 5656:             }
 5657:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5658:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 5659:             }
 5660:             if ($permission->{'custom'}) {
 5661:                 push(@allhelp,'Course_Editing_Custom_Roles');
 5662:             }
 5663:             if ($permission->{'cusr'}) {
 5664:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 5665:             }
 5666:             unless ($permission->{'cusr_section'}) {
 5667:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 5668:                     push(@allhelp,'Course_Automated_Enrollment');
 5669:                 }
 5670:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 5671:                     push(@allhelp,'Course_Approve_Selfenroll');
 5672:                 }
 5673:             }
 5674:             if ($permission->{'grp_manage'}) {
 5675:                 push(@allhelp,'Course_Manage_Group');
 5676:             }
 5677:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5678:                 push(@allhelp,'Course_User_Logs');
 5679:             }
 5680:         } elsif ($context eq 'author') {
 5681:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5682:                            'Author_View_Coauthor_List','Author_User_Logs'));
 5683:         } elsif ($context eq 'coauthor') {
 5684:             if ($permission->{'cusr'}) {
 5685:                 push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5686:                                'Author_View_Coauthor_List','Author_User_Logs'));
 5687:             } elsif ($permission->{'view'}) {
 5688:                 push(@allhelp,'Author_View_Coauthor_List');
 5689:             }
 5690:         } else {
 5691:             if ($permission->{'cusr'}) {
 5692:                 push(@allhelp,'Domain_Change_Privileges');
 5693:                 if ($permission->{'activity'}) {
 5694:                     push(@allhelp,'Domain_User_Access_Logs');
 5695:                 }
 5696:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 5697:                 if ($permission->{'custom'}) {
 5698:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 5699:                 }
 5700:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 5701:             } elsif ($permission->{'view'}) {
 5702:                 push(@allhelp,'Domain_View_Privileges');
 5703:                 if ($permission->{'activity'}) {
 5704:                     push(@allhelp,'Domain_User_Access_Logs');
 5705:                 }
 5706:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 5707:             }
 5708:         }
 5709:         if (@allhelp) {
 5710:             $allhelpitems = join(',',@allhelp);
 5711:         }
 5712:     }
 5713: 
 5714:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5715:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 5716:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue',
 5717:          'forceedit']);
 5718:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5719:     my $args;
 5720:     my $brcrum = [];
 5721:     my $bread_crumbs_component = 'User Management';
 5722:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 5723:         $brcrum = [{href=>"/adm/createuser",
 5724:                     text=>"User Management",
 5725:                     help=>$allhelpitems}
 5726:                   ];
 5727:     }
 5728:     if (!$allowed) {
 5729:         if ($context eq 'course') {
 5730:             $r->internal_redirect('/adm/viewclasslist');
 5731:             return OK;
 5732:         } elsif ($context eq 'coauthor') {
 5733:             $r->internal_redirect('/adm/viewcoauthors');
 5734:             return OK;
 5735:         }
 5736:         $env{'user.error.msg'}=
 5737:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 5738:                                  "or view user status.";
 5739:         return HTTP_NOT_ACCEPTABLE;
 5740:     }
 5741: 
 5742:     &Apache::loncommon::content_type($r,'text/html');
 5743:     $r->send_http_header;
 5744: 
 5745:     my $showcredits;
 5746:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 5747:          ($context eq 'domain')) {
 5748:         my %domdefaults = 
 5749:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 5750:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 5751:             $showcredits = 1;
 5752:         }
 5753:     }
 5754: 
 5755:     # Main switch on form.action and form.state, as appropriate
 5756:     if (! exists($env{'form.action'})) {
 5757:         $args = {bread_crumbs => $brcrum,
 5758:                  bread_crumbs_component => $bread_crumbs_component}; 
 5759:         $r->print(&header(undef,$args));
 5760:         $r->print(&print_main_menu($permission,$context,$crstype));
 5761:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 5762:         my $helpitem = 'Course_Create_Class_List';
 5763:         if ($context eq 'author') {
 5764:             $helpitem = 'Author_Create_Coauthor_List';
 5765:         } elsif ($context eq 'domain') {
 5766:             $helpitem = 'Domain_Create_Users';
 5767:         }
 5768:         push(@{$brcrum},
 5769:               { href => '/adm/createuser?action=upload&state=',
 5770:                 text => 'Upload Users List',
 5771:                 help => $helpitem,
 5772:               });
 5773:         $bread_crumbs_component = 'Upload Users List';
 5774:         $args = {bread_crumbs           => $brcrum,
 5775:                  bread_crumbs_component => $bread_crumbs_component};
 5776:         $r->print(&header(undef,$args));
 5777:         $r->print('<form name="studentform" method="post" '.
 5778:                   'enctype="multipart/form-data" '.
 5779:                   ' action="/adm/createuser">'."\n");
 5780:         if (! exists($env{'form.state'})) {
 5781:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5782:         } elsif ($env{'form.state'} eq 'got_file') {
 5783:             my $result = 
 5784:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 5785:                                                                  $permission,
 5786:                                                                  $crstype,$showcredits);
 5787:             if ($result eq 'missingdata') {
 5788:                 delete($env{'form.state'});
 5789:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5790:             }
 5791:         } elsif ($env{'form.state'} eq 'enrolling') {
 5792:             if ($env{'form.datatoken'}) {
 5793:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 5794:                                                                     $permission,
 5795:                                                                     $showcredits);
 5796:                 if ($result eq 'missingdata') {
 5797:                     delete($env{'form.state'});
 5798:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5799:                 } elsif ($result eq 'invalidhome') {
 5800:                     $env{'form.state'} = 'got_file';
 5801:                     delete($env{'form.lcserver'});
 5802:                     my $result =
 5803:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 5804:                                                                          $crstype,$showcredits);
 5805:                     if ($result eq 'missingdata') {
 5806:                         delete($env{'form.state'});
 5807:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5808:                     }
 5809:                 }
 5810:             } else {
 5811:                 delete($env{'form.state'});
 5812:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5813:             }
 5814:         } else {
 5815:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5816:         }
 5817:         $r->print('</form>');
 5818:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 5819:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 5820:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 5821:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 5822:         my $phase = $env{'form.phase'};
 5823:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 5824: 	&Apache::loncreateuser::restore_prev_selections();
 5825: 	my $srch;
 5826: 	foreach my $item (@search) {
 5827: 	    $srch->{$item} = $env{'form.'.$item};
 5828: 	}
 5829:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 5830:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 5831:             if ($env{'form.phase'} eq 'createnewuser') {
 5832:                 my $response;
 5833:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 5834:                     my $response =
 5835:                         '<span class="LC_warning">'
 5836:                        .&mt('You must specify a valid username. Only the following are allowed:'
 5837:                            .' letters numbers - . @')
 5838:                        .'</span>';
 5839:                     $env{'form.phase'} = '';
 5840:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 5841:                                                $crstype,$brcrum,$permission);
 5842:                 } else {
 5843:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 5844:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 5845:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 5846:                                                   $srch,$response,$context,
 5847:                                                   $permission,$crstype,$brcrum,
 5848:                                                   $showcredits);
 5849:                 }
 5850:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 5851:                 my ($currstate,$response,$forcenewuser,$results) = 
 5852:                     &user_search_result($context,$srch);
 5853:                 if ($env{'form.currstate'} eq 'modify') {
 5854:                     $currstate = $env{'form.currstate'};
 5855:                 }
 5856:                 if ($currstate eq 'select') {
 5857:                     &print_user_selection_page($r,$response,$srch,$results,
 5858:                                                \@search,$context,undef,$crstype,
 5859:                                                $brcrum);
 5860:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 5861:                     my ($ccuname,$ccdomain,$uhome);
 5862:                     if (($srch->{'srchby'} eq 'uname') && 
 5863:                         ($srch->{'srchtype'} eq 'exact')) {
 5864:                         $ccuname = $srch->{'srchterm'};
 5865:                         $ccdomain= $srch->{'srchdomain'};
 5866:                     } else {
 5867:                         my @matchedunames = keys(%{$results});
 5868:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 5869:                     }
 5870:                     $ccuname =&LONCAPA::clean_username($ccuname);
 5871:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 5872:                     if ($env{'form.action'} eq 'accesslogs') {
 5873:                         my $uhome;
 5874:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 5875:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 5876:                         }
 5877:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 5878:                             $env{'form.phase'} = '';
 5879:                             undef($forcenewuser);
 5880:                             #if ($response) {
 5881:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 5882:                             #        $response .= '<br /><br />';
 5883:                             #    }
 5884:                             #}
 5885:                             &print_username_entry_form($r,$context,$response,$srch,
 5886:                                                        $forcenewuser,$crstype,$brcrum,
 5887:                                                        $permission);
 5888:                         } else {
 5889:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5890:                         }
 5891:                     } else {
 5892:                         if ($env{'form.forcenewuser'}) {
 5893:                             $response = '';
 5894:                         }
 5895:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 5896:                                                       $srch,$response,$context,
 5897:                                                       $permission,$crstype,$brcrum);
 5898:                     }
 5899:                 } elsif ($currstate eq 'query') {
 5900:                     &print_user_query_page($r,'createuser',$brcrum);
 5901:                 } else {
 5902:                     $env{'form.phase'} = '';
 5903:                     &print_username_entry_form($r,$context,$response,$srch,
 5904:                                                $forcenewuser,$crstype,$brcrum,
 5905:                                                $permission);
 5906:                 }
 5907:             } elsif ($env{'form.phase'} eq 'userpicked') {
 5908:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 5909:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 5910:                 if ($env{'form.action'} eq 'accesslogs') {
 5911:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5912:                 } else {
 5913:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 5914:                                                   $context,$permission,$crstype,
 5915:                                                   $brcrum);
 5916:                 }
 5917:             } elsif ($env{'form.action'} eq 'accesslogs') {
 5918:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 5919:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 5920:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5921:             }
 5922:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 5923:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 5924:         } else {
 5925:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 5926:                                        $brcrum,$permission);
 5927:         }
 5928:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 5929:         my $prefix;
 5930:         if ($env{'form.phase'} eq 'set_custom_roles') {
 5931:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 5932:         } else {
 5933:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5934:         }
 5935:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 5936:              ($permission->{'cusr'}) && 
 5937:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5938:         push(@{$brcrum},
 5939:                  {href => '/adm/createuser?action=processauthorreq',
 5940:                   text => 'Authoring Space requests',
 5941:                   help => 'Domain_Role_Approvals'});
 5942:         $bread_crumbs_component = 'Authoring requests';
 5943:         if ($env{'form.state'} eq 'done') {
 5944:             push(@{$brcrum},
 5945:                      {href => '/adm/createuser?action=authorreqqueue',
 5946:                       text => 'Result',
 5947:                       help => 'Domain_Role_Approvals'});
 5948:             $bread_crumbs_component = 'Authoring request result';
 5949:         }
 5950:         $args = { bread_crumbs           => $brcrum,
 5951:                   bread_crumbs_component => $bread_crumbs_component};
 5952:         my $js = &usernamerequest_javascript();
 5953:         $r->print(&header(&add_script($js),$args));
 5954:         if (!exists($env{'form.state'})) {
 5955:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 5956:                                                                             $env{'request.role.domain'}));
 5957:         } elsif ($env{'form.state'} eq 'done') {
 5958:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 5959:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 5960:                                                                          $env{'request.role.domain'}));
 5961:         }
 5962:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 5963:              ($permission->{'cusr'}) &&
 5964:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5965:         push(@{$brcrum},
 5966:                  {href => '/adm/createuser?action=processusernamereq',
 5967:                   text => 'LON-CAPA account requests',
 5968:                   help => 'Domain_Username_Approvals'});
 5969:         $bread_crumbs_component = 'Account requests';
 5970:         if ($env{'form.state'} eq 'done') {
 5971:             push(@{$brcrum},
 5972:                      {href => '/adm/createuser?action=usernamereqqueue',
 5973:                       text => 'Result',
 5974:                       help => 'Domain_Username_Approvals'});
 5975:             $bread_crumbs_component = 'LON-CAPA account request result';
 5976:         }
 5977:         $args = { bread_crumbs           => $brcrum,
 5978:                   bread_crumbs_component => $bread_crumbs_component};
 5979:         my $js = &usernamerequest_javascript();
 5980:         $r->print(&header(&add_script($js),$args));
 5981:         if (!exists($env{'form.state'})) {
 5982:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 5983:                                                                             $env{'request.role.domain'}));
 5984:         } elsif ($env{'form.state'} eq 'done') {
 5985:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 5986:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 5987:                                                                          $env{'request.role.domain'}));
 5988:         }
 5989:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 5990:              ($permission->{'cusr'})) {
 5991:         my $dom = $env{'form.domain'};
 5992:         my $uname = $env{'form.username'};
 5993:         my $warning;
 5994:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 5995:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 5996:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 5997:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 5998:                     if ($uhome eq 'no_host') {
 5999:                         my $queue = $env{'form.queue'};
 6000:                         my $reqkey = &escape($uname).'_'.$queue; 
 6001:                         my $namespace = 'usernamequeue';
 6002:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 6003:                         my %queued =
 6004:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 6005:                         unless ($queued{$reqkey}) {
 6006:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 6007:                         }
 6008:                     } else {
 6009:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 6010:                     }
 6011:                 } else {
 6012:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 6013:                 }
 6014:             } else {
 6015:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 6016:             }
 6017:         } else {
 6018:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 6019:         }
 6020:         my $args = { only_body => 1 };
 6021:         $r->print(&header(undef,$args).
 6022:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 6023:         if ($warning ne '') {
 6024:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 6025:         } else {
 6026:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 6027:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 6028:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6029:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6030:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 6031:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 6032:                         my %info =
 6033:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 6034:                         if (ref($info{$uname}) eq 'HASH') {
 6035:                             my $usertype = $info{$uname}{'inststatus'};
 6036:                             unless ($usertype) {
 6037:                                 $usertype = 'default';
 6038:                             }
 6039:                             my ($showstatus,$showemail,$pickstart);
 6040:                             my $numextras = 0;
 6041:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6042:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 6043:                                 if (ref($usertypes) eq 'HASH') {
 6044:                                     if ($usertypes->{$usertype}) {
 6045:                                         $showstatus = $usertypes->{$usertype};
 6046:                                     } else {
 6047:                                         $showstatus = $othertitle;
 6048:                                     }
 6049:                                     if ($showstatus) {
 6050:                                         $numextras ++;
 6051:                                     }
 6052:                                 }
 6053:                             }
 6054:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 6055:                                 $showemail = $info{$uname}{'email'};
 6056:                                 $numextras ++;
 6057:                             }
 6058:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 6059:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 6060:                                     $pickstart = 1;
 6061:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6062:                                     my ($num,$count);
 6063:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 6064:                                     $count += $numextras;
 6065:                                     foreach my $field (@{$infofields}) {
 6066:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 6067:                                         next unless ($infotitles->{$field});
 6068:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 6069:                                                   $info{$uname}{$field});
 6070:                                         $num ++;
 6071:                                         unless ($count == $num) {
 6072:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 6073:                                         }
 6074:                                     }
 6075:                                 }
 6076:                             }
 6077:                             if ($numextras) {
 6078:                                 unless ($pickstart) {
 6079:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6080:                                     $pickstart = 1;
 6081:                                 }
 6082:                                 if ($showemail) {
 6083:                                     my $closure = '';
 6084:                                     unless ($showstatus) {
 6085:                                         $closure = 1;
 6086:                                     }
 6087:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 6088:                                               $showemail.
 6089:                                               &Apache::lonhtmlcommon::row_closure($closure));
 6090:                                 }
 6091:                                 if ($showstatus) {
 6092:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 6093:                                               $showstatus.
 6094:                                               &Apache::lonhtmlcommon::row_closure(1));
 6095:                                 }
 6096:                             }
 6097:                             if ($pickstart) { 
 6098:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 6099:                             } else {
 6100:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 6101:                             }
 6102:                         } else {
 6103:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 6104:                         }
 6105:                     }
 6106:                 }
 6107:             }
 6108:         }
 6109:         $r->print(&close_popup_form());
 6110:     } elsif (($env{'form.action'} eq 'listusers') && 
 6111:              ($permission->{'view'} || $permission->{'cusr'})) {
 6112:         my $helpitem = 'Course_View_Class_List';
 6113:         if ($context eq 'author') {
 6114:             $helpitem = 'Author_View_Coauthor_List';
 6115:         } elsif ($context eq 'domain') {
 6116:             $helpitem = 'Domain_View_Users_List';
 6117:         }
 6118:         if ($env{'form.phase'} eq 'bulkchange') {
 6119:             push(@{$brcrum},
 6120:                     {href => '/adm/createuser?action=listusers',
 6121:                      text => "List Users"},
 6122:                     {href => "/adm/createuser",
 6123:                      text => "Result",
 6124:                      help => $helpitem});
 6125:             $bread_crumbs_component = 'Update Users';
 6126:             $args = {bread_crumbs           => $brcrum,
 6127:                      bread_crumbs_component => $bread_crumbs_component};
 6128:             $r->print(&header(undef,$args));
 6129:             my $setting = $env{'form.roletype'};
 6130:             my $choice = $env{'form.bulkaction'};
 6131:             if ($permission->{'cusr'}) {
 6132:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 6133:             } else {
 6134:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 6135:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 6136:             }
 6137:         } else {
 6138:             push(@{$brcrum},
 6139:                     {href => '/adm/createuser?action=listusers',
 6140:                      text => "List Users",
 6141:                      help => $helpitem});
 6142:             $bread_crumbs_component = 'List Users';
 6143:             $args = {bread_crumbs           => $brcrum,
 6144:                      bread_crumbs_component => $bread_crumbs_component};
 6145:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 6146:             my $formname = 'studentform';
 6147:             my $hidecall = "hide_searching();";
 6148:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 6149:                 ($env{'form.roletype'} eq 'community'))) {
 6150:                 if ($env{'form.roletype'} eq 'course') {
 6151:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 6152:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 6153:                                                                 $formname);
 6154:                 } elsif ($env{'form.roletype'} eq 'community') {
 6155:                     $cb_jscript = 
 6156:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 6157:                     my %elements = (
 6158:                                       coursepick => 'radio',
 6159:                                       coursetotal => 'text',
 6160:                                       courselist => 'text',
 6161:                                    );
 6162:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 6163:                 }
 6164:                 $jscript .= &verify_user_display($context)."\n".
 6165:                             &Apache::loncommon::check_uncheck_jscript();
 6166:                 my $js = &add_script($jscript).$cb_jscript;
 6167:                 my $loadcode = 
 6168:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 6169:                 if ($loadcode ne '') {
 6170:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 6171:                 } else {
 6172:                     $args->{add_entries} = {onload => $hidecall};
 6173:                 }
 6174:                 $r->print(&header($js,$args));
 6175:             } else {
 6176:                 $args->{add_entries} = {onload => $hidecall};
 6177:                 $jscript = &verify_user_display($context).
 6178:                            &Apache::loncommon::check_uncheck_jscript(); 
 6179:                 $r->print(&header(&add_script($jscript),$args));
 6180:             }
 6181:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 6182:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 6183:                          $showcredits);
 6184:         }
 6185:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 6186:         my $brtext;
 6187:         if ($crstype eq 'Community') {
 6188:             $brtext = 'Drop Members';
 6189:         } else {
 6190:             $brtext = 'Drop Students';
 6191:         }
 6192:         push(@{$brcrum},
 6193:                 {href => '/adm/createuser?action=drop',
 6194:                  text => $brtext,
 6195:                  help => 'Course_Drop_Student'});
 6196:         if ($env{'form.state'} eq 'done') {
 6197:             push(@{$brcrum},
 6198:                      {href=>'/adm/createuser?action=drop',
 6199:                       text=>"Result"});
 6200:         }
 6201:         $bread_crumbs_component = $brtext;
 6202:         $args = {bread_crumbs           => $brcrum,
 6203:                  bread_crumbs_component => $bread_crumbs_component}; 
 6204:         $r->print(&header(undef,$args));
 6205:         if (!exists($env{'form.state'})) {
 6206:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 6207:         } elsif ($env{'form.state'} eq 'done') {
 6208:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 6209:                                                     $env{'form.action'});
 6210:         }
 6211:     } elsif ($env{'form.action'} eq 'dateselect') {
 6212:         if ($permission->{'cusr'}) {
 6213:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6214:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 6215:                                                                    $crstype,$showcredits));
 6216:         } else {
 6217:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6218:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 6219:         }
 6220:     } elsif ($env{'form.action'} eq 'selfenroll') {
 6221:         my %currsettings;
 6222:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 6223:             %currsettings = (
 6224:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 6225:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 6226:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 6227:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 6228:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 6229:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 6230:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 6231:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 6232:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 6233:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 6234:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 6235:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 6236:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 6237:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 6238:             );
 6239:         }
 6240:         if ($permission->{selfenrolladmin}) {
 6241:             push(@{$brcrum},
 6242:                     {href => '/adm/createuser?action=selfenroll',
 6243:                      text => "Configure Self-enrollment",
 6244:                      help => 'Course_Self_Enrollment'});
 6245:             if (!exists($env{'form.state'})) {
 6246:                 $args = { bread_crumbs           => $brcrum,
 6247:                           bread_crumbs_component => 'Configure Self-enrollment'};
 6248:                 $r->print(&header(undef,$args));
 6249:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6250:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 6251:             } elsif ($env{'form.state'} eq 'done') {
 6252:                 push (@{$brcrum},
 6253:                           {href=>'/adm/createuser?action=selfenroll',
 6254:                            text=>"Result"});
 6255:                 $args = { bread_crumbs           => $brcrum,
 6256:                           bread_crumbs_component => 'Self-enrollment result'};
 6257:                 $r->print(&header(undef,$args));
 6258:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6259:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 6260:             }
 6261:         } elsif ($permission->{selfenrollview}) {
 6262:             push(@{$brcrum},
 6263:                     {href => '/adm/createuser?action=selfenroll',
 6264:                      text => "View Self-enrollment configuration",
 6265:                      help => 'Course_Self_Enrollment'});
 6266:             $args = { bread_crumbs           => $brcrum,
 6267:                       bread_crumbs_component => 'Self-enrollment Settings'};
 6268:             $r->print(&header(undef,$args));
 6269:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6270:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 6271:         } else {
 6272:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6273:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 6274:         }
 6275:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 6276:         if ($permission->{selfenrolladmin}) {
 6277:             push(@{$brcrum},
 6278:                      {href => '/adm/createuser?action=selfenrollqueue',
 6279:                       text => 'Enrollment requests',
 6280:                       help => 'Course_Approve_Selfenroll'});
 6281:             $bread_crumbs_component = 'Enrollment requests';
 6282:             if ($env{'form.state'} eq 'done') {
 6283:                 push(@{$brcrum},
 6284:                          {href => '/adm/createuser?action=selfenrollqueue',
 6285:                           text => 'Result',
 6286:                           help => 'Course_Approve_Selfenroll'});
 6287:                 $bread_crumbs_component = 'Enrollment result';
 6288:             }
 6289:             $args = { bread_crumbs           => $brcrum,
 6290:                       bread_crumbs_component => $bread_crumbs_component};
 6291:             $r->print(&header(undef,$args));
 6292:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6293:             if (!exists($env{'form.state'})) {
 6294:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 6295:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 6296:                                                                                 $cdom,$cnum));
 6297:             } elsif ($env{'form.state'} eq 'done') {
 6298:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 6299:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 6300:                               $cdom,$cnum,$coursedesc));
 6301:             }
 6302:         } else {
 6303:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6304:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 6305:         }
 6306:     } elsif ($env{'form.action'} eq 'changelogs') {
 6307:         if ($permission->{cusr} || $permission->{view}) {
 6308:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 6309:         } else {
 6310:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6311:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 6312:         }
 6313:     } elsif ($env{'form.action'} eq 'helpdesk') {
 6314:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6315:             ($permission->{'cusr'} || $permission->{'view'})) {
 6316:             if ($env{'form.state'} eq 'process') {
 6317:                 if ($permission->{'owner'}) {
 6318:                     &update_helpdeskaccess($r,$permission,$brcrum);
 6319:                 } else {
 6320:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 6321:                 }
 6322:             } else {
 6323:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 6324:             }
 6325:         } else {
 6326:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6327:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 6328:         }
 6329:     } elsif ($env{'form.action'} eq 'rolerequests') {
 6330:         if ($permission->{cusr} || $permission->{view}) {
 6331:             &print_queued_roles($r,$context,$permission,$brcrum);
 6332:         }
 6333:     } elsif ($env{'form.action'} eq 'queuedroles') {
 6334:         if (($permission->{cusr}) && ($context eq 'domain')) {
 6335:             if (&show_role_requests($context,$env{'request.role.domain'})) {
 6336:                 if ($env{'form.state'} eq 'done') {
 6337:                     &process_pendingroles($r,$context,$permission,$brcrum);
 6338:                 } else {
 6339:                     &print_pendingroles($r,$context,$permission,$brcrum);
 6340:                 }
 6341:             } else {
 6342:                 $r->print(&header(undef,{'no_nav_bar' => 1}).
 6343:                           '<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>');
 6344:             }
 6345:         } else {
 6346:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6347:                      '<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>');
 6348:         }
 6349:     } elsif ($env{'form.action'} eq 'camanagers') {
 6350:         if (($permission->{cusr}) && ($context eq 'author')) {
 6351:             push(@{$brcrum},
 6352:                      {href => '/adm/createuser?action=camanagers',
 6353:                       text => 'Co-author Managers',
 6354:                       help => 'Author_Manage_Coauthors'});
 6355:             if ($env{'form.state'} eq 'process') {
 6356:                 push(@{$brcrum},
 6357:                          {href => '/adm/createuser?action=camanagers',
 6358:                           text => 'Result',
 6359:                           help => 'Author_Manage_Coauthors'});
 6360:             }
 6361:             $args = { bread_crumbs           => $brcrum };
 6362:             $r->print(&header(undef,$args));
 6363:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6364:             if (!exists($env{'form.state'})) {
 6365:                 $r->print('<h3>'.&mt('Co-author Management').'</h3>'."\n".
 6366:                           &display_coauthor_managers($permission));
 6367:             } elsif ($env{'form.state'} eq 'process') {
 6368:                 $r->print('<h3>'.&mt('Co-author Management Update Result').'</h3>'."\n".
 6369:                           &update_coauthor_managers($permission));
 6370:             }
 6371:         }
 6372:     } elsif (($env{'form.action'} eq 'calist') && ($context eq 'author')) {
 6373:         if ($permission->{'cusr'}) {
 6374:             my ($role,$audom,$auname,$canview,$canedit) =
 6375:                 &Apache::lonviewcoauthors::get_allowable();
 6376:             if (($canedit) && ($env{'form.forceedit'})) {
 6377:                 &Apache::lonviewcoauthors::get_editor_crumbs($brcrum,'/adm/createuser');
 6378:                 my $args = { 'bread_crumbs' => $brcrum };
 6379:                 $r->print(&Apache::loncommon::start_page('Configure co-author listing',undef,
 6380:                                                          $args).
 6381:                           &Apache::lonviewcoauthors::edit_settings($audom,$auname,$role,
 6382:                                                                    '/adm/createuser'));
 6383:             } else {
 6384:                 push(@{$brcrum},
 6385:                        {href => '/adm/createuser?action=calist',
 6386:                         text => 'Coauthor-viewable list',
 6387:                         help => 'Author_List_Coauthors'});
 6388:                 my $args = { 'bread_crumbs' => $brcrum };
 6389:                 $r->print(&Apache::loncommon::start_page('Coauthor-viewable list',undef,
 6390:                                                          $args));
 6391:                 my %viewsettings =
 6392:                     &Apache::lonviewcoauthors::retrieve_view_settings($auname,$audom,$role);
 6393:                 if ($viewsettings{'show'} eq 'none') {
 6394:                     $r->print('<h3>'.&mt('Coauthor-viewable listing').'</h3>'.
 6395:                               '<p class="LC_info">'.
 6396:                               &mt('Listing of co-authors not enabled for this Authoring Space').
 6397:                               '</p>');
 6398:                 } else {
 6399:                     &Apache::lonviewcoauthors::print_coauthors($r,$auname,$audom,$role,
 6400:                                                                '/adm/createuser',\%viewsettings);
 6401:                 }
 6402:             }
 6403:         } else {
 6404:             $r->internal_redirect('/adm/viewcoauthors');
 6405:             return OK;
 6406:         }
 6407:     } else {
 6408:         $bread_crumbs_component = 'User Management';
 6409:         $args = { bread_crumbs           => $brcrum,
 6410:                   bread_crumbs_component => $bread_crumbs_component};
 6411:         $r->print(&header(undef,$args));
 6412:         $r->print(&print_main_menu($permission,$context,$crstype));
 6413:     }
 6414:     $r->print(&Apache::loncommon::end_page());
 6415:     return OK;
 6416: }
 6417: 
 6418: sub header {
 6419:     my ($jscript,$args) = @_;
 6420:     my $start_page;
 6421:     if (ref($args) eq 'HASH') {
 6422:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 6423:     } else {
 6424:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 6425:     }
 6426:     return $start_page;
 6427: }
 6428: 
 6429: sub add_script {
 6430:     my ($js) = @_;
 6431:     return '<script type="text/javascript">'."\n"
 6432:           .'// <![CDATA['."\n"
 6433:           .$js."\n"
 6434:           .'// ]]>'."\n"
 6435:           .'</script>'."\n";
 6436: }
 6437: 
 6438: sub usernamerequest_javascript {
 6439:     my $js = <<ENDJS;
 6440: 
 6441: function openusernamereqdisplay(dom,uname,queue) {
 6442:     var url = '/adm/createuser?action=displayuserreq';
 6443:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 6444:     var title = 'Account_Request_Browser';
 6445:     var options = 'scrollbars=1,resizable=1,menubar=0';
 6446:     options += ',width=700,height=600';
 6447:     var stdeditbrowser = open(url,title,options,'1');
 6448:     stdeditbrowser.focus();
 6449:     return;
 6450: }
 6451:  
 6452: ENDJS
 6453: }
 6454: 
 6455: sub close_popup_form {
 6456:     my $close= &mt('Close Window');
 6457:     return << "END";
 6458: <p><form name="displayreq" action="" method="post">
 6459: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 6460: </form></p>
 6461: END
 6462: }
 6463: 
 6464: sub verify_user_display {
 6465:     my ($context) = @_;
 6466:     my %lt = &Apache::lonlocal::texthash (
 6467:         course    => 'course(s): description, section(s), status',
 6468:         community => 'community(s): description, section(s), status',
 6469:         author    => 'author',
 6470:     );
 6471:     my $photos;
 6472:     if (($context eq 'course') && $env{'request.course.id'}) {
 6473:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 6474:     }
 6475:     my $output = <<"END";
 6476: 
 6477: function hide_searching() {
 6478:     if (document.getElementById('searching')) {
 6479:         document.getElementById('searching').style.display = 'none';
 6480:     }
 6481:     return;
 6482: }
 6483: 
 6484: function display_update() {
 6485:     document.studentform.action.value = 'listusers';
 6486:     document.studentform.phase.value = 'display';
 6487:     document.studentform.submit();
 6488: }
 6489: 
 6490: function updateCols(caller) {
 6491:     var context = '$context';
 6492:     var photos = '$photos';
 6493:     if (caller == 'Status') {
 6494:         if ((context == 'domain') && 
 6495:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6496:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 6497:             document.getElementById('showcolstatus').checked = false;
 6498:             document.getElementById('showcolstatus').disabled = 'disabled';
 6499:             document.getElementById('showcolstart').checked = false;
 6500:             document.getElementById('showcolend').checked = false;
 6501:         } else {
 6502:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6503:                 document.getElementById('showcolstatus').checked = true;
 6504:                 document.getElementById('showcolstatus').disabled = '';
 6505:                 document.getElementById('showcolstart').checked = true;
 6506:                 document.getElementById('showcolend').checked = true;
 6507:             } else {
 6508:                 document.getElementById('showcolstatus').checked = false;
 6509:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6510:                 document.getElementById('showcolstart').checked = false;
 6511:                 document.getElementById('showcolend').checked = false;
 6512:             }
 6513:             if (context == 'author') {
 6514:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Expired') {
 6515:                     document.getElementById('showcolmanager').checked = false;
 6516:                     document.getElementById('showcolmanager').disabled = 'disabled';
 6517:                 } else if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value != 'aa') {
 6518:                     document.getElementById('showcolmanager').checked = true;
 6519:                     document.getElementById('showcolmanager').disabled = '';
 6520:                 }
 6521:             }
 6522:         }
 6523:     }
 6524:     if (caller == 'output') {
 6525:         if (photos == 1) {
 6526:             if (document.getElementById('showcolphoto')) {
 6527:                 var photoitem = document.getElementById('showcolphoto');
 6528:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 6529:                     photoitem.checked = true;
 6530:                     photoitem.disabled = '';
 6531:                 } else {
 6532:                     photoitem.checked = false;
 6533:                     photoitem.disabled = 'disabled';
 6534:                 }
 6535:             }
 6536:         }
 6537:     }
 6538:     if (caller == 'showrole') {
 6539:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 6540:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 6541:             document.getElementById('showcolrole').checked = true;
 6542:             document.getElementById('showcolrole').disabled = '';
 6543:         } else {
 6544:             document.getElementById('showcolrole').checked = false;
 6545:             document.getElementById('showcolrole').disabled = 'disabled';
 6546:         }
 6547:         if (context == 'domain') {
 6548:             var quotausageshow = 0;
 6549:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6550:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 6551:                 document.getElementById('showcolstatus').checked = false;
 6552:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6553:                 document.getElementById('showcolstart').checked = false;
 6554:                 document.getElementById('showcolend').checked = false;
 6555:             } else {
 6556:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6557:                     document.getElementById('showcolstatus').checked = true;
 6558:                     document.getElementById('showcolstatus').disabled = '';
 6559:                     document.getElementById('showcolstart').checked = true;
 6560:                     document.getElementById('showcolend').checked = true;
 6561:                 }
 6562:             }
 6563:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 6564:                 document.getElementById('showcolextent').disabled = 'disabled';
 6565:                 document.getElementById('showcolextent').checked = 'false';
 6566:                 document.getElementById('showextent').style.display='none';
 6567:                 document.getElementById('showcoltextextent').innerHTML = '';
 6568:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 6569:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 6570:                     if (document.getElementById('showcolauthorusage')) {
 6571:                         document.getElementById('showcolauthorusage').disabled = '';
 6572:                     }
 6573:                     if (document.getElementById('showcolauthorquota')) {
 6574:                         document.getElementById('showcolauthorquota').disabled = '';
 6575:                     }
 6576:                     quotausageshow = 1;
 6577:                 }
 6578:             } else {
 6579:                 document.getElementById('showextent').style.display='block';
 6580:                 document.getElementById('showextent').style.textAlign='left';
 6581:                 document.getElementById('showextent').style.textFace='normal';
 6582:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 6583:                     document.getElementById('showcolextent').disabled = '';
 6584:                     document.getElementById('showcolextent').checked = 'true';
 6585:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 6586:                 } else {
 6587:                     document.getElementById('showcolextent').disabled = '';
 6588:                     document.getElementById('showcolextent').checked = 'true';
 6589:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 6590:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 6591:                     } else {
 6592:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 6593:                     }
 6594:                 }
 6595:             }
 6596:             if (quotausageshow == 0)  {
 6597:                 if (document.getElementById('showcolauthorusage')) {
 6598:                     document.getElementById('showcolauthorusage').checked = false;
 6599:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 6600:                 }
 6601:                 if (document.getElementById('showcolauthorquota')) {
 6602:                     document.getElementById('showcolauthorquota').checked = false;
 6603:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 6604:                 }
 6605:             }
 6606:         }
 6607:         if (context == 'author') {
 6608:             if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'aa') {
 6609:                 document.getElementById('showcolmanager').checked = false;
 6610:                 document.getElementById('showcolmanager').disabled = 'disabled';
 6611:             } else if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value != 'Expired') {
 6612:                 document.getElementById('showcolmanager').checked = true;
 6613:                 document.getElementById('showcolmanager').disabled = '';
 6614:             }
 6615:         }
 6616:     }
 6617:     return;
 6618: }
 6619: 
 6620: END
 6621:     return $output;
 6622: 
 6623: }
 6624: 
 6625: ###############################################################
 6626: ###############################################################
 6627: #  Menu Phase One
 6628: sub print_main_menu {
 6629:     my ($permission,$context,$crstype) = @_;
 6630:     my $linkcontext = $context;
 6631:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 6632:     if (($context eq 'course') && ($crstype eq 'Community')) {
 6633:         $linkcontext = lc($crstype);
 6634:         $stuterm = 'Members';
 6635:     }
 6636:     my %links = (
 6637:                 domain => {
 6638:                             upload     => 'Upload a File of Users',
 6639:                             singleuser => 'Add/Modify a User',
 6640:                             listusers  => 'Manage Users',
 6641:                             },
 6642:                 author => {
 6643:                             upload     => 'Upload a File of Co-authors',
 6644:                             singleuser => 'Add/Modify a Co-author',
 6645:                             listusers  => 'Manage Co-authors',
 6646:                             },
 6647:                 course => {
 6648:                             upload     => 'Upload a File of Course Users',
 6649:                             singleuser => 'Add/Modify a Course User',
 6650:                             listusers  => 'List and Modify Multiple Course Users',
 6651:                             },
 6652:                 community => {
 6653:                             upload     => 'Upload a File of Community Users',
 6654:                             singleuser => 'Add/Modify a Community User',
 6655:                             listusers  => 'List and Modify Multiple Community Users',
 6656:                            },
 6657:                 );
 6658:      my %linktitles = (
 6659:                 domain => {
 6660:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 6661:                             listusers  => 'Show and manage users in this domain.',
 6662:                             },
 6663:                 author => {
 6664:                             singleuser => 'Add a user with a co- or assistant author role.',
 6665:                             listusers  => 'Show and manage co- or assistant authors.',
 6666:                             },
 6667:                 course => {
 6668:                             singleuser => 'Add a user with a certain role to this course.',
 6669:                             listusers  => 'Show and manage users in this course.',
 6670:                             },
 6671:                 community => {
 6672:                             singleuser => 'Add a user with a certain role to this community.',
 6673:                             listusers  => 'Show and manage users in this community.',
 6674:                            },
 6675:                 );
 6676: 
 6677:   if ($linkcontext eq 'domain') {
 6678:       unless ($permission->{'cusr'}) {
 6679:           $links{'domain'}{'singleuser'} = 'View a User';
 6680:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 6681:       }
 6682:   } elsif ($linkcontext eq 'course') {
 6683:       unless ($permission->{'cusr'}) {
 6684:           $links{'course'}{'singleuser'} = 'View a Course User';
 6685:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 6686:           $links{'course'}{'listusers'} = 'List Course Users';
 6687:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 6688:       }
 6689:   } elsif ($linkcontext eq 'community') {
 6690:       unless ($permission->{'cusr'}) {
 6691:           $links{'community'}{'singleuser'} = 'View a Community User';
 6692:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 6693:           $links{'community'}{'listusers'} = 'List Community Users';
 6694:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 6695:       }
 6696:   }
 6697:   my @menu = ( {categorytitle => 'Single Users', 
 6698:          items =>
 6699:          [
 6700:             {
 6701:              linktext => $links{$linkcontext}{'singleuser'},
 6702:              icon => 'edit-redo.png',
 6703:              #help => 'Course_Change_Privileges',
 6704:              url => '/adm/createuser?action=singleuser',
 6705:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6706:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 6707:             },
 6708:          ]},
 6709: 
 6710:          {categorytitle => 'Multiple Users',
 6711:          items => 
 6712:          [
 6713:             {
 6714:              linktext => $links{$linkcontext}{'upload'},
 6715:              icon => 'uplusr.png',
 6716:              #help => 'Course_Create_Class_List',
 6717:              url => '/adm/createuser?action=upload',
 6718:              permission => $permission->{'cusr'},
 6719:              linktitle => 'Upload a CSV or a text file containing users.',
 6720:             },
 6721:             {
 6722:              linktext => $links{$linkcontext}{'listusers'},
 6723:              icon => 'mngcu.png',
 6724:              #help => 'Course_View_Class_List',
 6725:              url => '/adm/createuser?action=listusers',
 6726:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6727:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 6728:             },
 6729: 
 6730:          ]},
 6731: 
 6732:          {categorytitle => 'Administration',
 6733:          items => [ ]},
 6734:        );
 6735: 
 6736:     if ($context eq 'domain'){
 6737:         push(@{  $menu[0]->{items} }, # Single Users
 6738:             {
 6739:              linktext => 'User Access Log',
 6740:              icon => 'document-properties.png',
 6741:              #help => 'Domain_User_Access_Logs',
 6742:              url => '/adm/createuser?action=accesslogs',
 6743:              permission => $permission->{'activity'},
 6744:              linktitle => 'View user access log.',
 6745:             }
 6746:         );
 6747:         
 6748:         push(@{ $menu[2]->{items} }, #Category: Administration
 6749:             {
 6750:              linktext => 'Custom Roles',
 6751:              icon => 'emblem-photos.png',
 6752:              #help => 'Course_Editing_Custom_Roles',
 6753:              url => '/adm/createuser?action=custom',
 6754:              permission => $permission->{'custom'},
 6755:              linktitle => 'Configure a custom role.',
 6756:             },
 6757:             {
 6758:              linktext => 'Authoring Space Requests',
 6759:              icon => 'selfenrl-queue.png',
 6760:              #help => 'Domain_Role_Approvals',
 6761:              url => '/adm/createuser?action=processauthorreq',
 6762:              permission => $permission->{'cusr'},
 6763:              linktitle => 'Approve or reject author role requests',
 6764:             },
 6765:             {
 6766:              linktext => 'LON-CAPA Account Requests',
 6767:              icon => 'list-add.png',
 6768:              #help => 'Domain_Username_Approvals',
 6769:              url => '/adm/createuser?action=processusernamereq',
 6770:              permission => $permission->{'cusr'},
 6771:              linktitle => 'Approve or reject LON-CAPA account requests',
 6772:             },
 6773:             {
 6774:              linktext => 'Change Log',
 6775:              icon => 'document-properties.png',
 6776:              #help => 'Course_User_Logs',
 6777:              url => '/adm/createuser?action=changelogs',
 6778:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 6779:              linktitle => 'View change log.',
 6780:             },
 6781:         );
 6782:         
 6783:     }elsif ($context eq 'course'){
 6784:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 6785: 
 6786:         my %linktext = (
 6787:                          'Course'    => {
 6788:                                           single => 'Add/Modify a Student', 
 6789:                                           drop   => 'Drop Students',
 6790:                                           groups => 'Course Groups',
 6791:                                         },
 6792:                          'Community' => {
 6793:                                           single => 'Add/Modify a Member', 
 6794:                                           drop   => 'Drop Members',
 6795:                                           groups => 'Community Groups',
 6796:                                         },
 6797:                        );
 6798:         $linktext{'Placement'} = $linktext{'Course'};
 6799: 
 6800:         my %linktitle = (
 6801:             'Course' => {
 6802:                   single => 'Add a user with the role of student to this course',
 6803:                   drop   => 'Remove a student from this course.',
 6804:                   groups => 'Manage course groups',
 6805:                         },
 6806:             'Community' => {
 6807:                   single => 'Add a user with the role of member to this community',
 6808:                   drop   => 'Remove a member from this community.',
 6809:                   groups => 'Manage community groups',
 6810:                            },
 6811:         );
 6812: 
 6813:         $linktitle{'Placement'} = $linktitle{'Course'};
 6814: 
 6815:         push(@{ $menu[0]->{items} }, #Category: Single Users
 6816:             {   
 6817:              linktext => $linktext{$crstype}{'single'},
 6818:              #help => 'Course_Add_Student',
 6819:              icon => 'list-add.png',
 6820:              url => '/adm/createuser?action=singlestudent',
 6821:              permission => $permission->{'cusr'},
 6822:              linktitle => $linktitle{$crstype}{'single'},
 6823:             },
 6824:         );
 6825:         
 6826:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 6827:             {
 6828:              linktext => $linktext{$crstype}{'drop'},
 6829:              icon => 'edit-undo.png',
 6830:              #help => 'Course_Drop_Student',
 6831:              url => '/adm/createuser?action=drop',
 6832:              permission => $permission->{'cusr'},
 6833:              linktitle => $linktitle{$crstype}{'drop'},
 6834:             },
 6835:         );
 6836:         push(@{ $menu[2]->{items} }, #Category: Administration
 6837:             {
 6838:              linktext => 'Helpdesk Access',
 6839:              icon => 'helpdesk-access.png',
 6840:              #help => 'Course_Helpdesk_Access',
 6841:              url => '/adm/createuser?action=helpdesk',
 6842:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6843:                             ($permission->{'view'} || $permission->{'cusr'})),
 6844:              linktitle => 'Helpdesk access options',
 6845:             },
 6846:             {
 6847:              linktext => 'Custom Roles',
 6848:              icon => 'emblem-photos.png',
 6849:              #help => 'Course_Editing_Custom_Roles',
 6850:              url => '/adm/createuser?action=custom',
 6851:              permission => $permission->{'custom'},
 6852:              linktitle => 'Configure a custom role.',
 6853:             },
 6854:             {
 6855:              linktext => $linktext{$crstype}{'groups'},
 6856:              icon => 'grps.png',
 6857:              #help => 'Course_Manage_Group',
 6858:              url => '/adm/coursegroups?refpage=cusr',
 6859:              permission => $permission->{'grp_manage'},
 6860:              linktitle => $linktitle{$crstype}{'groups'},
 6861:             },
 6862:             {
 6863:              linktext => 'Change Log',
 6864:              icon => 'document-properties.png',
 6865:              #help => 'Course_User_Logs',
 6866:              url => '/adm/createuser?action=changelogs',
 6867:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6868:              linktitle => 'View change log.',
 6869:             },
 6870:         );
 6871:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 6872:             push(@{ $menu[2]->{items} },
 6873:                     {
 6874:                      linktext => 'Enrollment Requests',
 6875:                      icon => 'selfenrl-queue.png',
 6876:                      #help => 'Course_Approve_Selfenroll',
 6877:                      url => '/adm/createuser?action=selfenrollqueue',
 6878:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6879:                      linktitle =>'Approve or reject enrollment requests.',
 6880:                     },
 6881:             );
 6882:         }
 6883:         
 6884:         if (!exists($permission->{'cusr_section'})){
 6885:             if ($crstype ne 'Community') {
 6886:                 push(@{ $menu[2]->{items} },
 6887:                     {
 6888:                      linktext => 'Automated Enrollment',
 6889:                      icon => 'roles.png',
 6890:                      #help => 'Course_Automated_Enrollment',
 6891:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 6892:                                          && (($permission->{'cusr'}) ||
 6893:                                              ($permission->{'view'}))),
 6894:                      url  => '/adm/populate',
 6895:                      linktitle => 'Automated enrollment manager.',
 6896:                     }
 6897:                 );
 6898:             }
 6899:             push(@{ $menu[2]->{items} }, 
 6900:                 {
 6901:                  linktext => 'User Self-Enrollment',
 6902:                  icon => 'self_enroll.png',
 6903:                  #help => 'Course_Self_Enrollment',
 6904:                  url => '/adm/createuser?action=selfenroll',
 6905:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6906:                  linktitle => 'Configure user self-enrollment.',
 6907:                 },
 6908:             );
 6909:         }
 6910:     } elsif ($context eq 'author') {
 6911:         push(@{ $menu[2]->{items} }, #Category: Administration
 6912:             {
 6913:              linktext => 'Change Log',
 6914:              icon => 'document-properties.png',
 6915:              #help => 'Course_User_Logs',
 6916:              url => '/adm/createuser?action=changelogs',
 6917:              permission => $permission->{'cusr'},
 6918:              linktitle => 'View change log.',
 6919:             },
 6920:             {
 6921:              linktext => 'Co-author Managers',
 6922:              icon => 'camanager.png',
 6923:              #help => 'Coauthor_Management',
 6924:              url => '/adm/createuser?action=camanagers',
 6925:              permission => $permission->{'author'},
 6926:              linktitle => 'Assign/Revoke right to manage co-author roles',
 6927:             },
 6928:             {
 6929:              linktext => 'Configure Co-author Listing',
 6930:              icon => 'coauthors.png',
 6931:              #help => 'Coauthor_Settings',
 6932:              url => '/adm/createuser?action=calist&forceedit=1',
 6933:              permission => ($permission->{'cusr'}),
 6934:              linktitle => 'Set availability of coauthor-viewable user listing',
 6935:             },
 6936:         );
 6937:     }
 6938:     push(@{ $menu[2]->{items} },
 6939:         {
 6940:          linktext => 'Role Requests (other domains)',
 6941:          icon => 'edit-find.png',
 6942:          #help => 'Role_Requests',
 6943:          url => '/adm/createuser?action=rolerequests',
 6944:          permission => $permission->{'cusr'},
 6945:          linktitle => 'Role requests for users in other domains',
 6946:         },
 6947:     );
 6948:     if (&show_role_requests($context,$env{'request.role.domain'})) {
 6949:         push(@{ $menu[2]->{items} },
 6950:             {
 6951:              linktext => 'Queued Role Assignments (this domain)',
 6952:              icon => 'edit-find.png',
 6953:              #help => 'Role_Approvals',
 6954:              url => '/adm/createuser?action=queuedroles',
 6955:              permission => $permission->{'cusr'},
 6956:              linktitle => "Role requests for this domain's users",
 6957:             },
 6958:         );
 6959:     }
 6960:     return Apache::lonhtmlcommon::generate_menu(@menu);
 6961: #               { text => 'View Log-in History',
 6962: #                 help => 'Course_User_Logins',
 6963: #                 action => 'logins',
 6964: #                 permission => $permission->{'cusr'},
 6965: #               });
 6966: }
 6967: 
 6968: sub restore_prev_selections {
 6969:     my %saveable_parameters = ('srchby'   => 'scalar',
 6970: 			       'srchin'   => 'scalar',
 6971: 			       'srchtype' => 'scalar',
 6972: 			       );
 6973:     &Apache::loncommon::store_settings('user','user_picker',
 6974: 				       \%saveable_parameters);
 6975:     &Apache::loncommon::restore_settings('user','user_picker',
 6976: 					 \%saveable_parameters);
 6977: }
 6978: 
 6979: sub print_selfenroll_menu {
 6980:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 6981:     my $crstype = &Apache::loncommon::course_type();
 6982:     my $formname = 'selfenroll';
 6983:     my $nolink = 1;
 6984:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 6985:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 6986:     my $setsec_js = 
 6987:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 6988:     my %alerts = &Apache::lonlocal::texthash(
 6989:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 6990:         butn => 'but no user types have been checked.',
 6991:         wilf => "Please uncheck 'activate' or check at least one type.",
 6992:     );
 6993:     my $disabled;
 6994:     if ($readonly) {
 6995:        $disabled = ' disabled="disabled"';
 6996:     }
 6997:     &js_escape(\%alerts);
 6998:     my $selfenroll_js = <<"ENDSCRIPT";
 6999: function update_types(caller,num) {
 7000:     var delidx = getIndexByName('selfenroll_delete');
 7001:     var actidx = getIndexByName('selfenroll_activate');
 7002:     if (caller == 'selfenroll_all') {
 7003:         var selall;
 7004:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7005:             if (document.$formname.selfenroll_all[i].checked) {
 7006:                 selall = document.$formname.selfenroll_all[i].value;
 7007:             }
 7008:         }
 7009:         if (selall == 1) {
 7010:             if (delidx != -1) {
 7011:                 if (document.$formname.selfenroll_delete.length) {
 7012:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7013:                         document.$formname.selfenroll_delete[j].checked = true;
 7014:                     }
 7015:                 } else {
 7016:                     document.$formname.elements[delidx].checked = true;
 7017:                 }
 7018:             }
 7019:             if (actidx != -1) {
 7020:                 if (document.$formname.selfenroll_activate.length) {
 7021:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7022:                         document.$formname.selfenroll_activate[j].checked = false;
 7023:                     }
 7024:                 } else {
 7025:                     document.$formname.elements[actidx].checked = false;
 7026:                 }
 7027:             }
 7028:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 7029:         }
 7030:     }
 7031:     if (caller == 'selfenroll_activate') {
 7032:         if (document.$formname.selfenroll_activate.length) {
 7033:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7034:                 if (document.$formname.selfenroll_activate[j].value == num) {
 7035:                     if (document.$formname.selfenroll_activate[j].checked) {
 7036:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7037:                             if (document.$formname.selfenroll_all[i].value == '1') {
 7038:                                 document.$formname.selfenroll_all[i].checked = false;
 7039:                             }
 7040:                             if (document.$formname.selfenroll_all[i].value == '0') {
 7041:                                 document.$formname.selfenroll_all[i].checked = true;
 7042:                             }
 7043:                         }
 7044:                     }
 7045:                 }
 7046:             }
 7047:         } else {
 7048:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7049:                 if (document.$formname.selfenroll_all[i].value == '1') {
 7050:                     document.$formname.selfenroll_all[i].checked = false;
 7051:                 }
 7052:                 if (document.$formname.selfenroll_all[i].value == '0') {
 7053:                     document.$formname.selfenroll_all[i].checked = true;
 7054:                 }
 7055:             }
 7056:         }
 7057:     }
 7058:     if (caller == 'selfenroll_delete') {
 7059:         if (document.$formname.selfenroll_delete.length) {
 7060:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7061:                 if (document.$formname.selfenroll_delete[j].value == num) {
 7062:                     if (document.$formname.selfenroll_delete[j].checked) {
 7063:                         var delindex = getIndexByName('selfenroll_types_'+num);
 7064:                         if (delindex != -1) { 
 7065:                             if (document.$formname.elements[delindex].length) {
 7066:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7067:                                     document.$formname.elements[delindex][k].checked = false;
 7068:                                 }
 7069:                             } else {
 7070:                                 document.$formname.elements[delindex].checked = false;
 7071:                             }
 7072:                         }
 7073:                     }
 7074:                 }
 7075:             }
 7076:         } else {
 7077:             if (document.$formname.selfenroll_delete.checked) {
 7078:                 var delindex = getIndexByName('selfenroll_types_'+num);
 7079:                 if (delindex != -1) {
 7080:                     if (document.$formname.elements[delindex].length) {
 7081:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7082:                             document.$formname.elements[delindex][k].checked = false;
 7083:                         }
 7084:                     } else {
 7085:                         document.$formname.elements[delindex].checked = false;
 7086:                     }
 7087:                 }
 7088:             }
 7089:         }
 7090:     }
 7091:     return;
 7092: }
 7093: 
 7094: function validate_types(form) {
 7095:     var needaction = new Array();
 7096:     var countfail = 0;
 7097:     var actidx = getIndexByName('selfenroll_activate');
 7098:     if (actidx != -1) {
 7099:         if (document.$formname.selfenroll_activate.length) {
 7100:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7101:                 var num = document.$formname.selfenroll_activate[j].value;
 7102:                 if (document.$formname.selfenroll_activate[j].checked) {
 7103:                     countfail = check_types(num,countfail,needaction)
 7104:                 }
 7105:             }
 7106:         } else {
 7107:             if (document.$formname.selfenroll_activate.checked) {
 7108:                 var num = document.$formname.selfenroll_activate.value;
 7109:                 countfail = check_types(num,countfail,needaction)
 7110:             }
 7111:         }
 7112:     }
 7113:     if (countfail > 0) {
 7114:         var msg = "$alerts{'acto'}\\n";
 7115:         var loopend = needaction.length -1;
 7116:         if (loopend > 0) {
 7117:             for (var m=0; m<loopend; m++) {
 7118:                 msg += needaction[m]+", ";
 7119:             }
 7120:         }
 7121:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 7122:         alert(msg);
 7123:         return; 
 7124:     }
 7125:     setSections(form);
 7126: }
 7127: 
 7128: function check_types(num,countfail,needaction) {
 7129:     var boxname = 'selfenroll_types_'+num;
 7130:     var typeidx = getIndexByName(boxname);
 7131:     var count = 0;
 7132:     if (typeidx != -1) {
 7133:         if (document.$formname.elements[boxname].length) {
 7134:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 7135:                 if (document.$formname.elements[boxname][k].checked) {
 7136:                     count ++;
 7137:                 }
 7138:             }
 7139:         } else {
 7140:             if (document.$formname.elements[typeidx].checked) {
 7141:                 count ++;
 7142:             }
 7143:         }
 7144:         if (count == 0) {
 7145:             var domidx = getIndexByName('selfenroll_dom_'+num);
 7146:             if (domidx != -1) {
 7147:                 var domname = document.$formname.elements[domidx].value;
 7148:                 needaction[countfail] = domname;
 7149:                 countfail ++;
 7150:             }
 7151:         }
 7152:     }
 7153:     return countfail;
 7154: }
 7155: 
 7156: function toggleNotify() {
 7157:     var selfenrollApproval = 0;
 7158:     if (document.$formname.selfenroll_approval.length) {
 7159:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 7160:             if (document.$formname.selfenroll_approval[i].checked) {
 7161:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 7162:                 break;        
 7163:             }
 7164:         }
 7165:     }
 7166:     if (document.getElementById('notified')) {
 7167:         if (selfenrollApproval == 0) {
 7168:             document.getElementById('notified').style.display='none';
 7169:         } else {
 7170:             document.getElementById('notified').style.display='block';
 7171:         }
 7172:     }
 7173:     return;
 7174: }
 7175: 
 7176: function getIndexByName(item) {
 7177:     for (var i=0;i<document.$formname.elements.length;i++) {
 7178:         if (document.$formname.elements[i].name == item) {
 7179:             return i;
 7180:         }
 7181:     }
 7182:     return -1;
 7183: }
 7184: ENDSCRIPT
 7185: 
 7186:     my $output = '<script type="text/javascript">'."\n".
 7187:                  '// <![CDATA['."\n".
 7188:                  $setsec_js."\n".$selfenroll_js."\n".
 7189:                  '// ]]>'."\n".
 7190:                  '</script>'."\n".
 7191:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 7192:     my $visactions = &cat_visibility($cdom);
 7193:     my ($cathash,%cattype);
 7194:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7195:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7196:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7197:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7198:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7199:         if ($cattype{'auth'} eq '') {
 7200:             $cattype{'auth'} = 'std';
 7201:         }
 7202:         if ($cattype{'unauth'} eq '') {
 7203:             $cattype{'unauth'} = 'std';
 7204:         }
 7205:     } else {
 7206:         $cathash = {};
 7207:         $cattype{'auth'} = 'std';
 7208:         $cattype{'unauth'} = 'std';
 7209:     }
 7210:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7211:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7212:                   '<br />'.
 7213:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7214:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7215:                   '</ul>');
 7216:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7217:         if ($currsettings->{'uniquecode'}) {
 7218:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7219:         } else {
 7220:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7221:                   '<br />'.
 7222:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7223:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7224:                   '</ul><br />');
 7225:         }
 7226:     } else {
 7227:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7228:         if (ref($visactions) eq 'HASH') {
 7229:             if ($visible) {
 7230:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 7231:            } else {
 7232:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 7233:                           .$visactions->{'yous'}.
 7234:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 7235:                 if (ref($vismsgs) eq 'ARRAY') {
 7236:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 7237:                     foreach my $item (@{$vismsgs}) {
 7238:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 7239:                     }
 7240:                     $output .= '</ul>';
 7241:                 }
 7242:                 $output .= '</p>';
 7243:             }
 7244:         }
 7245:     }
 7246:     my $actionhref = '/adm/createuser';
 7247:     if ($context eq 'domain') {
 7248:         $actionhref = '/adm/modifycourse';
 7249:     }
 7250: 
 7251:     my %noedit;
 7252:     unless ($context eq 'domain') {
 7253:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7254:     }
 7255:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 7256:                &Apache::lonhtmlcommon::start_pick_box();
 7257:     if (ref($row) eq 'ARRAY') {
 7258:         foreach my $item (@{$row}) {
 7259:             my $title = $item; 
 7260:             if (ref($lt) eq 'HASH') {
 7261:                 $title = $lt->{$item};
 7262:             }
 7263:             $output .= &Apache::lonhtmlcommon::row_title($title);
 7264:             if ($item eq 'types') {
 7265:                 my $curr_types;
 7266:                 if (ref($currsettings) eq 'HASH') {
 7267:                     $curr_types = $currsettings->{'selfenroll_types'};
 7268:                 }
 7269:                 if ($noedit{$item}) {
 7270:                     if ($curr_types eq '*') {
 7271:                         $output .= &mt('Any user in any domain');   
 7272:                     } else {
 7273:                         my @entries = split(/;/,$curr_types);
 7274:                         if (@entries > 0) {
 7275:                             $output .= '<ul>'; 
 7276:                             foreach my $entry (@entries) {
 7277:                                 my ($currdom,$typestr) = split(/:/,$entry);
 7278:                                 next if ($typestr eq '');
 7279:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 7280:                                 my @currinsttypes = split(',',$typestr);
 7281:                                 my ($othertitle,$usertypes,$types) = 
 7282:                                     &Apache::loncommon::sorted_inst_types($currdom);
 7283:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7284:                                     $usertypes->{'any'} = &mt('any user'); 
 7285:                                     if (keys(%{$usertypes}) > 0) {
 7286:                                         $usertypes->{'other'} = &mt('other users');
 7287:                                     }
 7288:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 7289:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 7290:                                  }
 7291:                             }
 7292:                             $output .= '</ul>';
 7293:                         } else {
 7294:                             $output .= &mt('None');
 7295:                         }
 7296:                     }
 7297:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7298:                     next;
 7299:                 }
 7300:                 my $showdomdesc = 1;
 7301:                 my $includeempty = 1;
 7302:                 my $num = 0;
 7303:                 $output .= &Apache::loncommon::start_data_table().
 7304:                            &Apache::loncommon::start_data_table_row()
 7305:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 7306:                            .&mt('Any user in any domain:')
 7307:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 7308:                 if ($curr_types eq '*') {
 7309:                     $output .= ' checked="checked" '; 
 7310:                 }
 7311:                 $output .= 'onchange="javascript:update_types('.
 7312:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 7313:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 7314:                 if ($curr_types ne '*') {
 7315:                     $output .= ' checked="checked" ';
 7316:                 }
 7317:                 $output .= ' onchange="javascript:update_types('.
 7318:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 7319:                            &Apache::loncommon::end_data_table_row().
 7320:                            &Apache::loncommon::end_data_table().
 7321:                            &mt('Or').'<br />'.
 7322:                            &Apache::loncommon::start_data_table();
 7323:                 my %currdoms;
 7324:                 if ($curr_types eq '') {
 7325:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 7326:                 } elsif ($curr_types ne '*') {
 7327:                     my @entries = split(/;/,$curr_types);
 7328:                     if (@entries > 0) {
 7329:                         foreach my $entry (@entries) {
 7330:                             my ($currdom,$typestr) = split(/:/,$entry);
 7331:                             $currdoms{$currdom} = 1;
 7332:                             my $domdesc = &Apache::lonnet::domain($currdom);
 7333:                             my @currinsttypes = split(',',$typestr);
 7334:                             $output .= &Apache::loncommon::start_data_table_row()
 7335:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 7336:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 7337:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 7338:                                        .'" value="'.$currdom.'" /></span><br />'
 7339:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 7340:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 7341:                                        .&mt('Delete').'</label></span></td>';
 7342:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 7343:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 7344:                                        .&Apache::loncommon::end_data_table_row();
 7345:                             $num ++;
 7346:                         }
 7347:                     }
 7348:                 }
 7349:                 my $add_domtitle = &mt('Users in additional domain:');
 7350:                 if ($curr_types eq '*') { 
 7351:                     $add_domtitle = &mt('Users in specific domain:');
 7352:                 } elsif ($curr_types eq '') {
 7353:                     $add_domtitle = &mt('Users in other domain:');
 7354:                 }
 7355:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 7356:                 $output .= &Apache::loncommon::start_data_table_row()
 7357:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 7358:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 7359:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 7360:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 7361:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 7362:                            .&Apache::loncommon::end_data_table();
 7363:             } elsif ($item eq 'registered') {
 7364:                 my ($regon,$regoff);
 7365:                 my $registered;
 7366:                 if (ref($currsettings) eq 'HASH') {
 7367:                     $registered = $currsettings->{'selfenroll_registered'};
 7368:                 }
 7369:                 if ($noedit{$item}) {
 7370:                     if ($registered) {
 7371:                         $output .= &mt('Must be registered in course');
 7372:                     } else {
 7373:                         $output .= &mt('No requirement');
 7374:                     }
 7375:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7376:                     next;
 7377:                 }
 7378:                 if ($registered) {
 7379:                     $regon = ' checked="checked" ';
 7380:                     $regoff = '';
 7381:                 } else {
 7382:                     $regon = '';
 7383:                     $regoff = ' checked="checked" ';
 7384:                 }
 7385:                 $output .= '<label>'.
 7386:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 7387:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 7388:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 7389:                            &mt('No').'</label>';
 7390:             } elsif ($item eq 'enroll_dates') {
 7391:                 my ($starttime,$endtime);
 7392:                 if (ref($currsettings) eq 'HASH') {
 7393:                     $starttime = $currsettings->{'selfenroll_start_date'};
 7394:                     $endtime = $currsettings->{'selfenroll_end_date'};
 7395:                     if ($starttime eq '') {
 7396:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7397:                     }
 7398:                     if ($endtime eq '') {
 7399:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7400:                     }
 7401:                 }
 7402:                 if ($noedit{$item}) {
 7403:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7404:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7405:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7406:                     next;
 7407:                 }
 7408:                 my $startform =
 7409:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 7410:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7411:                 my $endform =
 7412:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 7413:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7414:                 $output .= &selfenroll_date_forms($startform,$endform);
 7415:             } elsif ($item eq 'access_dates') {
 7416:                 my ($starttime,$endtime);
 7417:                 if (ref($currsettings) eq 'HASH') {
 7418:                     $starttime = $currsettings->{'selfenroll_start_access'};
 7419:                     $endtime = $currsettings->{'selfenroll_end_access'};
 7420:                     if ($starttime eq '') {
 7421:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7422:                     }
 7423:                     if ($endtime eq '') {
 7424:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7425:                     }
 7426:                 }
 7427:                 if ($noedit{$item}) {
 7428:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7429:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7430:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7431:                     next;
 7432:                 }
 7433:                 my $startform =
 7434:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 7435:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7436:                 my $endform =
 7437:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 7438:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7439:                 $output .= &selfenroll_date_forms($startform,$endform);
 7440:             } elsif ($item eq 'section') {
 7441:                 my $currsec;
 7442:                 if (ref($currsettings) eq 'HASH') {
 7443:                     $currsec = $currsettings->{'selfenroll_section'};
 7444:                 }
 7445:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 7446:                 my $newsecval;
 7447:                 if ($currsec ne 'none' && $currsec ne '') {
 7448:                     if (!defined($sections_count{$currsec})) {
 7449:                         $newsecval = $currsec;
 7450:                     }
 7451:                 }
 7452:                 if ($noedit{$item}) {
 7453:                     if ($currsec ne '') {
 7454:                         $output .= $currsec;
 7455:                     } else {
 7456:                         $output .= &mt('No specific section');
 7457:                     }
 7458:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7459:                     next;
 7460:                 }
 7461:                 my $sections_select = 
 7462:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 7463:                 $output .= '<table class="LC_createuser">'."\n".
 7464:                            '<tr class="LC_section_row">'."\n".
 7465:                            '<td align="center">'.&mt('Existing sections')."\n".
 7466:                            '<br />'.$sections_select.'</td><td align="center">'.
 7467:                            &mt('New section').'<br />'."\n".
 7468:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 7469:                            '<input type="hidden" name="sections" value="" />'."\n".
 7470:                            '</td></tr></table>'."\n";
 7471:             } elsif ($item eq 'approval') {
 7472:                 my ($currnotified,$currapproval,%appchecked);
 7473:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7474:                 if (ref($currsettings) eq 'HASH') {
 7475:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 7476:                     $currapproval = $currsettings->{'selfenroll_approval'};
 7477:                 }
 7478:                 if ($currapproval !~ /^[012]$/) {
 7479:                     $currapproval = 0;
 7480:                 }
 7481:                 if ($noedit{$item}) {
 7482:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 7483:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 7484:                     next;
 7485:                 }
 7486:                 $appchecked{$currapproval} = ' checked="checked"';
 7487:                 for my $i (0..2) {
 7488:                     $output .= '<label>'.
 7489:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 7490:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 7491:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 7492:                 }
 7493:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 7494:                 my (@ccs,%notified);
 7495:                 my $ccrole = 'cc';
 7496:                 if ($crstype eq 'Community') {
 7497:                     $ccrole = 'co';
 7498:                 }
 7499:                 if ($advhash{$ccrole}) {
 7500:                     @ccs = split(/,/,$advhash{$ccrole});
 7501:                 }
 7502:                 if ($currnotified) {
 7503:                     foreach my $current (split(/,/,$currnotified)) {
 7504:                         $notified{$current} = 1;
 7505:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 7506:                             push(@ccs,$current);
 7507:                         }
 7508:                     }
 7509:                 }
 7510:                 if (@ccs) {
 7511:                     my $style;
 7512:                     unless ($currapproval) {
 7513:                         $style = ' style="display: none;"'; 
 7514:                     }
 7515:                     $output .= '<br /><div id="notified"'.$style.'>'.
 7516:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 7517:                                &Apache::loncommon::start_data_table().
 7518:                                &Apache::loncommon::start_data_table_row();
 7519:                     my $count = 0;
 7520:                     my $numcols = 4;
 7521:                     foreach my $cc (sort(@ccs)) {
 7522:                         my $notifyon;
 7523:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 7524:                         if ($notified{$cc}) {
 7525:                             $notifyon = ' checked="checked" ';
 7526:                         }
 7527:                         if ($count && !$count%$numcols) {
 7528:                             $output .= &Apache::loncommon::end_data_table_row().
 7529:                                        &Apache::loncommon::start_data_table_row()
 7530:                         }
 7531:                         $output .= '<td><span class="LC_nobreak"><label>'.
 7532:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 7533:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 7534:                                    '</label></span></td>';
 7535:                         $count ++;
 7536:                     }
 7537:                     my $rem = $count%$numcols;
 7538:                     if ($rem) {
 7539:                         my $emptycols = $numcols - $rem;
 7540:                         for (my $i=0; $i<$emptycols; $i++) { 
 7541:                             $output .= '<td>&nbsp;</td>';
 7542:                         }
 7543:                     }
 7544:                     $output .= &Apache::loncommon::end_data_table_row().
 7545:                                &Apache::loncommon::end_data_table().
 7546:                                '</div>';
 7547:                 }
 7548:             } elsif ($item eq 'limit') {
 7549:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 7550:                 if (ref($currsettings) eq 'HASH') {
 7551:                     $currlim = $currsettings->{'selfenroll_limit'};
 7552:                     $currcap = $currsettings->{'selfenroll_cap'};
 7553:                 }
 7554:                 if ($noedit{$item}) {
 7555:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 7556:                         if ($currlim eq 'allstudents') {
 7557:                             $output .= &mt('Limit by total students');
 7558:                         } elsif ($currlim eq 'selfenrolled') {
 7559:                             $output .= &mt('Limit by total self-enrolled students');
 7560:                         }
 7561:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 7562:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 7563:                     } else {
 7564:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 7565:                     }
 7566:                     next;
 7567:                 }
 7568:                 if ($currlim eq 'allstudents') {
 7569:                     $crslimit = ' checked="checked" ';
 7570:                     $selflimit = ' ';
 7571:                     $nolimit = ' ';
 7572:                 } elsif ($currlim eq 'selfenrolled') {
 7573:                     $crslimit = ' ';
 7574:                     $selflimit = ' checked="checked" ';
 7575:                     $nolimit = ' '; 
 7576:                 } else {
 7577:                     $crslimit = ' ';
 7578:                     $selflimit = ' ';
 7579:                     $nolimit = ' checked="checked" ';
 7580:                 }
 7581:                 $output .= '<table><tr><td><label>'.
 7582:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 7583:                            &mt('No limit').'</label></td><td><label>'.
 7584:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 7585:                            &mt('Limit by total students').'</label></td><td><label>'.
 7586:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 7587:                            &mt('Limit by total self-enrolled students').
 7588:                            '</td></tr><tr>'.
 7589:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 7590:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 7591:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 7592:             }
 7593:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 7594:         }
 7595:     }
 7596:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 7597:     unless ($readonly) {
 7598:         $output .= '<input type="button" name="selfenrollconf" value="'
 7599:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 7600:     }
 7601:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 7602:               .'<input type="hidden" name="state" value="done" />'."\n"
 7603:               .$additional.'</form>';
 7604:     $r->print($output);
 7605:     return;
 7606: }
 7607: 
 7608: sub get_noedit_fields {
 7609:     my ($cdom,$cnum,$crstype,$row) = @_;
 7610:     my %noedit;
 7611:     if (ref($row) eq 'ARRAY') {
 7612:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 7613:                                                            'internal.selfenrollmgrdc',
 7614:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 7615:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 7616:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 7617:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 7618:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 7619:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 7620:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 7621: 
 7622:         foreach my $item (@{$row}) {
 7623:             next if ($specific_managebycc{$item});
 7624:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 7625:                 $noedit{$item} = 1;
 7626:             }
 7627:         }
 7628:     }
 7629:     return %noedit;
 7630: }
 7631: 
 7632: sub visible_in_stdcat {
 7633:     my ($cdom,$cnum,$domconf) = @_;
 7634:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 7635:     unless (ref($domconf) eq 'HASH') {
 7636:         return ($visible,$cansetvis,\@vismsgs);
 7637:     }
 7638:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7639:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 7640:             $settable{'togglecats'} = 1;
 7641:         }
 7642:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 7643:             $settable{'categorize'} = 1;
 7644:         }
 7645:         $cathash = $domconf->{'coursecategories'}{'cats'};
 7646:     }
 7647:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 7648:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 7649:     } elsif ($settable{'togglecats'}) {
 7650:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 7651:     } elsif ($settable{'categorize'}) {
 7652:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 7653:     } else {
 7654:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 7655:     }
 7656:      
 7657:     my %currsettings =
 7658:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 7659:                              $cdom,$cnum);
 7660:     $visible = 0;
 7661:     if ($currsettings{'internal.coursecode'} ne '') {
 7662:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7663:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7664:             if (ref($cathash) eq 'HASH') {
 7665:                 if ($cathash->{'instcode::0'} eq '') {
 7666:                     push(@vismsgs,'dc_addinst'); 
 7667:                 } else {
 7668:                     $visible = 1;
 7669:                 }
 7670:             } else {
 7671:                 $visible = 1;
 7672:             }
 7673:         } else {
 7674:             $visible = 1;
 7675:         }
 7676:     } else {
 7677:         if (ref($cathash) eq 'HASH') {
 7678:             if ($cathash->{'instcode::0'} ne '') {
 7679:                 push(@vismsgs,'dc_instcode');
 7680:             }
 7681:         } else {
 7682:             push(@vismsgs,'dc_instcode');
 7683:         }
 7684:     }
 7685:     if ($currsettings{'categories'} ne '') {
 7686:         my $cathash;
 7687:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7688:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7689:             if (ref($cathash) eq 'HASH') {
 7690:                 if (keys(%{$cathash}) == 0) {
 7691:                     push(@vismsgs,'dc_catalog');
 7692:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 7693:                     push(@vismsgs,'dc_categories');
 7694:                 } else {
 7695:                     my @currcategories = split('&',$currsettings{'categories'});
 7696:                     my $matched = 0;
 7697:                     foreach my $cat (@currcategories) {
 7698:                         if ($cathash->{$cat} ne '') {
 7699:                             $visible = 1;
 7700:                             $matched = 1;
 7701:                             last;
 7702:                         }
 7703:                     }
 7704:                     if (!$matched) {
 7705:                         if ($settable{'categorize'}) { 
 7706:                             push(@vismsgs,'chgcat');
 7707:                         } else {
 7708:                             push(@vismsgs,'dc_chgcat');
 7709:                         }
 7710:                     }
 7711:                 }
 7712:             }
 7713:         }
 7714:     } else {
 7715:         if (ref($cathash) eq 'HASH') {
 7716:             if ((keys(%{$cathash}) > 1) || 
 7717:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 7718:                 if ($settable{'categorize'}) {
 7719:                     push(@vismsgs,'addcat');
 7720:                 } else {
 7721:                     push(@vismsgs,'dc_addcat');
 7722:                 }
 7723:             }
 7724:         }
 7725:     }
 7726:     if ($currsettings{'hidefromcat'} eq 'yes') {
 7727:         $visible = 0;
 7728:         if ($settable{'togglecats'}) {
 7729:             unshift(@vismsgs,'unhide');
 7730:         } else {
 7731:             unshift(@vismsgs,'dc_unhide')
 7732:         }
 7733:     }
 7734:     return ($visible,$cansetvis,\@vismsgs);
 7735: }
 7736: 
 7737: sub cat_visibility {
 7738:     my ($cdom) = @_;
 7739:     my %visactions = &Apache::lonlocal::texthash(
 7740:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 7741:                    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.',
 7742:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 7743:                    none => 'Display of a course catalog is disabled for this domain.',
 7744:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 7745:                    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.',
 7746:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 7747:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 7748:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 7749:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 7750:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 7751:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 7752:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 7753:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 7754:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 7755:                    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',
 7756:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 7757:     );
 7758:     if ($env{'request.role'} eq "dc./$cdom/") {
 7759:         $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;');
 7760:         $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;');
 7761:         $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;');
 7762:         $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;');
 7763:         $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;');
 7764:         $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;');
 7765:         $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;');
 7766:         $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;');
 7767:         $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;');
 7768:     }
 7769:     $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>"');
 7770:     $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>"');
 7771:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 7772:     return \%visactions;
 7773: }
 7774: 
 7775: sub new_selfenroll_dom_row {
 7776:     my ($newdom,$num) = @_;
 7777:     my $domdesc = &Apache::lonnet::domain($newdom);
 7778:     my $output;
 7779:     if ($domdesc ne '') {
 7780:         $output .= &Apache::loncommon::start_data_table_row()
 7781:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 7782:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 7783:                    .'" value="'.$newdom.'" /></span><br />'
 7784:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 7785:                    .'name="selfenroll_activate" value="'.$num.'" '
 7786:                    .'onchange="javascript:update_types('
 7787:                    ."'selfenroll_activate','$num'".');" />'
 7788:                    .&mt('Activate').'</label></span></td>';
 7789:         my @currinsttypes;
 7790:         $output .= '<td>'.&mt('User types:').'<br />'
 7791:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 7792:                    .&Apache::loncommon::end_data_table_row();
 7793:     }
 7794:     return $output;
 7795: }
 7796: 
 7797: sub selfenroll_inst_types {
 7798:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 7799:     my $output;
 7800:     my $numinrow = 4;
 7801:     my $count = 0;
 7802:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 7803:     my $othervalue = 'any';
 7804:     my $disabled;
 7805:     if ($readonly) {
 7806:         $disabled = ' disabled="disabled"';
 7807:     }
 7808:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7809:         if (keys(%{$usertypes}) > 0) {
 7810:             $othervalue = 'other';
 7811:         }
 7812:         $output .= '<table><tr>';
 7813:         foreach my $type (@{$types}) {
 7814:             if (($count > 0) && ($count%$numinrow == 0)) {
 7815:                 $output .= '</tr><tr>';
 7816:             }
 7817:             if (defined($usertypes->{$type})) {
 7818:                 my $esc_type = &escape($type);
 7819:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 7820:                            $esc_type.'" ';
 7821:                 if (ref($currinsttypes) eq 'ARRAY') {
 7822:                     if (@{$currinsttypes} > 0) {
 7823:                         if (grep(/^any$/,@{$currinsttypes})) {
 7824:                             $output .= 'checked="checked"';
 7825:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 7826:                             $output .= 'checked="checked"';
 7827:                         }
 7828:                     } else {
 7829:                         $output .= 'checked="checked"';
 7830:                     }
 7831:                 }
 7832:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 7833:             }
 7834:             $count ++;
 7835:         }
 7836:         if (($count > 0) && ($count%$numinrow == 0)) {
 7837:             $output .= '</tr><tr>';
 7838:         }
 7839:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 7840:         if (ref($currinsttypes) eq 'ARRAY') {
 7841:             if (@{$currinsttypes} > 0) {
 7842:                 if (grep(/^any$/,@{$currinsttypes})) { 
 7843:                     $output .= ' checked="checked"';
 7844:                 } elsif ($othervalue eq 'other') {
 7845:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 7846:                         $output .= ' checked="checked"';
 7847:                     }
 7848:                 }
 7849:             } else {
 7850:                 $output .= ' checked="checked"';
 7851:             }
 7852:         } else {
 7853:             $output .= ' checked="checked"';
 7854:         }
 7855:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 7856:     }
 7857:     return $output;
 7858: }
 7859: 
 7860: sub selfenroll_date_forms {
 7861:     my ($startform,$endform) = @_;
 7862:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 7863:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 7864:                                                     'LC_oddrow_value')."\n".
 7865:                   $startform."\n".
 7866:                   &Apache::lonhtmlcommon::row_closure(1).
 7867:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 7868:                                                    'LC_oddrow_value')."\n".
 7869:                   $endform."\n".
 7870:                   &Apache::lonhtmlcommon::row_closure(1).
 7871:                   &Apache::lonhtmlcommon::end_pick_box();
 7872:     return $output;
 7873: }
 7874: 
 7875: sub print_userchangelogs_display {
 7876:     my ($r,$context,$permission,$brcrum) = @_;
 7877:     my $formname = 'rolelog';
 7878:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 7879:     if ($context eq 'domain') {
 7880:         $domain = $env{'request.role.domain'};
 7881:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 7882:     } else {
 7883:         if ($context eq 'course') { 
 7884:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7885:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 7886:             $crstype = &Apache::loncommon::course_type();
 7887:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 7888:             my %saveable_parameters = ('show' => 'scalar',);
 7889:             &Apache::loncommon::store_course_settings('roles_log',
 7890:                                                       \%saveable_parameters);
 7891:             &Apache::loncommon::restore_course_settings('roles_log',
 7892:                                                         \%saveable_parameters);
 7893:         } elsif ($context eq 'author') {
 7894:             $domain = $env{'user.domain'};
 7895:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 7896:                 $username = $env{'user.name'};
 7897:             } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 7898:                 ($domain,$username) = ($1,$2);
 7899:             } else {
 7900:                 undef($domain);
 7901:             }
 7902:         }
 7903:         if ($domain ne '' && $username ne '') { 
 7904:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 7905:         }
 7906:     }
 7907:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 7908: 
 7909:     my $helpitem;
 7910:     if ($context eq 'course') {
 7911:         $helpitem = 'Course_User_Logs';
 7912:     } elsif ($context eq 'domain') {
 7913:         $helpitem = 'Domain_Role_Logs';
 7914:     } elsif ($context eq 'author') {
 7915:         $helpitem = 'Author_User_Logs';
 7916:     }
 7917:     push (@{$brcrum},
 7918:              {href => '/adm/createuser?action=changelogs',
 7919:               text => 'User Management Logs',
 7920:               help => $helpitem});
 7921:     my $bread_crumbs_component = 'User Changes';
 7922:     my $args = { bread_crumbs           => $brcrum,
 7923:                  bread_crumbs_component => $bread_crumbs_component};
 7924: 
 7925:     # Create navigation javascript
 7926:     my $jsnav = &userlogdisplay_js($formname);
 7927: 
 7928:     my $jscript = (<<ENDSCRIPT);
 7929: <script type="text/javascript">
 7930: // <![CDATA[
 7931: $jsnav
 7932: // ]]>
 7933: </script>
 7934: ENDSCRIPT
 7935: 
 7936:     # print page header
 7937:     $r->print(&header($jscript,$args));
 7938: 
 7939:     # set defaults
 7940:     my $now = time();
 7941:     my $defstart = $now - (7*24*3600); #7 days ago 
 7942:     my %defaults = (
 7943:                      page               => '1',
 7944:                      show               => '10',
 7945:                      role               => 'any',
 7946:                      chgcontext         => 'any',
 7947:                      rolelog_start_date => $defstart,
 7948:                      rolelog_end_date   => $now,
 7949:                      approvals          => 'any',
 7950:                    );
 7951:     my $more_records = 0;
 7952: 
 7953:     # set current
 7954:     my %curr;
 7955:     foreach my $item ('show','page','role','chgcontext','approvals') {
 7956:         $curr{$item} = $env{'form.'.$item};
 7957:     }
 7958:     my ($startdate,$enddate) = 
 7959:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 7960:     $curr{'rolelog_start_date'} = $startdate;
 7961:     $curr{'rolelog_end_date'} = $enddate;
 7962:     foreach my $key (keys(%defaults)) {
 7963:         if ($curr{$key} eq '') {
 7964:             $curr{$key} = $defaults{$key};
 7965:         }
 7966:     }
 7967:     my (%whodunit,%changed,$version);
 7968:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 7969:     my ($minshown,$maxshown);
 7970:     $minshown = 1;
 7971:     my $count = 0;
 7972:     if ($curr{'show'} =~ /\D/) {
 7973:         $curr{'page'} = 1;
 7974:     } else {
 7975:         $maxshown = $curr{'page'} * $curr{'show'};
 7976:         if ($curr{'page'} > 1) {
 7977:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7978:         }
 7979:     }
 7980: 
 7981:     # Form Header
 7982:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7983:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 7984:                                    $version,$crstype));
 7985: 
 7986:     my $showntableheader = 0;
 7987: 
 7988:     # Table Header
 7989:     my $tableheader = 
 7990:         &Apache::loncommon::start_data_table_header_row()
 7991:        .'<th>&nbsp;</th>'
 7992:        .'<th>'.&mt('When').'</th>'
 7993:        .'<th>'.&mt('Who made the change').'</th>'
 7994:        .'<th>'.&mt('Changed User').'</th>'
 7995:        .'<th>'.&mt('Role').'</th>';
 7996: 
 7997:     if ($context eq 'course') {
 7998:         $tableheader .= '<th>'.&mt('Section').'</th>';
 7999:     }
 8000:     $tableheader .=
 8001:         '<th>'.&mt('Context').'</th>'
 8002:        .'<th>'.&mt('Start').'</th>'
 8003:        .'<th>'.&mt('End').'</th>'
 8004:        .&Apache::loncommon::end_data_table_header_row();
 8005: 
 8006:     # Display user change log data
 8007:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 8008:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 8009:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 8010:         if ($curr{'show'} !~ /\D/) {
 8011:             if ($count >= $curr{'page'} * $curr{'show'}) {
 8012:                 $more_records = 1;
 8013:                 last;
 8014:             }
 8015:         }
 8016:         if ($curr{'role'} ne 'any') {
 8017:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 8018:         }
 8019:         if ($curr{'chgcontext'} ne 'any') {
 8020:             if ($curr{'chgcontext'} eq 'selfenroll') {
 8021:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 8022:             } else {
 8023:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 8024:             }
 8025:         }
 8026:         if (($context eq 'course') && ($viewablesec ne '')) {
 8027:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 8028:         }
 8029:         if ($curr{'approvals'} eq 'none') {
 8030:             next if ($roleslog{$id}{'logentry'}{'approval'});
 8031:         } elsif ($curr{'approvals'} ne 'any') { 
 8032:             next if ($roleslog{$id}{'logentry'}{'approval'} ne $curr{'approvals'});
 8033:         }
 8034:         $count ++;
 8035:         next if ($count < $minshown);
 8036:         unless ($showntableheader) {
 8037:             $r->print(&Apache::loncommon::start_data_table()
 8038:                      .$tableheader);
 8039:             $r->rflush();
 8040:             $showntableheader = 1;
 8041:         }
 8042:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 8043:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 8044:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 8045:         }
 8046:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 8047:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 8048:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 8049:         }
 8050:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 8051:         if ($sec eq '') {
 8052:             $sec = &mt('None');
 8053:         }
 8054:         my ($rolestart,$roleend);
 8055:         if ($roleslog{$id}{'delflag'}) {
 8056:             $rolestart = &mt('deleted');
 8057:             $roleend = &mt('deleted');
 8058:         } else {
 8059:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 8060:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 8061:             if ($rolestart eq '' || $rolestart == 0) {
 8062:                 $rolestart = &mt('No start date'); 
 8063:             } else {
 8064:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 8065:             }
 8066:             if ($roleend eq '' || $roleend == 0) { 
 8067:                 $roleend = &mt('No end date');
 8068:             } else {
 8069:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 8070:             }
 8071:         }
 8072:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 8073:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 8074:             $chgcontext = 'selfenroll';
 8075:         }
 8076:         my %lt = &rolechg_contexts($context,$crstype);
 8077:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 8078:             $chgcontext = $lt{$chgcontext};
 8079:         }
 8080:         my ($showreqby,%reqby);
 8081:         if (($roleslog{$id}{'logentry'}{'approval'}) &&
 8082:             ($roleslog{$id}{'logentry'}{'requester'})) {
 8083:             if ($reqby{$roleslog{$id}{'logentry'}{'requester'}} eq '') {
 8084:                 my ($requname,$requdom) = split(/:/,$roleslog{$id}{'logentry'}{'requester'});
 8085:                 $reqby{$roleslog{$id}{'logentry'}{'requester'}} =
 8086:                     &Apache::loncommon::plainname($requname,$requdom);
 8087:             }
 8088:             $showreqby = &mt('Requester').': <span class="LC_nobreak">'.$reqby{$roleslog{$id}{'logentry'}{'requester'}}.'</span><br />';
 8089:             if ($roleslog{$id}{'logentry'}{'approval'} eq 'domain') {
 8090:                 $showreqby .= &mt('Adjudicator').': <span class="LC_nobreak">'.
 8091:                               $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.
 8092:                               '</span>';
 8093:             } else {
 8094:                 $showreqby .= '<span class="LC_nobreak">'.&mt('User approved').'</span>';
 8095:             }
 8096:         } else {
 8097:             $showreqby = $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}};
 8098:         }
 8099:         $r->print(
 8100:             &Apache::loncommon::start_data_table_row()
 8101:            .'<td>'.$count.'</td>'
 8102:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 8103:            .'<td>'.$showreqby.'</td>'
 8104:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 8105:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 8106:         if ($context eq 'course') { 
 8107:             $r->print('<td>'.$sec.'</td>');
 8108:         }
 8109:         $r->print(
 8110:             '<td>'.$chgcontext.'</td>'
 8111:            .'<td>'.$rolestart.'</td>'
 8112:            .'<td>'.$roleend.'</td>'
 8113:            .&Apache::loncommon::end_data_table_row()."\n");
 8114:     }
 8115: 
 8116:     if ($showntableheader) { # Table footer, if content displayed above
 8117:         $r->print(&Apache::loncommon::end_data_table().
 8118:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8119:     } else { # No content displayed above
 8120:         $r->print('<p class="LC_info">'
 8121:                  .&mt('There are no records to display.')
 8122:                  .'</p>'
 8123:         );
 8124:     }
 8125: 
 8126:     # Form Footer
 8127:     $r->print( 
 8128:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8129:        .'<input type="hidden" name="action" value="changelogs" />'
 8130:        .'</form>');
 8131:     return;
 8132: }
 8133: 
 8134: sub print_useraccesslogs_display {
 8135:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 8136:     my $formname = 'accesslog';
 8137:     my $form = 'document.accesslog';
 8138: 
 8139: # set breadcrumbs
 8140:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 8141:     my $prevphasestr;
 8142:     if ($env{'form.popup'}) {
 8143:         $brcrum = [];
 8144:     } else {
 8145:         push (@{$brcrum},
 8146:             {href => "javascript:backPage($form)",
 8147:              text => $breadcrumb_text{'search'}});
 8148:         my @prevphases;
 8149:         if ($env{'form.prevphases'}) {
 8150:             @prevphases = split(/,/,$env{'form.prevphases'});
 8151:             $prevphasestr = $env{'form.prevphases'};
 8152:         }
 8153:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 8154:             push(@{$brcrum},
 8155:                   {href => "javascript:backPage($form,'get_user_info','select')",
 8156:                    text => $breadcrumb_text{'userpicked'}});
 8157:             if ($env{'form.phase'} eq 'userpicked') {
 8158:                 $prevphasestr = 'userpicked';
 8159:             }
 8160:         }
 8161:     }
 8162:     push(@{$brcrum},
 8163:              {href => '/adm/createuser?action=accesslogs',
 8164:               text => 'User access logs',
 8165:               help => 'Domain_User_Access_Logs'});
 8166:     my $bread_crumbs_component = 'User Access Logs';
 8167:     my $args = { bread_crumbs           => $brcrum,
 8168:                  bread_crumbs_component => 'User Management'};
 8169:     if ($env{'form.popup'}) {
 8170:         $args->{'no_nav_bar'} = 1;
 8171:         $args->{'bread_crumbs_nomenu'} = 1;
 8172:     }
 8173: 
 8174: # set javascript
 8175:     my ($jsback,$elements) = &crumb_utilities();
 8176:     my $jsnav = &userlogdisplay_js($formname);
 8177: 
 8178:     my $jscript = (<<ENDSCRIPT);
 8179: <script type="text/javascript">
 8180: // <![CDATA[
 8181: 
 8182: $jsback
 8183: $jsnav
 8184: 
 8185: // ]]>
 8186: </script>
 8187: 
 8188: ENDSCRIPT
 8189: 
 8190: # print page header
 8191:     $r->print(&header($jscript,$args));
 8192: 
 8193: # early out unless log data can be displayed.
 8194:     unless ($permission->{'activity'}) {
 8195:         $r->print('<p class="LC_warning">'
 8196:                  .&mt('You do not have rights to display user access logs.')
 8197:                  .'</p>');
 8198:         if ($env{'form.popup'}) {
 8199:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8200:         } else {
 8201:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8202:         }
 8203:         return;
 8204:     }
 8205: 
 8206:     unless ($udom eq $env{'request.role.domain'}) {
 8207:         $r->print('<p class="LC_warning">'
 8208:                  .&mt("User's domain must match role's domain")
 8209:                  .'</p>'
 8210:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8211:         return;
 8212:     }
 8213: 
 8214:     if (($uname eq '') || ($udom eq '')) {
 8215:         $r->print('<p class="LC_warning">'
 8216:                  .&mt('Invalid username or domain')
 8217:                  .'</p>'
 8218:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8219:         return;
 8220:     }
 8221: 
 8222:     if (&Apache::lonnet::privileged($uname,$udom,
 8223:                                     [$env{'request.role.domain'}],['dc','su'])) {
 8224:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 8225:                                             [$env{'request.role.domain'}],['dc','su'])) {
 8226:             $r->print('<p class="LC_warning">'
 8227:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 8228:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 8229:                                                          $uname,$udom))
 8230:                  .'</p>');
 8231:             if ($env{'form.popup'}) {
 8232:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8233:             } else {
 8234:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8235:             }
 8236:             return;
 8237:         }
 8238:     }
 8239: 
 8240: # set defaults
 8241:     my $now = time();
 8242:     my $defstart = $now - (7*24*3600);
 8243:     my %defaults = (
 8244:                      page                 => '1',
 8245:                      show                 => '10',
 8246:                      activity             => 'any',
 8247:                      accesslog_start_date => $defstart,
 8248:                      accesslog_end_date   => $now,
 8249:                    );
 8250:     my $more_records = 0;
 8251: 
 8252: # set current
 8253:     my %curr;
 8254:     foreach my $item ('show','page','activity') {
 8255:         $curr{$item} = $env{'form.'.$item};
 8256:     }
 8257:     my ($startdate,$enddate) =
 8258:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 8259:     $curr{'accesslog_start_date'} = $startdate;
 8260:     $curr{'accesslog_end_date'} = $enddate;
 8261:     foreach my $key (keys(%defaults)) {
 8262:         if ($curr{$key} eq '') {
 8263:             $curr{$key} = $defaults{$key};
 8264:         }
 8265:     }
 8266:     my ($minshown,$maxshown);
 8267:     $minshown = 1;
 8268:     my $count = 0;
 8269:     if ($curr{'show'} =~ /\D/) {
 8270:         $curr{'page'} = 1;
 8271:     } else {
 8272:         $maxshown = $curr{'page'} * $curr{'show'};
 8273:         if ($curr{'page'} > 1) {
 8274:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8275:         }
 8276:     }
 8277: 
 8278: # form header
 8279:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8280:               &activity_display_filter($formname,\%curr));
 8281: 
 8282:     my $showntableheader = 0;
 8283:     my ($nav_script,$nav_links);
 8284: 
 8285: # table header
 8286:     my $heading = '<h3>'.
 8287:         &mt('User access logs for: [_1]',
 8288:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 8289:     my $tableheader = $heading
 8290:        .&Apache::loncommon::start_data_table_header_row()
 8291:        .'<th>&nbsp;</th>'
 8292:        .'<th>'.&mt('When').'</th>'
 8293:        .'<th>'.&mt('HostID').'</th>'
 8294:        .'<th>'.&mt('Event').'</th>'
 8295:        .'<th>'.&mt('Other data').'</th>'
 8296:        .&Apache::loncommon::end_data_table_header_row();
 8297: 
 8298:     my %filters=(
 8299:         start  => $curr{'accesslog_start_date'},
 8300:         end    => $curr{'accesslog_end_date'},
 8301:         action => $curr{'activity'},
 8302:     );
 8303: 
 8304:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 8305:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8306:         my (%courses,%missing);
 8307:         my @results = split(/\&/,$reply);
 8308:         foreach my $item (reverse(@results)) {
 8309:             my ($timestamp,$host,$event) = split(/:/,$item);
 8310:             next unless ($event =~ /^(Log|Role)/);
 8311:             if ($curr{'show'} !~ /\D/) {
 8312:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 8313:                     $more_records = 1;
 8314:                     last;
 8315:                 }
 8316:             }
 8317:             $count ++;
 8318:             next if ($count < $minshown);
 8319:             unless ($showntableheader) {
 8320:                 $r->print($nav_script
 8321:                          .&Apache::loncommon::start_data_table()
 8322:                          .$tableheader);
 8323:                 $r->rflush();
 8324:                 $showntableheader = 1;
 8325:             }
 8326:             my ($shown,$extra);
 8327:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 8328:             if ($event eq 'Role') {
 8329:                 my ($rolecode,$extent) = split(/\./,$data,2);
 8330:                 next if ($extent eq '');
 8331:                 my ($crstype,$desc,$info);
 8332:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 8333:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 8334:                     my $cid = $cdom.'_'.$cnum;
 8335:                     if (exists($courses{$cid})) {
 8336:                         $crstype = $courses{$cid}{'type'};
 8337:                         $desc = $courses{$cid}{'description'};
 8338:                     } elsif ($missing{$cid}) {
 8339:                         $crstype = 'Course';
 8340:                         $desc = 'Course/Community';
 8341:                     } else {
 8342:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8343:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 8344:                             $courses{$cid} = $crsinfo{$cid};
 8345:                             $crstype = $crsinfo{$cid}{'type'};
 8346:                             $desc = $crsinfo{$cid}{'description'};
 8347:                         } else {
 8348:                             $missing{$cid} = 1;
 8349:                         }
 8350:                     }
 8351:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 8352:                     if ($sec ne '') {
 8353:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 8354:                     }
 8355:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 8356:                     my ($dom,$name) = ($1,$2);
 8357:                     if ($rolecode eq 'au') {
 8358:                         $extra = '';
 8359:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 8360:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 8361:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 8362:                         $extra = &mt('Domain: [_1]',$dom);
 8363:                     }
 8364:                 }
 8365:                 my $rolename;
 8366:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 8367:                     my $role = $3;
 8368:                     my $owner = "($2:$1)";
 8369:                     if ($2 eq $1.'-domainconfig') {
 8370:                         $owner = '(ad hoc)';
 8371:                     }
 8372:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 8373:                 } else {
 8374:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 8375:                 }
 8376:                 $shown = &mt('Role selection: [_1]',$rolename);
 8377:             } else {
 8378:                 $shown = &mt($event);
 8379:                 if ($data =~ /^webdav/) {
 8380:                     my ($path,$clientip) = split(/\s+/,$data,2);
 8381:                     $path =~ s/^webdav//;
 8382:                     if ($clientip ne '') {
 8383:                         $extra = &mt('Client IP address: [_1]',$clientip);
 8384:                     }
 8385:                     if ($path ne '') {
 8386:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 8387:                     }
 8388:                 } elsif ($data ne '') {
 8389:                     $extra = &mt('Client IP address: [_1]',$data);
 8390:                 }
 8391:             }
 8392:             $r->print(
 8393:             &Apache::loncommon::start_data_table_row()
 8394:            .'<td>'.$count.'</td>'
 8395:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 8396:            .'<td>'.$host.'</td>'
 8397:            .'<td>'.$shown.'</td>'
 8398:            .'<td>'.$extra.'</td>'
 8399:            .&Apache::loncommon::end_data_table_row()."\n");
 8400:         }
 8401:     }
 8402: 
 8403:     if ($showntableheader) { # Table footer, if content displayed above
 8404:         $r->print(&Apache::loncommon::end_data_table().
 8405:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8406:     } else { # No content displayed above
 8407:         $r->print($heading.'<p class="LC_info">'
 8408:                  .&mt('There are no records to display.')
 8409:                  .'</p>');
 8410:     }
 8411: 
 8412:     if ($env{'form.popup'} == 1) {
 8413:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 8414:     }
 8415: 
 8416:     # Form Footer
 8417:     $r->print(
 8418:         '<input type="hidden" name="currstate" value="" />'
 8419:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 8420:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 8421:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8422:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 8423:        .'<input type="hidden" name="phase" value="activity" />'
 8424:        .'<input type="hidden" name="action" value="accesslogs" />'
 8425:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 8426:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 8427:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 8428:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 8429:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 8430:        .'</form>');
 8431:     return;
 8432: }
 8433: 
 8434: sub earlyout_accesslog_form {
 8435:     my ($formname,$prevphasestr,$udom) = @_;
 8436:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 8437:    return <<"END";
 8438: <form action="/adm/createuser" method="post" name="$formname">
 8439: <input type="hidden" name="currstate" value="" />
 8440: <input type="hidden" name="prevphases" value="$prevphasestr" />
 8441: <input type="hidden" name="phase" value="activity" />
 8442: <input type="hidden" name="action" value="accesslogs" />
 8443: <input type="hidden" name="srchdomain" value="$udom" />
 8444: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 8445: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 8446: <input type="hidden" name="srchterm" value="$srchterm" />
 8447: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 8448: </form>
 8449: END
 8450: }
 8451: 
 8452: sub activity_display_filter {
 8453:     my ($formname,$curr) = @_;
 8454:     my $nolink = 1;
 8455:     my $output = '<table><tr><td valign="top">'.
 8456:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 8457:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8458:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8459:                  '</td><td>&nbsp;&nbsp;</td>';
 8460:     my $startform =
 8461:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 8462:                                             $curr->{'accesslog_start_date'},undef,
 8463:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8464:     my $endform =
 8465:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 8466:                                             $curr->{'accesslog_end_date'},undef,
 8467:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8468:     my %lt = &Apache::lonlocal::texthash (
 8469:                                           activity => 'Activity',
 8470:                                           Role     => 'Role selection',
 8471:                                           log      => 'Log-in or Logout',
 8472:     );
 8473:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 8474:                '<table><tr><td>'.&mt('After:').
 8475:                '</td><td>'.$startform.'</td></tr>'.
 8476:                '<tr><td>'.&mt('Before:').'</td>'.
 8477:                '<td>'.$endform.'</td></tr></table>'.
 8478:                '</td>'.
 8479:                '<td>&nbsp;&nbsp;</td>'.
 8480:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 8481:                '<select name="activity"><option value="any"';
 8482:     if ($curr->{'activity'} eq 'any') {
 8483:         $output .= ' selected="selected"';
 8484:     }
 8485:     $output .= '>'.&mt('Any').'</option>'."\n";
 8486:     foreach my $activity ('Role','log') {
 8487:         my $selstr = '';
 8488:         if ($activity eq $curr->{'activity'}) {
 8489:             $selstr = ' selected="selected"';
 8490:         }
 8491:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 8492:     }
 8493:     $output .= '</select></td>'.
 8494:                '</tr></table>';
 8495:     # Update Display button
 8496:     $output .= '<p>'
 8497:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8498:               .'</p><hr />';
 8499:     return $output;
 8500: }
 8501: 
 8502: sub userlogdisplay_js {
 8503:     my ($formname) = @_;
 8504:     return <<"ENDSCRIPT";
 8505: 
 8506: function chgPage(caller) {
 8507:     if (caller == 'previous') {
 8508:         document.$formname.page.value --;
 8509:     }
 8510:     if (caller == 'next') {
 8511:         document.$formname.page.value ++;
 8512:     }
 8513:     document.$formname.submit();
 8514:     return;
 8515: }
 8516: ENDSCRIPT
 8517: }
 8518: 
 8519: sub userlogdisplay_navlinks {
 8520:     my ($curr,$more_records) = @_;
 8521:     return unless(ref($curr) eq 'HASH');
 8522:     # Navigation Buttons
 8523:     my $nav_links = '<p>';
 8524:     if (($curr->{'page'} > 1) || ($more_records)) {
 8525:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 8526:             $nav_links .= '<input type="button"'
 8527:                          .' onclick="javascript:chgPage('."'previous'".');"'
 8528:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 8529:                          .'" /> ';
 8530:         }
 8531:         if ($more_records) {
 8532:             $nav_links .= '<input type="button"'
 8533:                          .' onclick="javascript:chgPage('."'next'".');"'
 8534:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 8535:                          .'" />';
 8536:         }
 8537:     }
 8538:     $nav_links .= '</p>';
 8539:     return $nav_links;
 8540: }
 8541: 
 8542: sub role_display_filter {
 8543:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 8544:     my $nolink = 1;
 8545:     my $output = '<table><tr><td valign="top">'.
 8546:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 8547:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8548:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8549:                  '</td><td>&nbsp;&nbsp;</td>';
 8550:     my $startform =
 8551:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 8552:                                             $curr->{'rolelog_start_date'},undef,
 8553:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8554:     my $endform =
 8555:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 8556:                                             $curr->{'rolelog_end_date'},undef,
 8557:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8558:     my %lt = &rolechg_contexts($context,$crstype);
 8559:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 8560:                '<table><tr><td>'.&mt('After:').
 8561:                '</td><td>'.$startform.'</td></tr>'.
 8562:                '<tr><td>'.&mt('Before:').'</td>'.
 8563:                '<td>'.$endform.'</td></tr></table>'.
 8564:                '</td>'.
 8565:                '<td>&nbsp;&nbsp;</td>'.
 8566:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 8567:                '<select name="role"><option value="any"';
 8568:     if ($curr->{'role'} eq 'any') {
 8569:         $output .= ' selected="selected"';
 8570:     }
 8571:     $output .= '>'.&mt('Any').'</option>'."\n";
 8572:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 8573:     foreach my $role (@roles) {
 8574:         my $plrole;
 8575:         if ($role eq 'cr') {
 8576:             $plrole = &mt('Custom Role');
 8577:         } else {
 8578:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8579:         }
 8580:         my $selstr = '';
 8581:         if ($role eq $curr->{'role'}) {
 8582:             $selstr = ' selected="selected"';
 8583:         }
 8584:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 8585:     }
 8586:     $output .= '</select></td>'.
 8587:                '<td>&nbsp;&nbsp;</td>'.
 8588:                '<td valign="top"><b>'.
 8589:                &mt('Context:').'</b><br /><select name="chgcontext">';
 8590:     my @posscontexts;
 8591:     if ($context eq 'course') {
 8592:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype','ltienroll');
 8593:     } elsif ($context eq 'domain') {
 8594:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 8595:     } else {
 8596:         @posscontexts = ('any','author','coauthor','domain');
 8597:     }
 8598:     foreach my $chgtype (@posscontexts) {
 8599:         my $selstr = '';
 8600:         if ($curr->{'chgcontext'} eq $chgtype) {
 8601:             $selstr = ' selected="selected"';
 8602:         }
 8603:         if ($context eq 'course') {
 8604:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 8605:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 8606:             }
 8607:         }
 8608:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 8609:     }
 8610:     my @possapprovals = ('any','none','domain','user');
 8611:     my %apptxt = &approval_types();
 8612:     $output .= '</select></td>'.
 8613:                '<td>&nbsp;&nbsp;</td>'.
 8614:                '<td valign="top"><b>'.
 8615:                &mt('Approvals:').'</b><br /><select name="approvals">';
 8616:     foreach my $approval (@possapprovals) {
 8617:         my $selstr = '';
 8618:         if ($curr->{'approvals'} eq $approval) {
 8619:             $selstr = ' selected="selected"';
 8620:         }    
 8621:         $output .= '<option value="'.$approval.'"'.$selstr.'>'.$apptxt{$approval}.'</option>';
 8622:     }
 8623:     $output .= '</select></td></tr></table>';
 8624: 
 8625:     # Update Display button
 8626:     $output .= '<p>'
 8627:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8628:               .'</p>';
 8629: 
 8630:     # Server version info
 8631:     my $needsrev = '2.11.0';
 8632:     if ($context eq 'course') {
 8633:         $needsrev = '2.7.0';
 8634:     }
 8635:     
 8636:     $output .= '<p class="LC_info">'
 8637:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 8638:                   ,$needsrev);
 8639:     if ($version) {
 8640:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 8641:     }
 8642:     $output .= '</p><hr />';
 8643:     return $output;
 8644: }
 8645: 
 8646: sub rolechg_contexts {
 8647:     my ($context,$crstype) = @_;
 8648:     my %lt;
 8649:     if ($context eq 'course') {
 8650:         %lt = &Apache::lonlocal::texthash (
 8651:                                              any          => 'Any',
 8652:                                              automated    => 'Automated Enrollment',
 8653:                                              chgtype      => 'Enrollment Type/Lock Change',
 8654:                                              updatenow    => 'Roster Update',
 8655:                                              createcourse => 'Course Creation',
 8656:                                              course       => 'User Management in course',
 8657:                                              domain       => 'User Management in domain',
 8658:                                              selfenroll   => 'Self-enrolled',
 8659:                                              requestcourses => 'Course Request',
 8660:                                              ltienroll    => 'Enrollment via LTI',
 8661:                                          );
 8662:         if ($crstype eq 'Community') {
 8663:             $lt{'createcourse'} = &mt('Community Creation');
 8664:             $lt{'course'} = &mt('User Management in community');
 8665:             $lt{'requestcourses'} = &mt('Community Request');
 8666:         }
 8667:     } elsif ($context eq 'domain') {
 8668:         %lt = &Apache::lonlocal::texthash (
 8669:                                              any           => 'Any',
 8670:                                              domain        => 'User Management in domain',
 8671:                                              requestauthor => 'Authoring Request',
 8672:                                              server        => 'Command line script (DC role)',
 8673:                                              domconfig     => 'Self-enrolled',
 8674:                                          );
 8675:     } else {
 8676:         %lt = &Apache::lonlocal::texthash (
 8677:                                              any    => 'Any',
 8678:                                              domain => 'User Management in domain',
 8679:                                              author => 'User Management by author',
 8680:                                              coauthor => 'User Management by coauthor',
 8681:                                          );
 8682:     } 
 8683:     return %lt;
 8684: }
 8685: 
 8686: sub approval_types {
 8687:     return &Apache::lonlocal::texthash (
 8688:                                           any => 'Any',
 8689:                                           none => 'No approval needed',
 8690:                                           user => 'Role recipient approval',
 8691:                                           domain => 'Domain coordinator approval',
 8692:                                        );
 8693: }
 8694: 
 8695: sub print_helpdeskaccess_display {
 8696:     my ($r,$permission,$brcrum) = @_;
 8697:     my $formname = 'helpdeskaccess';
 8698:     my $helpitem = 'Course_Helpdesk_Access';
 8699:     push (@{$brcrum},
 8700:              {href => '/adm/createuser?action=helpdesk',
 8701:               text => 'Helpdesk Access',
 8702:               help => $helpitem});
 8703:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8704:     my $args = { bread_crumbs           => $brcrum,
 8705:                  bread_crumbs_component => $bread_crumbs_component};
 8706: 
 8707:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8708:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8709:     my $confname = $cdom.'-domainconfig';
 8710:     my $crstype = &Apache::loncommon::course_type();
 8711: 
 8712:     my @accesstypes = ('all','dh','da','none');
 8713:     my ($numstatustypes,@jsarray);
 8714:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8715:     if (ref($types) eq 'ARRAY') {
 8716:         if (@{$types} > 0) {
 8717:             $numstatustypes = scalar(@{$types});
 8718:             push(@accesstypes,'status');
 8719:             @jsarray = ('bystatus');
 8720:         }
 8721:     }
 8722:     my %customroles = &get_domain_customroles($cdom,$confname);
 8723:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8724:     if (keys(%domhelpdesk)) {
 8725:        push(@accesstypes,('inc','exc'));
 8726:        push(@jsarray,('notinc','notexc'));
 8727:     }
 8728:     push(@jsarray,'privs');
 8729:     my $hiddenstr = join("','",@jsarray);
 8730:     my $rolestr = join("','",sort(keys(%customroles)));
 8731: 
 8732:     my $jscript;
 8733:     my (%settings,%overridden);
 8734:     if (keys(%customroles)) {
 8735:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8736:                                 $types,\%customroles,\%settings,\%overridden);
 8737:         my %jsfull=();
 8738:         my %jslevels= (
 8739:                      course => {},
 8740:                      domain => {},
 8741:                      system => {},
 8742:                     );
 8743:         my %jslevelscurrent=(
 8744:                            course => {},
 8745:                            domain => {},
 8746:                            system => {},
 8747:                           );
 8748:         my (%privs,%jsprivs);
 8749:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 8750:         foreach my $priv (keys(%jsfull)) {
 8751:             if ($jslevels{'course'}{$priv}) {
 8752:                 $jsprivs{$priv} = 1;
 8753:             }
 8754:         }
 8755:         my (%elements,%stored);
 8756:         foreach my $role (keys(%customroles)) {
 8757:             $elements{$role.'_access'} = 'radio';
 8758:             $elements{$role.'_incrs'} = 'radio';
 8759:             if ($numstatustypes) {
 8760:                 $elements{$role.'_status'} = 'checkbox';
 8761:             }
 8762:             if (keys(%domhelpdesk) > 0) {
 8763:                 $elements{$role.'_staff_inc'} = 'checkbox';
 8764:                 $elements{$role.'_staff_exc'} = 'checkbox';
 8765:             }
 8766:             $elements{$role.'_override'} = 'checkbox';
 8767:             if (ref($settings{$role}) eq 'HASH') {
 8768:                 if ($settings{$role}{'access'} ne '') {
 8769:                     my $curraccess = $settings{$role}{'access'};
 8770:                     $stored{$role.'_access'} = $curraccess;
 8771:                     $stored{$role.'_incrs'} = 1;
 8772:                     if ($curraccess eq 'status') {
 8773:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 8774:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 8775:                         }
 8776:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8777:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 8778:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 8779:                         }
 8780:                     }
 8781:                 } else {
 8782:                     $stored{$role.'_incrs'} = 0;
 8783:                 }
 8784:                 $stored{$role.'_override'} = [];
 8785:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 8786:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 8787:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 8788:                             push(@{$stored{$role.'_override'}},$priv);
 8789:                         }
 8790:                     }
 8791:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 8792:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 8793:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 8794:                                 push(@{$stored{$role.'_override'}},$priv);
 8795:                             }
 8796:                         }
 8797:                     }
 8798:                 }
 8799:             } else {
 8800:                 $stored{$role.'_incrs'} = 0;
 8801:             }
 8802:         }
 8803:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 8804:     }
 8805: 
 8806:     my $js = <<"ENDJS";
 8807: <script type="text/javascript">
 8808: // <![CDATA[
 8809: $jscript;
 8810: 
 8811: function switchRoleTab(caller,role) {
 8812:     if (document.getElementById(role+'_maindiv')) {
 8813:         if (caller.id != 'LC_current_minitab') {
 8814:             if (document.getElementById('LC_current_minitab')) {
 8815:                 document.getElementById('LC_current_minitab').id=null;
 8816:             }
 8817:             var roledivs = Array('$rolestr');
 8818:             if (roledivs.length > 0) {
 8819:                 for (var i=0; i<roledivs.length; i++) {
 8820:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 8821:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 8822:                     }
 8823:                 }
 8824:             }
 8825:             caller.id = 'LC_current_minitab';
 8826:             document.getElementById(role+'_maindiv').style.display='block';
 8827:         }
 8828:     }
 8829:     return false;
 8830: }
 8831: 
 8832: function helpdeskAccess(role) {
 8833:     var curraccess = null;
 8834:     if (document.$formname.elements[role+'_access'].length) {
 8835:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 8836:             if (document.$formname.elements[role+'_access'][i].checked) {
 8837:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 8838:             }
 8839:         }
 8840:     }
 8841:     var shown = Array();
 8842:     var hidden = Array();
 8843:     if (curraccess == 'none') {
 8844:         hidden = Array ('$hiddenstr');
 8845:     } else {
 8846:         if (curraccess == 'status') {
 8847:             shown = Array ('bystatus','privs');
 8848:             hidden = Array ('notinc','notexc');
 8849:         } else {
 8850:             if (curraccess == 'exc') {
 8851:                 shown = Array ('notexc','privs');
 8852:                 hidden = Array ('notinc','bystatus');
 8853:             }
 8854:             if (curraccess == 'inc') {
 8855:                 shown = Array ('notinc','privs');
 8856:                 hidden = Array ('notexc','bystatus');
 8857:             }
 8858:             if (curraccess == 'all') {
 8859:                 shown = Array ('privs');
 8860:                 hidden = Array ('notinc','notexc','bystatus');
 8861:             }
 8862:         }
 8863:     }
 8864:     if (hidden.length > 0) {
 8865:         for (var i=0; i<hidden.length; i++) {
 8866:             if (document.getElementById(role+'_'+hidden[i])) {
 8867:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 8868:             }
 8869:         }
 8870:     }
 8871:     if (shown.length > 0) {
 8872:         for (var i=0; i<shown.length; i++) {
 8873:             if (document.getElementById(role+'_'+shown[i])) {
 8874:                 if (shown[i] == 'privs') {
 8875:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 8876:                 } else {
 8877:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 8878:                 }
 8879:             }
 8880:         }
 8881:     }
 8882:     return;
 8883: }
 8884: 
 8885: function toggleAccess(role) {
 8886:     if ((document.getElementById(role+'_setincrs')) &&
 8887:         (document.getElementById(role+'_setindom'))) {
 8888:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 8889:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 8890:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 8891:                     document.getElementById(role+'_setindom').style.display = 'none';
 8892:                     document.getElementById(role+'_setincrs').style.display = 'block';
 8893:                 } else {
 8894:                     document.getElementById(role+'_setincrs').style.display = 'none';
 8895:                     document.getElementById(role+'_setindom').style.display = 'block';
 8896:                 }
 8897:                 break;
 8898:             }
 8899:         }
 8900:     }
 8901:     return;
 8902: }
 8903: 
 8904: // ]]>
 8905: </script>
 8906: ENDJS
 8907: 
 8908:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 8909: 
 8910:     # print page header
 8911:     $r->print(&header($js,$args));
 8912:     # print form header
 8913:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 8914: 
 8915:     if (keys(%customroles)) {
 8916:         my %lt = &Apache::lonlocal::texthash(
 8917:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 8918:                     'rou'    => 'Role usage',
 8919:                     'whi'    => 'Which helpdesk personnel may use this role?',
 8920:                     'udd'    => 'Use domain default',
 8921:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 8922:                     'dh'     => 'All with domain helpdesk role',
 8923:                     'da'     => 'All with domain helpdesk assistant role',
 8924:                     'none'   => 'None',
 8925:                     'status' => 'Determined based on institutional status',
 8926:                     'inc'    => 'Include all, but exclude specific personnel',
 8927:                     'exc'    => 'Exclude all, but include specific personnel',
 8928:                     'hel'    => 'Helpdesk',
 8929:                     'rpr'    => 'Role privileges',
 8930:                  );
 8931:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 8932:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8933:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 8934:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8935:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8936:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8937:             }
 8938:         }
 8939:         my $count = 0;
 8940:         foreach my $role (sort(keys(%customroles))) {
 8941:             my ($order,$desc,$access_in_dom);
 8942:             if (ref($domcurrent{$role}) eq 'HASH') {
 8943:                 $order = $domcurrent{$role}{'order'};
 8944:                 $desc = $domcurrent{$role}{'desc'};
 8945:                 $access_in_dom = $domcurrent{$role}{'access'};
 8946:             }
 8947:             if ($order eq '') {
 8948:                 $order = $count;
 8949:             }
 8950:             $ordered{$order} = $role;
 8951:             if ($desc ne '') {
 8952:                 $description{$role} = $desc;
 8953:             } else {
 8954:                 $description{$role}= $role;
 8955:             }
 8956:             $count++;
 8957:         }
 8958:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8959:         my @roles_by_num = ();
 8960:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8961:             push(@roles_by_num,$ordered{$item});
 8962:         }
 8963:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 8964:         if ($permission->{'owner'}) {
 8965:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 8966:             $r->print('<input type="hidden" name="state" value="process" />'.
 8967:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 8968:         } else {
 8969:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 8970:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 8971:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 8972:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 8973:             }
 8974:             $disabled = ' disabled="disabled"';
 8975:         }
 8976:         $r->print('</p>');
 8977: 
 8978:         $r->print('<div id="LC_minitab_header"><ul>');
 8979:         my $count = 0;
 8980:         my %visibility;
 8981:         foreach my $role (@roles_by_num) {
 8982:             my $id;
 8983:             if ($count == 0) {
 8984:                 $id=' id="LC_current_minitab"';
 8985:                 $visibility{$role} = ' style="display:block"';
 8986:             } else {
 8987:                 $visibility{$role} = ' style="display:none"';
 8988:             }
 8989:             $count ++;
 8990:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 8991:         }
 8992:         $r->print('</ul></div>');
 8993: 
 8994:         foreach my $role (@roles_by_num) {
 8995:             my %usecheck = (
 8996:                              all => ' checked="checked"',
 8997:                            );
 8998:             my %displaydiv = (
 8999:                                 status => 'none',
 9000:                                 inc    => 'none',
 9001:                                 exc    => 'none',
 9002:                                 priv   => 'block',
 9003:                              );
 9004:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 9005:             if (ref($settings{$role}) eq 'HASH') {
 9006:                 if ($settings{$role}{'access'} ne '') {
 9007:                     $indomvis = ' style="display:none"';
 9008:                     $incrsvis = ' style="display:block"';
 9009:                     $incrscheck = ' checked="checked"';
 9010:                     if ($settings{$role}{'access'} ne 'all') {
 9011:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 9012:                         delete($usecheck{'all'});
 9013:                         if ($settings{$role}{'access'} eq 'status') {
 9014:                             my $access = 'status';
 9015:                             $displaydiv{$access} = 'inline';
 9016:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9017:                                 $selected{$access} = $settings{$role}{$access};
 9018:                             }
 9019:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 9020:                             my $access = $1;
 9021:                             $displaydiv{$access} = 'inline';
 9022:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9023:                                 $selected{$access} = $settings{$role}{$access};
 9024:                             }
 9025:                         } elsif ($settings{$role}{'access'} eq 'none') {
 9026:                             $displaydiv{'priv'} = 'none';
 9027:                         }
 9028:                     }
 9029:                 } else {
 9030:                     $indomcheck = ' checked="checked"';
 9031:                     $indomvis = ' style="display:block"';
 9032:                     $incrsvis = ' style="display:none"';
 9033:                 }
 9034:             } else {
 9035:                 $indomcheck = ' checked="checked"';
 9036:                 $indomvis = ' style="display:block"';
 9037:                 $incrsvis = ' style="display:none"';
 9038:             }
 9039:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 9040:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 9041:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 9042:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9043:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 9044:                       '<span>'.('&nbsp;'x2).
 9045:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9046:                       $lt{'udd'}.'</label><span></p>'.
 9047:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 9048:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 9049:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 9050:             foreach my $access (@accesstypes) {
 9051:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 9052:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 9053:                 if ($access eq 'status') {
 9054:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 9055:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 9056:                                                                         $othertitle,$usertypes,$types,$disabled).
 9057:                               '</div>');
 9058:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 9059:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 9060:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9061:                                                                  \%domhelpdesk,$disabled).
 9062:                               '</div>');
 9063:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 9064:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 9065:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9066:                                                                  \%domhelpdesk,$disabled).
 9067:                               '</div>');
 9068:                 }
 9069:                 $r->print('</p>');
 9070:             }
 9071:             $r->print('</div></fieldset>');
 9072:             my %full=();
 9073:             my %levels= (
 9074:                          course => {},
 9075:                          domain => {},
 9076:                          system => {},
 9077:                         );
 9078:             my %levelscurrent=(
 9079:                                course => {},
 9080:                                domain => {},
 9081:                                system => {},
 9082:                               );
 9083:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9084:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 9085:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 9086:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 9087:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 9088:         }
 9089:         if ($permission->{'owner'}) {
 9090:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 9091:         }
 9092:     } else {
 9093:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 9094:     }
 9095:     # Form Footer
 9096:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 9097:              .'</form>');
 9098:     return;
 9099: }
 9100: 
 9101: sub print_queued_roles {
 9102:     my ($r,$context,$permission,$brcrum) = @_;
 9103:     push (@{$brcrum},
 9104:              {href => '/adm/createuser?action=rolerequests',
 9105:               text => 'Role Requests (other domains)',
 9106:               help => ''});
 9107:     my $bread_crumbs_component = 'Role Requests';
 9108:     my $args = { bread_crumbs           => $brcrum,
 9109:                  bread_crumbs_component => $bread_crumbs_component};
 9110:     # print page header
 9111:     $r->print(&header('',$args));
 9112:     my ($dom,$cnum);
 9113:     $dom = $env{'request.role.domain'};
 9114:     if ($context eq 'course') {
 9115:         if ($env{'request.course.id'}) {
 9116:             if (&Apache::loncommon::course_type() eq 'Community') {
 9117:                 $context = 'community';
 9118:             }
 9119:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9120:         }
 9121:     } elsif ($context eq 'author') {
 9122:         $cnum = $env{'user.name'};
 9123:     }
 9124:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomqueue',$dom,$cnum,$context));
 9125:     return;
 9126: }
 9127: 
 9128: sub print_pendingroles {
 9129:     my ($r,$context,$permission,$brcrum) = @_;
 9130:     push (@{$brcrum},
 9131:              {href => '/adm/createuser?action=queuedroles',
 9132:               text => 'Queued Role Assignments (users in this domain)',
 9133:               help => ''});
 9134:     my $bread_crumbs_component = 'Queued Role Assignments';
 9135:     my $args = { bread_crumbs           => $brcrum,
 9136:                  bread_crumbs_component => $bread_crumbs_component};
 9137:     # print page header
 9138:     $r->print(&header('',$args));
 9139:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomaction',$env{'request.role.domain'},'','domain'));
 9140:     return;
 9141: }
 9142: 
 9143: sub process_pendingroles {
 9144:     my ($r,$context,$permission,$brcrum) = @_;
 9145:     push (@{$brcrum},
 9146:              {href => '/adm/createuser?action=queuedroles',
 9147:               text => 'Queued Role Assignments (users in this domain)',
 9148:               help => ''},
 9149:              {href => '/adm/createuser?action=processrolereq',
 9150:               text => 'Process Queue',
 9151:               help => ''});
 9152:     my $bread_crumbs_component = 'Queued Role Assignments';
 9153:     my $args = { bread_crumbs           => $brcrum,
 9154:                  bread_crumbs_component => $bread_crumbs_component};
 9155:     # print page header
 9156:     $r->print(&header('',$args));
 9157:     $r->print(&Apache::loncoursequeueadmin::update_request_queue('othdombydc',
 9158:                                                                  $env{'request.role.domain'}));
 9159:     return;
 9160: }
 9161: 
 9162: sub domain_adhoc_access {
 9163:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 9164:     my %domusage;
 9165:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 9166:     foreach my $role (keys(%{$roles})) {
 9167:         if (ref($domcurrent->{$role}) eq 'HASH') {
 9168:             my $access = $domcurrent->{$role}{'access'};
 9169:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 9170:                 $access = 'all';
 9171:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 9172:                                                                                           &Apache::lonnet::plaintext('da'));
 9173:             } elsif ($access eq 'status') {
 9174:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 9175:                     my @shown;
 9176:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 9177:                         unless ($type eq 'default') {
 9178:                             if ($usertypes->{$type}) {
 9179:                                 push(@shown,$usertypes->{$type});
 9180:                             }
 9181:                         }
 9182:                     }
 9183:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 9184:                         push(@shown,$othertitle);
 9185:                     }
 9186:                     if (@shown) {
 9187:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 9188:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 9189:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 9190:                     } else {
 9191:                         $domusage{$role} = &mt('No one in the domain');
 9192:                     }
 9193:                 }
 9194:             } elsif ($access eq 'inc') {
 9195:                 my @dominc = ();
 9196:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 9197:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 9198:                         my ($uname,$udom) = split(/:/,$user);
 9199:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9200:                     }
 9201:                     my $showninc = join(', ',@dominc);
 9202:                     if ($showninc ne '') {
 9203:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 9204:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 9205:                     } else {
 9206:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9207:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9208:                     }
 9209:                 }
 9210:             } elsif ($access eq 'exc') {
 9211:                 my @domexc = ();
 9212:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 9213:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 9214:                         my ($uname,$udom) = split(/:/,$user);
 9215:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9216:                     }
 9217:                 }
 9218:                 my $shownexc = join(', ',@domexc);
 9219:                 if ($shownexc ne '') {
 9220:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 9221:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 9222:                 } else {
 9223:                     $domusage{$role} = &mt('No one in the domain');
 9224:                 }
 9225:             } elsif ($access eq 'none') {
 9226:                 $domusage{$role} = &mt('No one in the domain');
 9227:             } elsif ($access eq 'dh') {
 9228:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 9229:             } elsif ($access eq 'da') {
 9230:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 9231:             } elsif ($access eq 'all') {
 9232:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9233:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9234:             }
 9235:         } else {
 9236:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9237:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9238:         }
 9239:     }
 9240:     return %domusage;
 9241: }
 9242: 
 9243: sub get_domain_customroles {
 9244:     my ($cdom,$confname) = @_;
 9245:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 9246:     my %customroles;
 9247:     foreach my $key (keys(%existing)) {
 9248:         if ($key=~/^rolesdef\_(\w+)$/) {
 9249:             my $rolename = $1;
 9250:             my %privs;
 9251:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 9252:             $customroles{$rolename} = \%privs;
 9253:         }
 9254:     }
 9255:     return %customroles;
 9256: }
 9257: 
 9258: sub role_priv_table {
 9259:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 9260:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 9261:                    (ref($levelscurrent) eq 'HASH'));
 9262:     my %lt=&Apache::lonlocal::texthash (
 9263:                     'crl'  => 'Course Level Privilege',
 9264:                     'def'  => 'Domain Defaults',
 9265:                     'ove'  => 'Override in Course',
 9266:                     'ine'  => 'In effect',
 9267:                     'dis'  => 'Disabled',
 9268:                     'ena'  => 'Enabled',
 9269:                    );
 9270:     if ($crstype eq 'Community') {
 9271:         $lt{'ove'} = 'Override in Community',
 9272:     }
 9273:     my @status = ('Disabled','Enabled');
 9274:     my (%on,%off);
 9275:     if (ref($overridden) eq 'HASH') {
 9276:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 9277:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 9278:         }
 9279:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 9280:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 9281:         }
 9282:     }
 9283:     my $output=&Apache::loncommon::start_data_table().
 9284:                &Apache::loncommon::start_data_table_header_row().
 9285:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 9286:                '</th><th>'.$lt{'ine'}.'</th>'.
 9287:                &Apache::loncommon::end_data_table_header_row();
 9288:     foreach my $priv (sort(keys(%{$full}))) {
 9289:         next unless ($levels->{'course'}{$priv});
 9290:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 9291:         my ($default,$ineffect);
 9292:         if ($levelscurrent->{'course'}{$priv}) {
 9293:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9294:             $ineffect = $default;
 9295:         }
 9296:         my ($customstatus,$checked);
 9297:         $output .= &Apache::loncommon::start_data_table_row().
 9298:                    '<td>'.$privtext.'</td>'.
 9299:                    '<td>'.$default.'</td><td>';
 9300:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 9301:             if ($permission->{'owner'}) {
 9302:                 $checked = ' checked="checked"';
 9303:             }
 9304:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 9305:             $ineffect = $customstatus;
 9306:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 9307:             if ($permission->{'owner'}) {
 9308:                 $checked = ' checked="checked"';
 9309:             }
 9310:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9311:             $ineffect = $customstatus;
 9312:         }
 9313:         if ($permission->{'owner'}) {
 9314:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 9315:         } else {
 9316:             $output .= $customstatus;
 9317:         }
 9318:         $output .= '</td><td>'.$ineffect.'</td>'.
 9319:                    &Apache::loncommon::end_data_table_row();
 9320:     }
 9321:     $output .= &Apache::loncommon::end_data_table();
 9322:     return $output;
 9323: }
 9324: 
 9325: sub get_adhocrole_settings {
 9326:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 9327:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 9328:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 9329:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 9330:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 9331:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 9332:             $settings->{$role}{'access'} = $curraccess;
 9333:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 9334:                 my @status = split(/,/,$rest);
 9335:                 my @currstatus;
 9336:                 foreach my $type (@status) {
 9337:                     if ($type eq 'default') {
 9338:                         push(@currstatus,$type);
 9339:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9340:                         push(@currstatus,$type);
 9341:                     }
 9342:                 }
 9343:                 if (@currstatus) {
 9344:                     $settings->{$role}{$curraccess} = \@currstatus;
 9345:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 9346:                     my @personnel = split(/,/,$rest);
 9347:                     $settings->{$role}{$curraccess} = \@personnel;
 9348:                 }
 9349:             }
 9350:         }
 9351:     }
 9352:     foreach my $role (keys(%{$customroles})) {
 9353:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 9354:             my %currentprivs;
 9355:             if (ref($customroles->{$role}) eq 'HASH') {
 9356:                 if (exists($customroles->{$role}{'course'})) {
 9357:                     my %full=();
 9358:                     my %levels= (
 9359:                                   course => {},
 9360:                                   domain => {},
 9361:                                   system => {},
 9362:                                 );
 9363:                     my %levelscurrent=(
 9364:                                         course => {},
 9365:                                         domain => {},
 9366:                                         system => {},
 9367:                                       );
 9368:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 9369:                     %currentprivs = %{$levelscurrent{'course'}};
 9370:                 }
 9371:             }
 9372:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 9373:                 next if ($item eq '');
 9374:                 my ($rule,$rest) = split(/=/,$item);
 9375:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 9376:                 foreach my $priv (split(/:/,$rest)) {
 9377:                     if ($priv ne '') {
 9378:                         if ($rule eq 'off') {
 9379:                             push(@{$overridden->{$role}{'off'}},$priv);
 9380:                             if ($currentprivs{$priv}) {
 9381:                                 push(@{$settings->{$role}{'off'}},$priv);
 9382:                             }
 9383:                         } else {
 9384:                             push(@{$overridden->{$role}{'on'}},$priv);
 9385:                             unless ($currentprivs{$priv}) {
 9386:                                 push(@{$settings->{$role}{'on'}},$priv);
 9387:                             }
 9388:                         }
 9389:                     }
 9390:                 }
 9391:             }
 9392:         }
 9393:     }
 9394:     return;
 9395: }
 9396: 
 9397: sub update_helpdeskaccess {
 9398:     my ($r,$permission,$brcrum) = @_;
 9399:     my $helpitem = 'Course_Helpdesk_Access';
 9400:     push (@{$brcrum},
 9401:              {href => '/adm/createuser?action=helpdesk',
 9402:               text => 'Helpdesk Access',
 9403:               help => $helpitem},
 9404:              {href => '/adm/createuser?action=helpdesk',
 9405:               text => 'Result',
 9406:               help => $helpitem}
 9407:          );
 9408:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 9409:     my $args = { bread_crumbs           => $brcrum,
 9410:                  bread_crumbs_component => $bread_crumbs_component};
 9411: 
 9412:     # print page header
 9413:     $r->print(&header('',$args));
 9414:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 9415:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 9416:         return;
 9417:     }
 9418:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 9419:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9420:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9421:     my $confname = $cdom.'-domainconfig';
 9422:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 9423:     my $crstype = &Apache::loncommon::course_type();
 9424:     my %customroles = &get_domain_customroles($cdom,$confname);
 9425:     my (%settings,%overridden);
 9426:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 9427:                             $types,\%customroles,\%settings,\%overridden);
 9428:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 9429:     my (%changed,%storehash,@todelete);
 9430: 
 9431:     if (keys(%customroles)) {
 9432:         my (%newsettings,@incrs);
 9433:         foreach my $role (keys(%customroles)) {
 9434:             $newsettings{$role} = {
 9435:                                     access => '',
 9436:                                     status => '',
 9437:                                     exc    => '',
 9438:                                     inc    => '',
 9439:                                     on     => '',
 9440:                                     off    => '',
 9441:                                   };
 9442:             my %current;
 9443:             if (ref($settings{$role}) eq 'HASH') {
 9444:                 %current = %{$settings{$role}};
 9445:             }
 9446:             if (ref($overridden{$role}) eq 'HASH') {
 9447:                 $current{'overridden'} = $overridden{$role};
 9448:             }
 9449:             if ($env{'form.'.$role.'_incrs'}) {
 9450:                 my $access = $env{'form.'.$role.'_access'};
 9451:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 9452:                     push(@incrs,$role);
 9453:                     unless ($current{'access'} eq $access) {
 9454:                         $changed{$role}{'access'} = 1;
 9455:                         $storehash{'internal.adhoc.'.$role} = $access;
 9456:                     }
 9457:                     if ($access eq 'status') {
 9458:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 9459:                         my @stored;
 9460:                         my @shownstatus;
 9461:                         if (ref($types) eq 'ARRAY') {
 9462:                             foreach my $type (sort(@statuses)) {
 9463:                                 if ($type eq 'default') {
 9464:                                     push(@stored,$type);
 9465:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9466:                                     push(@stored,$type);
 9467:                                     push(@shownstatus,$usertypes->{$type});
 9468:                                 }
 9469:                             }
 9470:                             if (grep(/^default$/,@statuses)) {
 9471:                                 push(@shownstatus,$othertitle);
 9472:                             }
 9473:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9474:                         }
 9475:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 9476:                         if (ref($current{'status'}) eq 'ARRAY') {
 9477:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 9478:                             if (@diffs) {
 9479:                                 $changed{$role}{'status'} = 1;
 9480:                             }
 9481:                         } elsif (@stored) {
 9482:                             $changed{$role}{'status'} = 1;
 9483:                         }
 9484:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 9485:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 9486:                         my @newspecstaff;
 9487:                         my @stored;
 9488:                         my @currstaff;
 9489:                         foreach my $person (sort(@personnel)) {
 9490:                             if ($domhelpdesk{$person}) {
 9491:                                 push(@stored,$person);
 9492:                             }
 9493:                         }
 9494:                         if (ref($current{$access}) eq 'ARRAY') {
 9495:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 9496:                             if (@diffs) {
 9497:                                 $changed{$role}{$access} = 1;
 9498:                             }
 9499:                         } elsif (@stored) {
 9500:                             $changed{$role}{$access} = 1;
 9501:                         }
 9502:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9503:                         foreach my $person (@stored) {
 9504:                             my ($uname,$udom) = split(/:/,$person);
 9505:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 9506:                         }
 9507:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 9508:                     }
 9509:                     $newsettings{$role}{'access'} = $access;
 9510:                 }
 9511:             } else {
 9512:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 9513:                     $changed{$role}{'access'} = 1;
 9514:                     $newsettings{$role} = {};
 9515:                     push(@todelete,'internal.adhoc.'.$role);
 9516:                 }
 9517:             }
 9518:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 9519:                 if (ref($current{'overridden'}) eq 'HASH') {
 9520:                     push(@todelete,'internal.adhocpriv.'.$role);
 9521:                 }
 9522:             } else {
 9523:                 my %full=();
 9524:                 my %levels= (
 9525:                              course => {},
 9526:                              domain => {},
 9527:                              system => {},
 9528:                             );
 9529:                 my %levelscurrent=(
 9530:                                    course => {},
 9531:                                    domain => {},
 9532:                                    system => {},
 9533:                                   );
 9534:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9535:                 my (@updatedon,@updatedoff,@override);
 9536:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 9537:                 if (@override) {
 9538:                     foreach my $priv (sort(keys(%full))) {
 9539:                         next unless ($levels{'course'}{$priv});
 9540:                         if (grep(/^\Q$priv\E$/,@override)) {
 9541:                             if ($levelscurrent{'course'}{$priv}) {
 9542:                                 push(@updatedoff,$priv);
 9543:                             } else {
 9544:                                 push(@updatedon,$priv);
 9545:                             }
 9546:                         }
 9547:                     }
 9548:                 }
 9549:                 if (@updatedon) {
 9550:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 9551:                 }
 9552:                 if (@updatedoff) {
 9553:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 9554:                 }
 9555:                 if (ref($current{'overridden'}) eq 'HASH') {
 9556:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 9557:                         if (@updatedon) {
 9558:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 9559:                             if (@diffs) {
 9560:                                 $changed{$role}{'on'} = 1;
 9561:                             }
 9562:                         } else {
 9563:                             $changed{$role}{'on'} = 1;
 9564:                         }
 9565:                     } elsif (@updatedon) {
 9566:                         $changed{$role}{'on'} = 1;
 9567:                     }
 9568:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 9569:                         if (@updatedoff) {
 9570:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 9571:                             if (@diffs) {
 9572:                                 $changed{$role}{'off'} = 1;
 9573:                             }
 9574:                         } else {
 9575:                             $changed{$role}{'off'} = 1;
 9576:                         }
 9577:                     } elsif (@updatedoff) {
 9578:                         $changed{$role}{'off'} = 1;
 9579:                     }
 9580:                 } else {
 9581:                     if (@updatedon) {
 9582:                         $changed{$role}{'on'} = 1;
 9583:                     }
 9584:                     if (@updatedoff) {
 9585:                         $changed{$role}{'off'} = 1;
 9586:                     }
 9587:                 }
 9588:                 if (ref($changed{$role}) eq 'HASH') {
 9589:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 9590:                         my $newpriv;
 9591:                         if (@updatedon) {
 9592:                             $newpriv = 'on='.join(':',@updatedon);
 9593:                         }
 9594:                         if (@updatedoff) {
 9595:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 9596:                         }
 9597:                         if ($newpriv eq '') {
 9598:                             push(@todelete,'internal.adhocpriv.'.$role);
 9599:                         } else {
 9600:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 9601:                         }
 9602:                     }
 9603:                 }
 9604:             }
 9605:         }
 9606:         if (@incrs) {
 9607:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 9608:         } elsif (@todelete) {
 9609:             push(@todelete,'internal.adhocaccess');
 9610:         }
 9611:         if (keys(%changed)) {
 9612:             my ($putres,$delres);
 9613:             if (keys(%storehash)) {
 9614:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 9615:                 my %newenvhash;
 9616:                 foreach my $key (keys(%storehash)) {
 9617:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 9618:                 }
 9619:                 &Apache::lonnet::appenv(\%newenvhash);
 9620:             }
 9621:             if (@todelete) {
 9622:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 9623:                 foreach my $key (@todelete) {
 9624:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 9625:                 }
 9626:             }
 9627:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 9628:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9629:                 my (%domcurrent,%ordered,%description,%domusage);
 9630:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9631:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9632:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9633:                     }
 9634:                 }
 9635:                 my $count = 0;
 9636:                 foreach my $role (sort(keys(%customroles))) {
 9637:                     my ($order,$desc);
 9638:                     if (ref($domcurrent{$role}) eq 'HASH') {
 9639:                         $order = $domcurrent{$role}{'order'};
 9640:                         $desc = $domcurrent{$role}{'desc'};
 9641:                     }
 9642:                     if ($order eq '') {
 9643:                         $order = $count;
 9644:                     }
 9645:                     $ordered{$order} = $role;
 9646:                     if ($desc ne '') {
 9647:                         $description{$role} = $desc;
 9648:                     } else {
 9649:                         $description{$role}= $role;
 9650:                     }
 9651:                     $count++;
 9652:                 }
 9653:                 my @roles_by_num = ();
 9654:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9655:                     push(@roles_by_num,$ordered{$item});
 9656:                 }
 9657:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9658:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 9659:                 $r->print('<ul>');
 9660:                 foreach my $role (@roles_by_num) {
 9661:                     next unless (ref($changed{$role}) eq 'HASH');
 9662:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 9663:                               '<ul>');
 9664:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 9665:                         $r->print('<li>');
 9666:                         if ($env{'form.'.$role.'_incrs'}) {
 9667:                             if ($newsettings{$role}{'access'} eq 'all') {
 9668:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 9669:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 9670:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9671:                                               &Apache::lonnet::plaintext('dh')));
 9672:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 9673:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9674:                                               &Apache::lonnet::plaintext('da')));
 9675:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 9676:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9677:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 9678:                                 if ($newsettings{$role}{'status'}) {
 9679:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 9680:                                     if (split(/,/,$rest) > 1) {
 9681:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 9682:                                                       $newsettings{$role}{'status'}));
 9683:                                     } else {
 9684:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 9685:                                                       $newsettings{$role}{'status'}));
 9686:                                     }
 9687:                                 } else {
 9688:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9689:                                 }
 9690:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 9691:                                 if ($newsettings{$role}{'exc'}) {
 9692:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 9693:                                 } else {
 9694:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9695:                                 }
 9696:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 9697:                                 if ($newsettings{$role}{'inc'}) {
 9698:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 9699:                                 } else {
 9700:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 9701:                                 }
 9702:                             }
 9703:                         } else {
 9704:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 9705:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 9706:                         }
 9707:                         $r->print('</li>');
 9708:                     }
 9709:                     unless ($newsettings{$role}{'access'} eq 'none') {
 9710:                         if ($changed{$role}{'off'}) {
 9711:                             if ($newsettings{$role}{'off'}) {
 9712:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 9713:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 9714:                             } else {
 9715:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 9716:                             }
 9717:                         }
 9718:                         if ($changed{$role}{'on'}) {
 9719:                             if ($newsettings{$role}{'on'}) {
 9720:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 9721:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 9722:                             } else {
 9723:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 9724:                             }
 9725:                         }
 9726:                     }
 9727:                     $r->print('</ul></li>');
 9728:                 }
 9729:                 $r->print('</ul>');
 9730:             }
 9731:         } else {
 9732:             $r->print(&mt('No changes made to helpdesk access settings.'));
 9733:         }
 9734:     }
 9735:     return;
 9736: }
 9737: 
 9738: #-------------------------------------------------- functions for &phase_two
 9739: sub user_search_result {
 9740:     my ($context,$srch) = @_;
 9741:     my %allhomes;
 9742:     my %inst_matches;
 9743:     my %srch_results;
 9744:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 9745:     $srch->{'srchterm'} =~ s/\s+/ /g;
 9746:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 9747:         $response = &mt('Invalid search.');
 9748:     }
 9749:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 9750:         $response = &mt('Invalid search.');
 9751:     }
 9752:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 9753:         $response = &mt('Invalid search.');
 9754:     }
 9755:     if ($srch->{'srchterm'} eq '') {
 9756:         $response = &mt('You must enter a search term.');
 9757:     }
 9758:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 9759:         $response = &mt('Your search term must contain more than just spaces.');
 9760:     }
 9761:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 9762:         if (($srch->{'srchdomain'} eq '') || 
 9763: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 9764:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 9765:         }
 9766:     }
 9767:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 9768:         ($srch->{'srchin'} eq 'alc')) {
 9769:         if ($srch->{'srchby'} eq 'uname') {
 9770:             my $unamecheck = $srch->{'srchterm'};
 9771:             if ($srch->{'srchtype'} eq 'contains') {
 9772:                 if ($unamecheck !~ /^\w/) {
 9773:                     $unamecheck = 'a'.$unamecheck; 
 9774:                 }
 9775:             }
 9776:             if ($unamecheck !~ /^$match_username$/) {
 9777:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 9778:             }
 9779:         }
 9780:     }
 9781:     if ($response ne '') {
 9782:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 9783:     }
 9784:     if ($srch->{'srchin'} eq 'instd') {
 9785:         my $instd_chk = &instdirectorysrch_check($srch);
 9786:         if ($instd_chk ne 'ok') {
 9787:             my $domd_chk = &domdirectorysrch_check($srch);
 9788:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 9789:             if ($domd_chk eq 'ok') {
 9790:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 9791:             }
 9792:             $response .= '<br />';
 9793:         }
 9794:     } else {
 9795:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 9796:             my $domd_chk = &domdirectorysrch_check($srch);
 9797:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 9798:                 my $instd_chk = &instdirectorysrch_check($srch);
 9799:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 9800:                 if ($instd_chk eq 'ok') {
 9801:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 9802:                 }
 9803:                 $response .= '<br />';
 9804:             }
 9805:         }
 9806:     }
 9807:     if ($response ne '') {
 9808:         return ($currstate,$response);
 9809:     }
 9810:     if ($srch->{'srchby'} eq 'uname') {
 9811:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 9812:             if ($env{'form.forcenew'}) {
 9813:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 9814:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9815:                     if ($uhome eq 'no_host') {
 9816:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 9817:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 9818:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 9819:                     } else {
 9820:                         $currstate = 'modify';
 9821:                     }
 9822:                 } else {
 9823:                     $currstate = 'modify';
 9824:                 }
 9825:             } else {
 9826:                 if ($srch->{'srchin'} eq 'dom') {
 9827:                     if ($srch->{'srchtype'} eq 'exact') {
 9828:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9829:                         if ($uhome eq 'no_host') {
 9830:                             ($currstate,$response,$forcenewuser) =
 9831:                                 &build_search_response($context,$srch,%srch_results);
 9832:                         } else {
 9833:                             $currstate = 'modify';
 9834:                             if ($env{'form.action'} eq 'accesslogs') {
 9835:                                 $currstate = 'activity';
 9836:                             }
 9837:                             my $uname = $srch->{'srchterm'};
 9838:                             my $udom = $srch->{'srchdomain'};
 9839:                             $srch_results{$uname.':'.$udom} =
 9840:                                 { &Apache::lonnet::get('environment',
 9841:                                                        ['firstname',
 9842:                                                         'lastname',
 9843:                                                         'permanentemail'],
 9844:                                                          $udom,$uname)
 9845:                                 };
 9846:                         }
 9847:                     } else {
 9848:                         %srch_results = &Apache::lonnet::usersearch($srch);
 9849:                         ($currstate,$response,$forcenewuser) =
 9850:                             &build_search_response($context,$srch,%srch_results);
 9851:                     }
 9852:                 } else {
 9853:                     my $courseusers = &get_courseusers();
 9854:                     if ($srch->{'srchtype'} eq 'exact') {
 9855:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 9856:                             $currstate = 'modify';
 9857:                         } else {
 9858:                             ($currstate,$response,$forcenewuser) =
 9859:                                 &build_search_response($context,$srch,%srch_results);
 9860:                         }
 9861:                     } else {
 9862:                         foreach my $user (keys(%$courseusers)) {
 9863:                             my ($cuname,$cudomain) = split(/:/,$user);
 9864:                             if ($cudomain eq $srch->{'srchdomain'}) {
 9865:                                 my $matched = 0;
 9866:                                 if ($srch->{'srchtype'} eq 'begins') {
 9867:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 9868:                                         $matched = 1;
 9869:                                     }
 9870:                                 } else {
 9871:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 9872:                                         $matched = 1;
 9873:                                     }
 9874:                                 }
 9875:                                 if ($matched) {
 9876:                                     $srch_results{$user} = 
 9877: 					{&Apache::lonnet::get('environment',
 9878: 							     ['firstname',
 9879: 							      'lastname',
 9880: 							      'permanentemail'],
 9881: 							      $cudomain,$cuname)};
 9882:                                 }
 9883:                             }
 9884:                         }
 9885:                         ($currstate,$response,$forcenewuser) =
 9886:                             &build_search_response($context,$srch,%srch_results);
 9887:                     }
 9888:                 }
 9889:             }
 9890:         } elsif ($srch->{'srchin'} eq 'alc') {
 9891:             $currstate = 'query';
 9892:         } elsif ($srch->{'srchin'} eq 'instd') {
 9893:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 9894:             if ($dirsrchres eq 'ok') {
 9895:                 ($currstate,$response,$forcenewuser) = 
 9896:                     &build_search_response($context,$srch,%srch_results);
 9897:             } else {
 9898:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9899:                 $response = '<span class="LC_warning">'.
 9900:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9901:                     '</span><br />'.
 9902:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 9903:                     '<br />'; 
 9904:             }
 9905:         }
 9906:     } else {
 9907:         if ($srch->{'srchin'} eq 'dom') {
 9908:             %srch_results = &Apache::lonnet::usersearch($srch);
 9909:             ($currstate,$response,$forcenewuser) = 
 9910:                 &build_search_response($context,$srch,%srch_results); 
 9911:         } elsif ($srch->{'srchin'} eq 'crs') {
 9912:             my $courseusers = &get_courseusers(); 
 9913:             foreach my $user (keys(%$courseusers)) {
 9914:                 my ($uname,$udom) = split(/:/,$user);
 9915:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 9916:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 9917:                 if ($srch->{'srchby'} eq 'lastname') {
 9918:                     if ((($srch->{'srchtype'} eq 'exact') && 
 9919:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 9920:                         (($srch->{'srchtype'} eq 'begins') &&
 9921:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 9922:                         (($srch->{'srchtype'} eq 'contains') &&
 9923:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 9924:                         $srch_results{$user} = {firstname => $names{'firstname'},
 9925:                                             lastname => $names{'lastname'},
 9926:                                             permanentemail => $emails{'permanentemail'},
 9927:                                            };
 9928:                     }
 9929:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 9930:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 9931:                     $srchlast =~ s/\s+$//;
 9932:                     $srchfirst =~ s/^\s+//;
 9933:                     if ($srch->{'srchtype'} eq 'exact') {
 9934:                         if (($names{'lastname'} eq $srchlast) &&
 9935:                             ($names{'firstname'} eq $srchfirst)) {
 9936:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9937:                                                 lastname => $names{'lastname'},
 9938:                                                 permanentemail => $emails{'permanentemail'},
 9939: 
 9940:                                            };
 9941:                         }
 9942:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 9943:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 9944:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 9945:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9946:                                                 lastname => $names{'lastname'},
 9947:                                                 permanentemail => $emails{'permanentemail'},
 9948:                                                };
 9949:                         }
 9950:                     } else {
 9951:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 9952:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 9953:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9954:                                                 lastname => $names{'lastname'},
 9955:                                                 permanentemail => $emails{'permanentemail'},
 9956:                                                };
 9957:                         }
 9958:                     }
 9959:                 }
 9960:             }
 9961:             ($currstate,$response,$forcenewuser) = 
 9962:                 &build_search_response($context,$srch,%srch_results); 
 9963:         } elsif ($srch->{'srchin'} eq 'alc') {
 9964:             $currstate = 'query';
 9965:         } elsif ($srch->{'srchin'} eq 'instd') {
 9966:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 9967:             if ($dirsrchres eq 'ok') {
 9968:                 ($currstate,$response,$forcenewuser) = 
 9969:                     &build_search_response($context,$srch,%srch_results);
 9970:             } else {
 9971:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9972:                 $response = '<span class="LC_warning">'.
 9973:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9974:                     '</span><br />'.
 9975:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 9976:                     '<br />';
 9977:             }
 9978:         }
 9979:     }
 9980:     return ($currstate,$response,$forcenewuser,\%srch_results);
 9981: }
 9982: 
 9983: sub domdirectorysrch_check {
 9984:     my ($srch) = @_;
 9985:     my $response;
 9986:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 9987:                                              ['directorysrch'],$srch->{'srchdomain'});
 9988:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 9989:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 9990:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 9991:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 9992:         }
 9993:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 9994:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 9995:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 9996:             }
 9997:         }
 9998:     }
 9999:     return 'ok';
10000: }
10001: 
10002: sub instdirectorysrch_check {
10003:     my ($srch) = @_;
10004:     my $can_search = 0;
10005:     my $response;
10006:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10007:                                              ['directorysrch'],$srch->{'srchdomain'});
10008:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10009:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10010:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
10011:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
10012:         }
10013:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
10014:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10015:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
10016:             }
10017:             my @usertypes = split(/:/,$env{'environment.inststatus'});
10018:             if (!@usertypes) {
10019:                 push(@usertypes,'default');
10020:             }
10021:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
10022:                 foreach my $type (@usertypes) {
10023:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
10024:                         $can_search = 1;
10025:                         last;
10026:                     }
10027:                 }
10028:             }
10029:             if (!$can_search) {
10030:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
10031:                 my @longtypes; 
10032:                 foreach my $item (@usertypes) {
10033:                     if (defined($insttypes->{$item})) { 
10034:                         push (@longtypes,$insttypes->{$item});
10035:                     } elsif ($item eq 'default') {
10036:                         push (@longtypes,&mt('other')); 
10037:                     }
10038:                 }
10039:                 my $insttype_str = join(', ',@longtypes); 
10040:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
10041:             }
10042:         } else {
10043:             $can_search = 1;
10044:         }
10045:     } else {
10046:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
10047:     }
10048:     my %longtext = &Apache::lonlocal::texthash (
10049:                        uname     => 'username',
10050:                        lastfirst => 'last name, first name',
10051:                        lastname  => 'last name',
10052:                        contains  => 'contains',
10053:                        exact     => 'as exact match to',
10054:                        begins    => 'begins with',
10055:                    );
10056:     if ($can_search) {
10057:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
10058:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
10059:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
10060:             }
10061:         } else {
10062:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
10063:         }
10064:     }
10065:     if ($can_search) {
10066:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
10067:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
10068:                 return 'ok';
10069:             } else {
10070:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10071:             }
10072:         } else {
10073:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
10074:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
10075:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
10076:                 return 'ok';
10077:             } else {
10078:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10079:             }
10080:         }
10081:     }
10082: }
10083: 
10084: sub get_courseusers {
10085:     my %advhash;
10086:     my $classlist = &Apache::loncoursedata::get_classlist();
10087:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
10088:     foreach my $role (sort(keys(%coursepersonnel))) {
10089:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
10090: 	    if (!exists($classlist->{$user})) {
10091: 		$classlist->{$user} = [];
10092: 	    }
10093:         }
10094:     }
10095:     return $classlist;
10096: }
10097: 
10098: sub build_search_response {
10099:     my ($context,$srch,%srch_results) = @_;
10100:     my ($currstate,$response,$forcenewuser);
10101:     my %names = (
10102:           'uname'     => 'username',
10103:           'lastname'  => 'last name',
10104:           'lastfirst' => 'last name, first name',
10105:           'crs'       => 'this course',
10106:           'dom'       => 'LON-CAPA domain',
10107:           'instd'     => 'the institutional directory for domain',
10108:     );
10109: 
10110:     my %single = (
10111:                    begins   => 'A match',
10112:                    contains => 'A match',
10113:                    exact    => 'An exact match',
10114:                  );
10115:     my %nomatch = (
10116:                    begins   => 'No match',
10117:                    contains => 'No match',
10118:                    exact    => 'No exact match',
10119:                   );
10120:     if (keys(%srch_results) > 1) {
10121:         $currstate = 'select';
10122:     } else {
10123:         if (keys(%srch_results) == 1) {
10124:             if ($env{'form.action'} eq 'accesslogs') {
10125:                 $currstate = 'activity';
10126:             } else {
10127:                 $currstate = 'modify';
10128:             }
10129:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
10130:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10131:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
10132:             }
10133:         } else { # Search has nothing found. Prepare message to user.
10134:             $response = '<span class="LC_warning">';
10135:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10136:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
10137:                                  '<b>'.$srch->{'srchterm'}.'</b>',
10138:                                  &display_domain_info($srch->{'srchdomain'}));
10139:             } else {
10140:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
10141:                                  '<b>'.$srch->{'srchterm'}.'</b>');
10142:             }
10143:             $response .= '</span>';
10144: 
10145:             if ($srch->{'srchin'} ne 'alc') {
10146:                 $forcenewuser = 1;
10147:                 my $cansrchinst = 0; 
10148:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
10149:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
10150:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
10151:                         if ($domconfig{'directorysrch'}{'available'}) {
10152:                             $cansrchinst = 1;
10153:                         } 
10154:                     }
10155:                 }
10156:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
10157:                      ($srch->{'srchby'} eq 'lastname')) &&
10158:                     ($srch->{'srchin'} eq 'dom')) {
10159:                     if ($cansrchinst) {
10160:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
10161:                     }
10162:                 }
10163:                 if ($srch->{'srchin'} eq 'crs') {
10164:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
10165:                 }
10166:             }
10167:             my $createdom = $env{'request.role.domain'};
10168:             if ($context eq 'requestcrs') {
10169:                 if ($env{'form.coursedom'} ne '') {
10170:                     $createdom = $env{'form.coursedom'};
10171:                 }
10172:             }
10173:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
10174:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
10175:                 my $cancreate =
10176:                     &Apache::lonuserutils::can_create_user($createdom,$context);
10177:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
10178:                 if ($cancreate) {
10179:                     my $showdom = &display_domain_info($createdom); 
10180:                     $response .= '<br /><br />'
10181:                                 .'<b>'.&mt('To add a new user:').'</b>'
10182:                                 .'<br />';
10183:                     if ($context eq 'requestcrs') {
10184:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
10185:                     } else {
10186:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
10187:                     }
10188:                     $response .='<ul><li>'
10189:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
10190:                                 .'</li><li>'
10191:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
10192:                                 .'</li><li>'
10193:                                 .&mt('Provide the proposed username')
10194:                                 .'</li><li>'
10195:                                 .&mt("Click 'Search'")
10196:                                 .'</li></ul><br />';
10197:                 } else {
10198:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
10199:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
10200:                         $response .= '<br /><br />';
10201:                         if ($context eq 'requestcrs') {
10202:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
10203:                         } else {
10204:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
10205:                         }
10206:                         $response .= '<br />'
10207:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
10208:                                         ,' <a'.$helplink.'>'
10209:                                         ,'</a>')
10210:                                      .'<br />';
10211:                     }
10212:                 }
10213:             }
10214:         }
10215:     }
10216:     return ($currstate,$response,$forcenewuser);
10217: }
10218: 
10219: sub display_domain_info {
10220:     my ($dom) = @_;
10221:     my $output = $dom;
10222:     if ($dom ne '') { 
10223:         my $domdesc = &Apache::lonnet::domain($dom,'description');
10224:         if ($domdesc ne '') {
10225:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
10226:         }
10227:     }
10228:     return $output;
10229: }
10230: 
10231: sub crumb_utilities {
10232:     my %elements = (
10233:        crtuser => {
10234:            srchterm => 'text',
10235:            srchin => 'selectbox',
10236:            srchby => 'selectbox',
10237:            srchtype => 'selectbox',
10238:            srchdomain => 'selectbox',
10239:        },
10240:        crtusername => {
10241:            srchterm => 'text',
10242:            srchdomain => 'selectbox',
10243:        },
10244:        docustom => {
10245:            rolename => 'selectbox',
10246:            newrolename => 'textbox',
10247:        },
10248:        studentform => {
10249:            srchterm => 'text',
10250:            srchin => 'selectbox',
10251:            srchby => 'selectbox',
10252:            srchtype => 'selectbox',
10253:            srchdomain => 'selectbox',
10254:        },
10255:     );
10256: 
10257:     my $jsback .= qq|
10258: function backPage(formname,prevphase,prevstate) {
10259:     if (typeof prevphase == 'undefined') {
10260:         formname.phase.value = '';
10261:     }
10262:     else {  
10263:         formname.phase.value = prevphase;
10264:     }
10265:     if (typeof prevstate == 'undefined') {
10266:         formname.currstate.value = '';
10267:     }
10268:     else {
10269:         formname.currstate.value = prevstate;
10270:     }
10271:     formname.submit();
10272: }
10273: |;
10274:     return ($jsback,\%elements);
10275: }
10276: 
10277: sub course_level_table {
10278:     my ($inccourses,$showcredits,$defaultcredits) = @_;
10279:     return unless (ref($inccourses) eq 'HASH');
10280:     my $table = '';
10281: # Custom Roles?
10282: 
10283:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10284:     my %lt=&Apache::lonlocal::texthash(
10285:             'exs'  => "Existing sections",
10286:             'new'  => "Define new section",
10287:             'ssd'  => "Set Start Date",
10288:             'sed'  => "Set End Date",
10289:             'crl'  => "Course Level",
10290:             'act'  => "Activate",
10291:             'rol'  => "Role",
10292:             'ext'  => "Extent",
10293:             'grs'  => "Section",
10294:             'crd'  => "Credits",
10295:             'sta'  => "Start",
10296:             'end'  => "End"
10297:     );
10298: 
10299:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
10300: 	my $thiscourse=$protectedcourse;
10301: 	$thiscourse=~s:_:/:g;
10302: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
10303:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
10304: 	my $area=$coursedata{'description'};
10305:         my $crstype=$coursedata{'type'};
10306: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
10307: 	my ($domain,$cnum)=split(/\//,$thiscourse);
10308:         my %sections_count;
10309:         if (defined($env{'request.course.id'})) {
10310:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
10311:                 %sections_count = 
10312: 		    &Apache::loncommon::get_sections($domain,$cnum);
10313:             }
10314:         }
10315:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
10316: 	foreach my $role (@roles) {
10317:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
10318: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
10319:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
10320:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10321:                                             $plrole,\%sections_count,\%lt,
10322:                                             $showcredits,$defaultcredits,$crstype);
10323:             } elsif ($env{'request.course.sec'} ne '') {
10324:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
10325:                                              $env{'request.course.sec'})) {
10326:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10327:                                                 $plrole,\%sections_count,\%lt,
10328:                                                 $showcredits,$defaultcredits,$crstype);
10329:                 }
10330:             }
10331:         }
10332:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
10333:             foreach my $cust (sort(keys(%customroles))) {
10334:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
10335:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
10336:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10337:                                             $cust,\%sections_count,\%lt,
10338:                                             $showcredits,$defaultcredits,$crstype);
10339:             }
10340: 	}
10341:     }
10342:     return '' if ($table eq ''); # return nothing if there is nothing 
10343:                                  # in the table
10344:     my $result;
10345:     if (!$env{'request.course.id'}) {
10346:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
10347:     }
10348:     $result .= 
10349: &Apache::loncommon::start_data_table().
10350: &Apache::loncommon::start_data_table_header_row().
10351: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10352: '<th>'.$lt{'ext'}.'</th><th>'."\n";
10353:     if ($showcredits) {
10354:         $result .= $lt{'crd'}.'</th>';
10355:     }
10356:     $result .=
10357: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
10358: '<th>'.$lt{'end'}.'</th>'.
10359: &Apache::loncommon::end_data_table_header_row().
10360: $table.
10361: &Apache::loncommon::end_data_table();
10362:     return $result;
10363: }
10364: 
10365: sub course_level_row {
10366:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
10367:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
10368:     my $creditem;
10369:     my $row = &Apache::loncommon::start_data_table_row().
10370:               ' <td><input type="checkbox" name="act_'.
10371:               $protectedcourse.'_'.$role.'" /></td>'."\n".
10372:               ' <td>'.$plrole.'</td>'."\n".
10373:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
10374:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
10375:         $row .= 
10376:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
10377:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
10378:     } else {
10379:         $row .= '<td>&nbsp;</td>';
10380:     }
10381:     if (($role eq 'cc') || ($role eq 'co')) {
10382:         $row .= '<td>&nbsp;</td>';
10383:     } elsif ($env{'request.course.sec'} ne '') {
10384:         $row .= ' <td><input type="hidden" value="'.
10385:                 $env{'request.course.sec'}.'" '.
10386:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
10387:                 $env{'request.course.sec'}.'</td>';
10388:     } else {
10389:         if (ref($sections_count) eq 'HASH') {
10390:             my $currsec = 
10391:                 &Apache::lonuserutils::course_sections($sections_count,
10392:                                                        $protectedcourse.'_'.$role);
10393:             $row .= '<td><table class="LC_createuser">'."\n".
10394:                     '<tr class="LC_section_row">'."\n".
10395:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
10396:                        $currsec.'</td>'."\n".
10397:                      ' <td>&nbsp;&nbsp;</td>'."\n".
10398:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
10399:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
10400:                      '" value="" />'.
10401:                      '<input type="hidden" '.
10402:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
10403:                      '</tr></table></td>'."\n";
10404:         } else {
10405:             $row .= '<td><input type="text" size="10" '.
10406:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
10407:         }
10408:     }
10409:     $row .= <<ENDTIMEENTRY;
10410: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
10411: <a href=
10412: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
10413: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
10414: <a href=
10415: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
10416: ENDTIMEENTRY
10417:     $row .= &Apache::loncommon::end_data_table_row();
10418:     return $row;
10419: }
10420: 
10421: sub course_level_dc {
10422:     my ($dcdom,$showcredits) = @_;
10423:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10424:     my @roles = &Apache::lonuserutils::roles_by_context('course');
10425:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
10426:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
10427:                       '<input type="hidden" name="dccourse" value="" />';
10428:     my $courseform=&Apache::loncommon::selectcourse_link
10429:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
10430:     my $credit_elem;
10431:     if ($showcredits) {
10432:         $credit_elem = 'credits';
10433:     }
10434:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
10435:     my %lt=&Apache::lonlocal::texthash(
10436:                     'rol'  => "Role",
10437:                     'grs'  => "Section",
10438:                     'exs'  => "Existing sections",
10439:                     'new'  => "Define new section", 
10440:                     'sta'  => "Start",
10441:                     'end'  => "End",
10442:                     'ssd'  => "Set Start Date",
10443:                     'sed'  => "Set End Date",
10444:                     'scc'  => "Course/Community",
10445:                     'crd'  => "Credits",
10446:                   );
10447:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
10448:                  &Apache::loncommon::start_data_table().
10449:                  &Apache::loncommon::start_data_table_header_row().
10450:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10451:                  '<th>'.$lt{'grs'}.'</th>'."\n";
10452:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
10453:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
10454:                  &Apache::loncommon::end_data_table_header_row();
10455:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
10456:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
10457:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
10458:                      '<td valign="top"><br /><select name="role">'."\n";
10459:     foreach my $role (@roles) {
10460:         my $plrole=&Apache::lonnet::plaintext($role);
10461:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
10462:     }
10463:     if ( keys(%customroles) > 0) {
10464:         foreach my $cust (sort(keys(%customroles))) {
10465:             my $custrole='cr_cr_'.$env{'user.domain'}.
10466:                     '_'.$env{'user.name'}.'_'.$cust;
10467:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
10468:         }
10469:     }
10470:     $otheritems .= '</select></td><td>'.
10471:                      '<table border="0" cellspacing="0" cellpadding="0">'.
10472:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
10473:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
10474:                      '<td>&nbsp;&nbsp;</td>'.
10475:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
10476:                      '<input type="text" name="newsec" value="" />'.
10477:                      '<input type="hidden" name="section" value="" />'.
10478:                      '<input type="hidden" name="groups" value="" />'.
10479:                      '<input type="hidden" name="crstype" value="" /></td>'.
10480:                      '</tr></table></td>'."\n";
10481:     if ($showcredits) {
10482:         $otheritems .= '<td><br />'."\n".
10483:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
10484:     }
10485:     $otheritems .= <<ENDTIMEENTRY;
10486: <td><br /><input type="hidden" name="start" value='' />
10487: <a href=
10488: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
10489: <td><br /><input type="hidden" name="end" value='' />
10490: <a href=
10491: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
10492: ENDTIMEENTRY
10493:     $otheritems .= &Apache::loncommon::end_data_table_row().
10494:                    &Apache::loncommon::end_data_table()."\n";
10495:     return $cb_jscript.$hiddenitems.$header.$otheritems;
10496: }
10497: 
10498: sub update_selfenroll_config {
10499:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
10500:     return unless (ref($currsettings) eq 'HASH');
10501:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
10502:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10503:     my (%changes,%warning);
10504:     my $curr_types;
10505:     my %noedit;
10506:     unless ($context eq 'domain') {
10507:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
10508:     }
10509:     if (ref($row) eq 'ARRAY') {
10510:         foreach my $item (@{$row}) {
10511:             next if ($noedit{$item});
10512:             if ($item eq 'enroll_dates') {
10513:                 my (%currenrolldate,%newenrolldate);
10514:                 foreach my $type ('start','end') {
10515:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
10516:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
10517:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
10518:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
10519:                     }
10520:                 }
10521:             } elsif ($item eq 'access_dates') {
10522:                 my (%currdate,%newdate);
10523:                 foreach my $type ('start','end') {
10524:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
10525:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
10526:                     if ($newdate{$type} ne $currdate{$type}) {
10527:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
10528:                     }
10529:                 }
10530:             } elsif ($item eq 'types') {
10531:                 $curr_types = $currsettings->{'selfenroll_'.$item};
10532:                 if ($env{'form.selfenroll_all'}) {
10533:                     if ($curr_types ne '*') {
10534:                         $changes{'internal.selfenroll_types'} = '*';
10535:                     } else {
10536:                         next;
10537:                     }
10538:                 } else {
10539:                     my %currdoms;
10540:                     my @entries = split(/;/,$curr_types);
10541:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
10542:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
10543:                     my $newnum = 0;
10544:                     my @latesttypes;
10545:                     foreach my $num (@activations) {
10546:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
10547:                         if (@types > 0) {
10548:                             @types = sort(@types);
10549:                             my $typestr = join(',',@types);
10550:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
10551:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10552:                             $currdoms{$typedom} = 1;
10553:                             $newnum ++;
10554:                         }
10555:                     }
10556:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
10557:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
10558:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
10559:                             if (@types > 0) {
10560:                                 @types = sort(@types);
10561:                                 my $typestr = join(',',@types);
10562:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
10563:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
10564:                                 $currdoms{$typedom} = 1;
10565:                                 $newnum ++;
10566:                             }
10567:                         }
10568:                     }
10569:                     if ($env{'form.selfenroll_newdom'} ne '') {
10570:                         my $typedom = $env{'form.selfenroll_newdom'};
10571:                         if ((!defined($currdoms{$typedom})) && 
10572:                             (&Apache::lonnet::domain($typedom) ne '')) {
10573:                             my $typestr;
10574:                             my ($othertitle,$usertypes,$types) = 
10575:                                 &Apache::loncommon::sorted_inst_types($typedom);
10576:                             my $othervalue = 'any';
10577:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
10578:                                 if (@{$types} > 0) {
10579:                                     my @esc_types = map { &escape($_); } @{$types};
10580:                                     $othervalue = 'other';
10581:                                     $typestr = join(',',(@esc_types,$othervalue));
10582:                                 }
10583:                                 $typestr = $othervalue;
10584:                             } else {
10585:                                 $typestr = $othervalue;
10586:                             } 
10587:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10588:                             $newnum ++ ;
10589:                         }
10590:                     }
10591:                     my $selfenroll_types = join(';',@latesttypes);
10592:                     if ($selfenroll_types ne $curr_types) {
10593:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
10594:                     }
10595:                 }
10596:             } elsif ($item eq 'limit') {
10597:                 my $newlimit = $env{'form.selfenroll_limit'};
10598:                 my $newcap = $env{'form.selfenroll_cap'};
10599:                 $newcap =~s/\s+//g;
10600:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10601:                 $currlimit = 'none' if ($currlimit eq '');
10602:                 my $currcap = $currsettings->{'selfenroll_cap'};
10603:                 if ($newlimit ne $currlimit) {
10604:                     if ($newlimit ne 'none') {
10605:                         if ($newcap =~ /^\d+$/) {
10606:                             if ($newcap ne $currcap) {
10607:                                 $changes{'internal.selfenroll_cap'} = $newcap;
10608:                             }
10609:                             $changes{'internal.selfenroll_limit'} = $newlimit;
10610:                         } else {
10611:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10612:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
10613:                         }
10614:                     } elsif ($currcap ne '') {
10615:                         $changes{'internal.selfenroll_cap'} = '';
10616:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
10617:                     }
10618:                 } elsif ($currlimit ne 'none') {
10619:                     if ($newcap =~ /^\d+$/) {
10620:                         if ($newcap ne $currcap) {
10621:                             $changes{'internal.selfenroll_cap'} = $newcap;
10622:                         }
10623:                     } else {
10624:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10625:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
10626:                     }
10627:                 }
10628:             } elsif ($item eq 'approval') {
10629:                 my (@currnotified,@newnotified);
10630:                 my $currapproval = $currsettings->{'selfenroll_approval'};
10631:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
10632:                 if ($currnotifylist ne '') {
10633:                     @currnotified = split(/,/,$currnotifylist);
10634:                     @currnotified = sort(@currnotified);
10635:                 }
10636:                 my $newapproval = $env{'form.selfenroll_approval'};
10637:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
10638:                 @newnotified = sort(@newnotified);
10639:                 if ($newapproval ne $currapproval) {
10640:                     $changes{'internal.selfenroll_approval'} = $newapproval;
10641:                     if (!$newapproval) {
10642:                         if ($currnotifylist ne '') {
10643:                             $changes{'internal.selfenroll_notifylist'} = '';
10644:                         }
10645:                     } else {
10646:                         my @differences =  
10647:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10648:                         if (@differences > 0) {
10649:                             if (@newnotified > 0) {
10650:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10651:                             } else {
10652:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10653:                             }
10654:                         }
10655:                     }
10656:                 } else {
10657:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10658:                     if (@differences > 0) {
10659:                         if (@newnotified > 0) {
10660:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10661:                         } else {
10662:                             $changes{'internal.selfenroll_notifylist'} = '';
10663:                         }
10664:                     }
10665:                 }
10666:             } else {
10667:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
10668:                 my $newval = $env{'form.selfenroll_'.$item};
10669:                 if ($item eq 'section') {
10670:                     $newval = $env{'form.sections'};
10671:                     if (defined($curr_groups{$newval})) {
10672:                         $newval = $curr_val;
10673:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
10674:                                           &mt('Group names and section names must be distinct');
10675:                     } elsif ($newval eq 'all') {
10676:                         $newval = $curr_val;
10677:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
10678:                     }
10679:                     if ($newval eq '') {
10680:                         $newval = 'none';
10681:                     }
10682:                 }
10683:                 if ($newval ne $curr_val) {
10684:                     $changes{'internal.selfenroll_'.$item} = $newval;
10685:                 }
10686:             }
10687:         }
10688:         if (keys(%warning) > 0) {
10689:             foreach my $item (@{$row}) {
10690:                 if (exists($warning{$item})) {
10691:                     $r->print($warning{$item}.'<br />');
10692:                 }
10693:             } 
10694:         }
10695:         if (keys(%changes) > 0) {
10696:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
10697:             if ($putresult eq 'ok') {
10698:                 if ((exists($changes{'internal.selfenroll_types'})) ||
10699:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
10700:                     (exists($changes{'internal.selfenroll_end_date'}))) {
10701:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
10702:                                                                 $cnum,undef,undef,'Course');
10703:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
10704:                     if (ref($crsinfo{$cid}) eq 'HASH') {
10705:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
10706:                             if (exists($changes{'internal.'.$item})) {
10707:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
10708:                             }
10709:                         }
10710:                         my $crsputresult =
10711:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
10712:                                                          $chome,'notime');
10713:                     }
10714:                 }
10715:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
10716:                 foreach my $item (@{$row}) {
10717:                     my $title = $item;
10718:                     if (ref($lt) eq 'HASH') {
10719:                         $title = $lt->{$item};
10720:                     }
10721:                     if ($item eq 'enroll_dates') {
10722:                         foreach my $type ('start','end') {
10723:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
10724:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
10725:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10726:                                           $title,$type,$newdate).'</li>');
10727:                             }
10728:                         }
10729:                     } elsif ($item eq 'access_dates') {
10730:                         foreach my $type ('start','end') {
10731:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
10732:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
10733:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10734:                                           $title,$type,$newdate).'</li>');
10735:                             }
10736:                         }
10737:                     } elsif ($item eq 'limit') {
10738:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
10739:                             (exists($changes{'internal.selfenroll_cap'}))) {
10740:                             my ($newval,$newcap);
10741:                             if ($changes{'internal.selfenroll_cap'} ne '') {
10742:                                 $newcap = $changes{'internal.selfenroll_cap'}
10743:                             } else {
10744:                                 $newcap = $currsettings->{'selfenroll_cap'};
10745:                             }
10746:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
10747:                                 $newval = &mt('No limit');
10748:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
10749:                                      'allstudents') {
10750:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10751:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10752:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10753:                             } else {
10754:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10755:                                 if ($currlimit eq 'allstudents') {
10756:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10757:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10758:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10759:                                 }
10760:                             }
10761:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10762:                         }
10763:                     } elsif ($item eq 'approval') {
10764:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
10765:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
10766:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
10767:                             my ($newval,$newnotify);
10768:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
10769:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
10770:                             } else {   
10771:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
10772:                             }
10773:                             if (exists($changes{'internal.selfenroll_approval'})) {
10774:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
10775:                                     $changes{'internal.selfenroll_approval'} = '0';
10776:                                 }
10777:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
10778:                             } else {
10779:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
10780:                                 if ($currapproval !~ /^[012]$/) {
10781:                                     $currapproval = 0;
10782:                                 }
10783:                                 $newval = $selfdescs{'approval'}{$currapproval};
10784:                             }
10785:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
10786:                             if ($newnotify) {
10787:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
10788:                             } else {
10789:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
10790:                             }
10791:                             $r->print('</li>'."\n");
10792:                         }
10793:                     } else {
10794:                         if (exists($changes{'internal.selfenroll_'.$item})) {
10795:                             my $newval = $changes{'internal.selfenroll_'.$item};
10796:                             if ($item eq 'types') {
10797:                                 if ($newval eq '') {
10798:                                     $newval = &mt('None');
10799:                                 } elsif ($newval eq '*') {
10800:                                     $newval = &mt('Any user in any domain');
10801:                                 }
10802:                             } elsif ($item eq 'registered') {
10803:                                 if ($newval eq '1') {
10804:                                     $newval = &mt('Yes');
10805:                                 } elsif ($newval eq '0') {
10806:                                     $newval = &mt('No');
10807:                                 }
10808:                             }
10809:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10810:                         }
10811:                     }
10812:                 }
10813:                 $r->print('</ul>');
10814:                 if ($env{'course.'.$cid.'.description'} ne '') {
10815:                     my %newenvhash;
10816:                     foreach my $key (keys(%changes)) {
10817:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
10818:                     }
10819:                     &Apache::lonnet::appenv(\%newenvhash);
10820:                 }
10821:             } else {
10822:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
10823:                           &mt('The error was: [_1].',$putresult));
10824:             }
10825:         } else {
10826:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10827:         }
10828:     } else {
10829:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10830:     }
10831:     my $visactions = &cat_visibility($cdom);
10832:     my ($cathash,%cattype);
10833:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
10834:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10835:         $cathash = $domconfig{'coursecategories'}{'cats'};
10836:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
10837:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
10838:     } else {
10839:         $cathash = {};
10840:         $cattype{'auth'} = 'std';
10841:         $cattype{'unauth'} = 'std';
10842:     }
10843:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
10844:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10845:                   '<br />'.
10846:                   '<br />'.$visactions->{'take'}.'<ul>'.
10847:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
10848:                   '</ul>');
10849:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
10850:         if ($currsettings->{'uniquecode'}) {
10851:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
10852:         } else {
10853:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10854:                   '<br />'.
10855:                   '<br />'.$visactions->{'take'}.'<ul>'.
10856:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
10857:                   '</ul><br />');
10858:         }
10859:     } else {
10860:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
10861:         if (ref($visactions) eq 'HASH') {
10862:             if (!$visible) {
10863:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10864:                           '<br />');
10865:                 if (ref($vismsgs) eq 'ARRAY') {
10866:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
10867:                     foreach my $item (@{$vismsgs}) {
10868:                         $r->print('<li>'.$visactions->{$item}.'</li>');
10869:                     }
10870:                     $r->print('</ul>');
10871:                 }
10872:                 $r->print($cansetvis);
10873:             }
10874:         }
10875:     } 
10876:     return;
10877: }
10878: 
10879: #---------------------------------------------- end functions for &phase_two
10880: 
10881: #--------------------------------- functions for &phase_two and &phase_three
10882: 
10883: #--------------------------end of functions for &phase_two and &phase_three
10884: 
10885: 1;
10886: __END__
10887: 
10888: 

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