File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.470: download - view: text, annotated - select for diffs
Fri Nov 3 01:12:15 2023 UTC (6 months, 4 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Authoring Space defaults defaults which domain coordinator can override.
  - Available Editors, WebDAV access, Disk Quota for Authoring Space
    can be set for specific users by DC via "Add/modify user"
- Bug 5273 Co-authors in "group authoring" accounts can manage co-authors
  - Existing co-author(s) can be assigned rights to add/revoke co-author
    roles. Can be set by DC via "Add/modify user" or by author via "People"
- Co-authors and Assistant co-authors can view a list of co-authors for
  the Authoring Space. Availability set by Author or Co-author "manager".
  Listing can be set to "opt-in".

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.470 2023/11/03 01:12:15 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use Apache::lonviewcoauthors;
   74: use LONCAPA qw(:DEFAULT :match);
   75: use HTML::Entities;
   76: 
   77: my $loginscript; # piece of javascript used in two separate instances
   78: my $authformnop;
   79: my $authformkrb;
   80: my $authformint;
   81: my $authformfsys;
   82: my $authformloc;
   83: my $authformlti;
   84: 
   85: sub initialize_authen_forms {
   86:     my ($dom,$formname,$curr_authtype,$mode,$readonly) = @_;
   87:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   88:     my %param = ( formname => $formname,
   89:                   kerb_def_dom => $krbdefdom,
   90:                   kerb_def_auth => $krbdef,
   91:                   domain => $dom,
   92:                 );
   93:     my %abv_auth = &auth_abbrev();
   94:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix|lti):(.*)$/) {
   95:         my $long_auth = $1;
   96:         my $curr_autharg = $2;
   97:         my %abv_auth = &auth_abbrev();
   98:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   99:         if ($long_auth =~ /^krb(4|5)$/) {
  100:             $param{'curr_kerb_ver'} = $1;
  101:             $param{'curr_autharg'} = $curr_autharg;
  102:         }
  103:         if ($mode eq 'modifyuser') {
  104:             $param{'mode'} = $mode;
  105:         }
  106:     }
  107:     if ($readonly) {
  108:         $param{'readonly'} = 1;
  109:     }
  110:     $loginscript  = &Apache::loncommon::authform_header(%param);
  111:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  112:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  113:     $authformint  = &Apache::loncommon::authform_internal(%param);
  114:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  115:     $authformloc  = &Apache::loncommon::authform_local(%param);
  116:     $authformlti  = &Apache::loncommon::authform_lti(%param);
  117: }
  118: 
  119: sub auth_abbrev {
  120:     my %abv_auth = (
  121:                      krb5      => 'krb',
  122:                      krb4      => 'krb',
  123:                      internal  => 'int',
  124:                      localauth => 'loc',
  125:                      unix      => 'fsys',
  126:                      lti       => 'lti',
  127:                    );
  128:     return %abv_auth;
  129: }
  130: 
  131: # ====================================================
  132: 
  133: sub user_quotas {
  134:     my ($ccuname,$ccdomain,$name) = @_;
  135:     my %lt = &Apache::lonlocal::texthash(
  136:                    'cust'      => "Custom quota",
  137:                    'chqu'      => "Change quota",
  138:     );
  139:     my ($output,$longinsttype);
  140:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  141:     my %titles = &Apache::lonlocal::texthash (
  142:                     portfolio => "Disk space allocated to user's portfolio files",
  143:                     author    => "Disk space allocated to user's Authoring Space",
  144:                  );
  145:     my ($currquota,$quotatype,$inststatus,$defquota) =
  146:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  147:     if ($longinsttype eq '') {
  148:         if ($inststatus ne '') {
  149:             if ($usertypes->{$inststatus} ne '') {
  150:                 $longinsttype = $usertypes->{$inststatus};
  151:             }
  152:         }
  153:     }
  154:     my ($showquota,$custom_on,$custom_off,$defaultinfo,$colspan);
  155:     $custom_on = ' ';
  156:     $custom_off = ' checked="checked" ';
  157:     $colspan = ' colspan="2"';
  158:     if ($quotatype eq 'custom') {
  159:         $custom_on = $custom_off;
  160:         $custom_off = ' ';
  161:         $showquota = $currquota;
  162:         if ($longinsttype eq '') {
  163:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
  164:                               .' MB.',$defquota);
  165:         } else {
  166:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
  167:                                " MB,[_2]as determined by the user's institutional".
  168:                                " affiliation ([_3]).",$defquota,'<br />',$longinsttype);
  169:         }
  170:     } else {
  171:         if ($longinsttype eq '') {
  172:             $defaultinfo = &mt('For this user, the default quota is [_1]'
  173:                               .' MB.',$defquota);
  174:         } else {
  175:             $defaultinfo = &mt("For this user, the default quota of [_1]".
  176:                                " MB,[_2]is determined by the user's institutional".
  177:                                " affiliation ([_3]).",$defquota,'<br />'.$longinsttype);
  178:         }
  179:     }
  180: 
  181:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  182:         $output .= '<tr class="LC_info_row">'."\n".
  183:                    '    <td'.$colspan.'>'.$titles{$name}.'</td>'."\n".
  184:                    '  </tr>'."\n".
  185:                    &Apache::loncommon::start_data_table_row()."\n".
  186:                    '  <td'.$colspan.'><span class="LC_nobreak">'.
  187:                    &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  188:                    $defaultinfo.'</td>'."\n".
  189:                    &Apache::loncommon::end_data_table_row()."\n".
  190:                    &Apache::loncommon::start_data_table_row()."\n".
  191:                    '<td'.$colspan.'><span class="LC_nobreak">'.$lt{'chqu'}.
  192:                    ': <label>'.
  193:                    '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  194:                    'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  195:                    ' /><span class="LC_nobreak">'.
  196:                    &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  197:                    '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  198:                    'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  199:                    ' />'.$lt{'cust'}.':</label>&nbsp;'.
  200:                    '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  201:                    'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  202:                    ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  203:                    &Apache::loncommon::end_data_table_row()."\n";
  204:     }
  205:     return $output;
  206: }
  207: 
  208: sub user_quota_js {
  209:     return  <<"END_SCRIPT";
  210: <script type="text/javascript">
  211: // <![CDATA[
  212: function quota_changes(caller,context) {
  213:     var customoff = document.getElementById('custom_'+context+'quota_off');
  214:     var customon = document.getElementById('custom_'+context+'quota_on');
  215:     var number = document.getElementById(context+'quota');
  216:     if (caller == "custom") {
  217:         if (customoff) {
  218:             if (customoff.checked) {
  219:                 number.value = "";
  220:             }
  221:         }
  222:     }
  223:     if (caller == "quota") {
  224:         if (customon) {
  225:             customon.checked = true;
  226:         }
  227:     }
  228:     return;
  229: }
  230: // ]]>
  231: </script>
  232: END_SCRIPT
  233: 
  234: }
  235: 
  236: sub set_custom_js {
  237:     return  <<"END_SCRIPT";
  238: 
  239: <script type="text/javascript">
  240: // <![CDATA[
  241: function toggleCustom(form,item,name) {
  242:     if (document.getElementById(item)) {
  243:         var divid = document.getElementById(item);
  244:         var radioname = form.elements[name];
  245:         if (radioname) {
  246:             if (radioname.length > 0) {
  247:                 var setvis;
  248:                 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 co-authors",
  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:         @usertools = ('webdav','editors','managers');
  329:         $colspan = ' colspan="2"';
  330:     } else {
  331:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  332:                           'tools.aboutme','tools.portfolio','tools.blog',
  333:                           'tools.timezone','tools.portaccess');
  334:         @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
  335:         $colspan = ' colspan="2"';
  336:     }
  337:     foreach my $item (@usertools) {
  338:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  339:             $currdisp,$custdisp,$custradio,$onclick);
  340:         $cust_off = 'checked="checked" ';
  341:         $tool_on = 'checked="checked" ';
  342:         $curr_access =
  343:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  344:                                               $context,\%userenv,'',
  345:                                               {'is_adv' => $isadv});
  346:         if ($context eq 'requestauthor') {
  347:             if ($userenv{$context} ne '') {
  348:                 $cust_on = ' checked="checked" ';
  349:                 $cust_off = '';
  350:             }
  351:         } elsif ($context eq 'authordefaults') {
  352:             if ($item eq 'editors') {
  353:                 if ($userenv{'author'.$item} ne '') {
  354:                     $cust_on = ' checked="checked" ';
  355:                     $cust_off = '';
  356:                 }
  357:             } elsif ($item eq 'webdav') {
  358:                 if ($userenv{'tools.'.$item} ne '') {
  359:                     $cust_on = ' checked="checked" ';
  360:                     $cust_off = '';
  361:                 }
  362:             }
  363:         } elsif ($userenv{$context.'.'.$item} ne '') {
  364:             $cust_on = ' checked="checked" ';
  365:             $cust_off = '';
  366:         }
  367:         if ($context eq 'requestcourses') {
  368:             if ($userenv{$context.'.'.$item} eq '') {
  369:                 $custom_access = &mt('Currently from default setting.');
  370:                 $customsty = ' style="display:none;"';
  371:             } else {
  372:                 $custom_access = &mt('Currently from custom setting.');
  373:                 $customsty = ' style="display:block;"';
  374:             }
  375:         } elsif ($context eq 'requestauthor') {
  376:             if ($userenv{$context} eq '') {
  377:                 $custom_access = &mt('Currently from default setting.');
  378:                 $customsty = ' style="display:none;"';
  379:             } else {
  380:                 $custom_access = &mt('Currently from custom setting.');
  381:                 $customsty = ' style="display:block;"';
  382:             }
  383:         } elsif ($item eq 'editors') {
  384:             if ($userenv{'author'.$item} eq '') {
  385:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
  386:                     @defaulteditors = @{$domconfig{'authordefaults'}{'editors'}};
  387:                 } else {
  388:                     @defaulteditors = ('edit','xml');
  389:                 }
  390:                 $custom_access = &mt('Can use: [_1]',
  391:                                                join(', ', map { $lt{$_} } @defaulteditors));
  392:                 $editorsty = ' style="display:none;"';
  393:             } else {
  394:                 $custom_access = &mt('Currently from custom setting.');
  395:                 foreach my $editor (split(/,/,$userenv{'author'.$item})) {
  396:                     if ($editor =~ /^(edit|daxe|xml)$/) {
  397:                         push(@customeditors,$editor);
  398:                     }
  399:                 }
  400:                 if (@customeditors) {
  401:                     if (@customeditors > 1) {
  402:                         $custom_access .= '<br /><span>';
  403:                     } else {
  404:                         $custom_access .= ' <span class="LC_nobreak">';
  405:                     }
  406:                     $custom_access .= &mt('Can use: [_1]',
  407:                                           join(', ', map { $lt{$_} } @customeditors)).
  408:                                       '</span>';
  409:                 } else {
  410:                     $custom_access .= ' '.&mt('No available editors');
  411:                 }
  412:                 $editorsty = ' style="display:block;"';
  413:             }
  414:         } elsif ($item eq 'managers') {
  415:             my %ca_roles = &Apache::lonnet::get_my_roles($ccuname,$ccdomain,undef,
  416:                                                          ['active','future'],['ca']);
  417:             if (keys(%ca_roles)) {
  418:                 foreach my $entry (sort(keys(%ca_roles))) {
  419:                     if ($entry =~ /^($match_username\:$match_domain):ca$/) {
  420:                         my $user = $1;
  421:                         unless ($user eq "$ccuname:$ccdomain") {
  422:                             push(@possmanagers,$user);
  423:                         }
  424:                     }
  425:                 }
  426:             }
  427:             if ($userenv{'author'.$item} eq '') {
  428:                 $custom_access = &mt('Currently author manages co-author roles');
  429:             } else {
  430:                 if (keys(%ca_roles)) {
  431:                     foreach my $user (split(/,/,$userenv{'author'.$item})) {
  432:                         if ($user =~ /^($match_username):($match_domain)$/) {
  433:                             if (exists($ca_roles{$user.':ca'})) {
  434:                                 unless ($user eq "$ccuname:$ccdomain") {
  435:                                     push(@custommanagers,$user);
  436:                                 }
  437:                             }
  438:                         }
  439:                     }
  440:                 }
  441:                 if (@custommanagers) {
  442:                     $custom_access = &mt('Co-authors who manage co-author roles: [_1]',
  443:                                          join(', ',@custommanagers));
  444:                 } else {
  445:                     $custom_access = &mt('Currently author manages co-author roles');
  446:                 }
  447:             }
  448:         } else {
  449:             my $current = $userenv{$context.'.'.$item};
  450:             if ($item eq 'webdav') {
  451:                 $current = $userenv{'tools.webdav'};
  452:             }
  453:             if ($current eq '') {
  454:                 $custom_access =
  455:                     &mt('Availability determined currently from default setting.');
  456:                 if (!$curr_access) {
  457:                     $tool_off = 'checked="checked" ';
  458:                     $tool_on = '';
  459:                 }
  460:                 $customsty = ' style="display:none;"';
  461:             } else {
  462:                 $custom_access =
  463:                     &mt('Availability determined currently from custom setting.');
  464:                 if ($current == 0) {
  465:                     $tool_off = 'checked="checked" ';
  466:                     $tool_on = '';
  467:                 }
  468:                 $customsty = ' style="display:inline;"';
  469:             }
  470:         }
  471:         $output .= '  <tr class="LC_info_row">'."\n".
  472:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  473:                    '  </tr>'."\n".
  474:                    &Apache::loncommon::start_data_table_row()."\n";
  475:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  476:             my ($curroption,$currlimit,$customsty);
  477:             my $envkey = $context.'.'.$item;
  478:             if ($context eq 'requestauthor') {
  479:                 $envkey = $context;
  480:             }
  481:             if ($userenv{$envkey} ne '') {
  482:                 $curroption = $userenv{$envkey};
  483:                 $customsty = ' style="display:block"';
  484:             } else {
  485:                 $customsty = ' style="display:none"';
  486:                 my (@inststatuses);
  487:                 if ($context eq 'requestcourses') {
  488:                     $curroption =
  489:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  490:                                                                       $isadv,$ccdomain,$item,
  491:                                                                       \@inststatuses,\%domconfig);
  492:                 } else {
  493:                      $curroption = 
  494:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  495:                                                                        $isadv,$ccdomain,undef,
  496:                                                                        \@inststatuses,\%domconfig);
  497:                 }
  498:             }
  499:             if (!$curroption) {
  500:                 $curroption = 'norequest';
  501:             }
  502:             my $name = 'crsreq_'.$item;
  503:             if ($context eq 'requestauthor') {
  504:                 $name = $item;
  505:             }
  506:             $onclick = ' onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');"';
  507:             if ($curroption =~ /^autolimit=(\d*)$/) {
  508:                 $currlimit = $1;
  509:                 if ($currlimit eq '') {
  510:                     $currdisp = &mt('Yes, automatic creation');
  511:                 } else {
  512:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  513:                 }
  514:             } else {
  515:                 $currdisp = $reqdisplay{$curroption};
  516:             }
  517:             $custdisp = '<fieldset id="customtext_'.$item.'"'.$customsty.'>';
  518:             foreach my $option (@options) {
  519:                 my $val = $option;
  520:                 if ($option eq 'norequest') {
  521:                     $val = 0;
  522:                 }
  523:                 if ($option eq 'validate') {
  524:                     my $canvalidate = 0;
  525:                     if (ref($validations{$item}) eq 'HASH') {
  526:                         if ($validations{$item}{'_custom_'}) {
  527:                             $canvalidate = 1;
  528:                         }
  529:                     }
  530:                     next if (!$canvalidate);
  531:                 }
  532:                 my $checked = '';
  533:                 if ($option eq $curroption) {
  534:                     $checked = ' checked="checked"';
  535:                 } elsif ($option eq 'autolimit') {
  536:                     if ($curroption =~ /^autolimit/) {
  537:                         $checked = ' checked="checked"';
  538:                     }
  539:                 }
  540:                 if ($option eq 'autolimit') {
  541:                     $custdisp .= '<br />';
  542:                 }
  543:                 $custdisp .= '<span class="LC_nobreak"><label>'.
  544:                              '<input type="radio" name="'.$name.'" '.
  545:                              'value="'.$val.'"'.$checked.' />'.
  546:                              $reqtitles{$option}.'</label>&nbsp;';
  547:                 if ($option eq 'autolimit') {
  548:                     $custdisp .= '<input type="text" name="'.$name.
  549:                                  '_limit" size="1" '.
  550:                                  'value="'.$currlimit.'" />&nbsp;'.
  551:                                  $reqtitles{'unlimited'}.'</span>';
  552:                 } else {
  553:                     $custdisp .= '</span>';
  554:                 }
  555:                 $custdisp .= ' ';
  556:             }
  557:             $custdisp .= '</fieldset>';
  558:             $custradio = '<br />'.$custdisp;
  559:         } elsif ($item eq 'editors') {
  560:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  561:                        &Apache::loncommon::end_data_table_row()."\n";
  562:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  563:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  564:                           '<td'.$colspan.'><span class="LC_nobreak">'.
  565:                           $lt{'chse'}.': <label>'.
  566:                           '<input type="radio" name="custom'.$item.'" value="0" '.
  567:                           $cust_off.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  568:                           $lt{'usde'}.'</label>'.('&nbsp;' x3).
  569:                           '<label><input type="radio" name="custom'.$item.'" value="1" '.
  570:                           $cust_on.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  571:                           $lt{'uscu'}.'</label></span><br />'.
  572:                           '<fieldset id="customtext_'.$item.'"'.$editorsty.'>';
  573:                 foreach my $editor ('edit','xml','daxe') {
  574:                     my $checked;
  575:                     if ($userenv{'author'.$item} eq '') {
  576:                         if (grep(/^\Q$editor\E$/,@defaulteditors)) {
  577:                             $checked = ' checked="checked"';
  578:                         }
  579:                     } elsif (grep(/^\Q$editor\E$/,@customeditors)) {
  580:                         $checked = ' checked="checked"';
  581:                     }
  582:                     $output .= '<span style="LC_nobreak"><label>'.
  583:                                '<input type="checkbox" name="custom_editor" '.
  584:                                'value="'.$editor.'"'.$checked.' />'.
  585:                                $lt{$editor}.'</label></span> ';
  586:                 }
  587:                 $output .= '</fieldset></td>'.
  588:                            &Apache::loncommon::end_data_table_row()."\n";
  589:             }
  590:         } elsif ($item eq 'managers') {
  591:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  592:                        &Apache::loncommon::end_data_table_row()."\n";
  593:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  594:                 $output .=
  595:                     &Apache::loncommon::start_data_table_row()."\n".
  596:                     '<td'.$colspan.'>';
  597:                 if (@possmanagers) {
  598:                     $output .= &mt('Select manager(s)').': ';
  599:                     foreach my $user (@possmanagers) {
  600:                         my $checked;
  601:                         if (grep(/^\Q$user\E$/,@custommanagers)) {
  602:                             $checked = ' checked="checked"';
  603:                         }
  604:                         $output .= '<span style="LC_nobreak"><label>'.
  605:                                    '<input type="checkbox" name="custommanagers" '.
  606:                                    'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
  607:                                    $user.'</label></span> ';
  608:                     }
  609:                 } else {
  610:                     $output .= &mt('No co-author roles assignable as manager');
  611:                 }
  612:                 $output .= '</td>'.
  613:                            &Apache::loncommon::end_data_table_row()."\n";
  614:             }
  615:         } else {
  616:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  617:             my $name = $context.'_'.$item;
  618:             $onclick = 'onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');" ';
  619:             $custdisp = '<span class="LC_nobreak"><label>'.
  620:                         '<input type="radio" name="'.$name.'"'.
  621:                         ' value="1" '.$tool_on.$onclick.'/>'.&mt('On').'</label>&nbsp;<label>'.
  622:                         '<input type="radio" name="'.$name.'" value="0" '.
  623:                         $tool_off.$onclick.'/>'.&mt('Off').'</label></span>';
  624:             $custradio = '<span id="customtext_'.$item.'"'.$customsty.' class="LC_nobreak">'.
  625:                          '--'.$lt{'cusa'}.':&nbsp;'.$custdisp.'</span>';
  626:         }
  627:         unless (($item eq 'editors') || ($item eq 'managers')) {
  628:             $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  629:                        $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  630:                        &Apache::loncommon::end_data_table_row()."\n";
  631:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  632:                 $output .=
  633:                    &Apache::loncommon::start_data_table_row()."\n".
  634:                    '<td><span class="LC_nobreak">'.
  635:                    $lt{'chse'}.': <label>'.
  636:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  637:                    $cust_off.$onclick.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  638:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  639:                    $cust_on.$onclick.'/>'.$lt{'uscu'}.'</label></span>';
  640:                 if ($colspan) {
  641:                     $output .= '</td><td>';
  642:                 }
  643:                 $output .= $custradio.'</td>'.
  644:                            &Apache::loncommon::end_data_table_row()."\n";
  645:             }
  646:         }
  647:     }
  648:     return $output;
  649: }
  650: 
  651: sub coursereq_externaluser {
  652:     my ($ccuname,$ccdomain,$cdom) = @_;
  653:     my (@usertools,@options,%validations,%userenv,$output);
  654:     my %lt = &Apache::lonlocal::texthash (
  655:                    'official'   => 'Can request creation of official courses',
  656:                    'unofficial' => 'Can request creation of unofficial courses',
  657:                    'community'  => 'Can request creation of communities',
  658:                    'textbook'   => 'Can request creation of textbook courses',
  659:                    'placement'  => 'Can request creation of placement tests',
  660:     );
  661: 
  662:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  663:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  664:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  665:                       'reqcrsotherdom.placement');
  666:     @usertools = ('official','unofficial','community','textbook','placement');
  667:     @options = ('approval','validate','autolimit');
  668:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  669:     my $optregex = join('|',@options);
  670:     my %reqtitles = &courserequest_titles();
  671:     foreach my $item (@usertools) {
  672:         my ($curroption,$currlimit,$tooloff);
  673:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  674:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  675:             foreach my $req (@curr) {
  676:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  677:                     $curroption = $1;
  678:                     $currlimit = $2;
  679:                     last;
  680:                 }
  681:             }
  682:             if (!$curroption) {
  683:                 $curroption = 'norequest';
  684:                 $tooloff = ' checked="checked"';
  685:             }
  686:         } else {
  687:             $curroption = 'norequest';
  688:             $tooloff = ' checked="checked"';
  689:         }
  690:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  691:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  692:                   '<table><tr><td valign="top">'."\n".
  693:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  694:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  695:                   '</label></td>';
  696:         foreach my $option (@options) {
  697:             if ($option eq 'validate') {
  698:                 my $canvalidate = 0;
  699:                 if (ref($validations{$item}) eq 'HASH') {
  700:                     if ($validations{$item}{'_external_'}) {
  701:                         $canvalidate = 1;
  702:                     }
  703:                 }
  704:                 next if (!$canvalidate);
  705:             }
  706:             my $checked = '';
  707:             if ($option eq $curroption) {
  708:                 $checked = ' checked="checked"';
  709:             }
  710:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  711:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  712:                        '" value="'.$option.'"'.$checked.' />'.
  713:                        $reqtitles{$option}.'</label>';
  714:             if ($option eq 'autolimit') {
  715:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  716:                            $item.'_limit" size="1" '.
  717:                            'value="'.$currlimit.'" /></span>'.
  718:                            '<br />'.$reqtitles{'unlimited'};
  719:             } else {
  720:                 $output .= '</span>';
  721:             }
  722:             $output .= '</td>';
  723:         }
  724:         $output .= '</td></tr></table></td>'."\n".
  725:                    &Apache::loncommon::end_data_table_row()."\n";
  726:     }
  727:     return $output;
  728: }
  729: 
  730: sub domainrole_req {
  731:     my ($ccuname,$ccdomain) = @_;
  732:     return '<br /><h3>'.
  733:            &mt('Can Request Assignment of Domain Roles?').
  734:            '</h3>'."\n".
  735:            &Apache::loncommon::start_data_table().
  736:            &build_tools_display($ccuname,$ccdomain,
  737:                                 'requestauthor').
  738:            &Apache::loncommon::end_data_table();
  739: }
  740: 
  741: sub authoring_defaults {
  742:     my ($ccuname,$ccdomain) = @_;
  743:     return '<br /><h3>'.
  744:            &mt('Authoring Space defaults (if role assigned)').
  745:            '</h3>'."\n".
  746:            &Apache::loncommon::start_data_table().
  747:            &build_tools_display($ccuname,$ccdomain,
  748:                                 'authordefaults').
  749:            &user_quotas($ccuname,$ccdomain,'author').
  750:            &Apache::loncommon::end_data_table();
  751: }
  752: 
  753: sub courserequest_titles {
  754:     my %titles = &Apache::lonlocal::texthash (
  755:                                    official   => 'Official',
  756:                                    unofficial => 'Unofficial',
  757:                                    community  => 'Communities',
  758:                                    textbook   => 'Textbook',
  759:                                    placement  => 'Placement Tests',
  760:                                    lti        => 'LTI Provider',
  761:                                    norequest  => 'Not allowed',
  762:                                    approval   => 'Approval by Dom. Coord.',
  763:                                    validate   => 'With validation',
  764:                                    autolimit  => 'Numerical limit',
  765:                                    unlimited  => '(blank for unlimited)',
  766:                  );
  767:     return %titles;
  768: }
  769: 
  770: sub courserequest_display {
  771:     my %titles = &Apache::lonlocal::texthash (
  772:                                    approval   => 'Yes, need approval',
  773:                                    validate   => 'Yes, with validation',
  774:                                    norequest  => 'No',
  775:    );
  776:    return %titles;
  777: }
  778: 
  779: sub requestauthor_titles {
  780:     my %titles = &Apache::lonlocal::texthash (
  781:                                    norequest  => 'Not allowed',
  782:                                    approval   => 'Approval by Dom. Coord.',
  783:                                    automatic  => 'Automatic approval',
  784:                  );
  785:     return %titles;
  786: 
  787: }
  788: 
  789: sub requestauthor_display {
  790:     my %titles = &Apache::lonlocal::texthash (
  791:                                    approval   => 'Yes, need approval',
  792:                                    automatic  => 'Yes, automatic approval',
  793:                                    norequest  => 'No',
  794:    );
  795:    return %titles;
  796: }
  797: 
  798: sub requestchange_display {
  799:     my %titles = &Apache::lonlocal::texthash (
  800:                                    approval   => "availability set to 'on' (approval required)", 
  801:                                    automatic  => "availability set to 'on' (automatic approval)",
  802:                                    norequest  => "availability set to 'off'",
  803:    );
  804:    return %titles;
  805: }
  806: 
  807: sub curr_requestauthor {
  808:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  809:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  810:     if ($uname eq '' || $udom eq '') {
  811:         $uname = $env{'user.name'};
  812:         $udom = $env{'user.domain'};
  813:         $isadv = $env{'user.adv'};
  814:     }
  815:     my (%userenv,%settings,$val);
  816:     my @options = ('automatic','approval');
  817:     %userenv =
  818:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  819:     if ($userenv{'requestauthor'}) {
  820:         $val = $userenv{'requestauthor'};
  821:         @{$inststatuses} = ('_custom_');
  822:     } else {
  823:         my %alltasks;
  824:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  825:             %settings = %{$domconfig->{'requestauthor'}};
  826:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  827:                 $val = $settings{'_LC_adv'};
  828:                 @{$inststatuses} = ('_LC_adv_');
  829:             } else {
  830:                 if ($userenv{'inststatus'} ne '') {
  831:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  832:                 } else {
  833:                     @{$inststatuses} = ('default');
  834:                 }
  835:                 foreach my $status (@{$inststatuses}) {
  836:                     if (exists($settings{$status})) {
  837:                         my $value = $settings{$status};
  838:                         next unless ($value);
  839:                         unless (exists($alltasks{$value})) {
  840:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  841:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  842:                                     push(@{$alltasks{$value}},$status);
  843:                                 }
  844:                             } else {
  845:                                 @{$alltasks{$value}} = ($status);
  846:                             }
  847:                         }
  848:                     }
  849:                 }
  850:                 foreach my $option (@options) {
  851:                     if ($alltasks{$option}) {
  852:                         $val = $option;
  853:                         last;
  854:                     }
  855:                 }
  856:             }
  857:         }
  858:     }
  859:     return $val;
  860: }
  861: 
  862: # =================================================================== Phase one
  863: 
  864: sub print_username_entry_form {
  865:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  866:         $permission) = @_;
  867:     my $defdom=$env{'request.role.domain'};
  868:     my $formtoset = 'crtuser';
  869:     if (exists($env{'form.startrolename'})) {
  870:         $formtoset = 'docustom';
  871:         $env{'form.rolename'} = $env{'form.startrolename'};
  872:     } elsif ($env{'form.origform'} eq 'crtusername') {
  873:         $formtoset =  $env{'form.origform'};
  874:     }
  875: 
  876:     my ($jsback,$elements) = &crumb_utilities();
  877: 
  878:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  879:         '<script type="text/javascript">'."\n".
  880:         '// <![CDATA['."\n".
  881:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  882:         '// ]]>'."\n".
  883:         '</script>'."\n";
  884: 
  885:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  886:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  887:         && (&Apache::lonnet::allowed('mcr','/'))) {
  888:         $jscript .= &customrole_javascript();
  889:     }
  890:     my $helpitem = 'Course_Change_Privileges';
  891:     if ($env{'form.action'} eq 'custom') {
  892:         if ($context eq 'course') {
  893:             $helpitem = 'Course_Editing_Custom_Roles';
  894:         } elsif ($context eq 'domain') {
  895:             $helpitem = 'Domain_Editing_Custom_Roles';
  896:         }
  897:     } elsif ($env{'form.action'} eq 'singlestudent') {
  898:         $helpitem = 'Course_Add_Student';
  899:     } elsif ($env{'form.action'} eq 'accesslogs') {
  900:         $helpitem = 'Domain_User_Access_Logs';
  901:     } elsif ($context eq 'author') {
  902:         $helpitem = 'Author_Change_Privileges';
  903:     } elsif ($context eq 'domain') {
  904:         if ($permission->{'cusr'}) {
  905:             $helpitem = 'Domain_Change_Privileges';
  906:         } elsif ($permission->{'view'}) {
  907:             $helpitem = 'Domain_View_Privileges';
  908:         } else {
  909:             undef($helpitem);
  910:         }
  911:     }
  912:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  913:     if ($env{'form.action'} eq 'custom') {
  914:         push(@{$brcrum},
  915:                  {href=>"javascript:backPage(document.crtuser)",       
  916:                   text=>"Pick custom role",
  917:                   help => $helpitem,}
  918:                  );
  919:     } else {
  920:         push (@{$brcrum},
  921:                   {href => "javascript:backPage(document.crtuser)",
  922:                    text => $breadcrumb_text{'search'},
  923:                    help => $helpitem,
  924:                    faq  => 282,
  925:                    bug  => 'Instructor Interface',}
  926:                   );
  927:     }
  928:     my %loaditems = (
  929:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  930:                     );
  931:     my $args = {bread_crumbs           => $brcrum,
  932:                 bread_crumbs_component => 'User Management',
  933:                 add_entries            => \%loaditems,};
  934:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  935: 
  936:     my %lt=&Apache::lonlocal::texthash(
  937:                     'srst' => 'Search for a user and enroll as a student',
  938:                     'srme' => 'Search for a user and enroll as a member',
  939:                     'srad' => 'Search for a user and modify/add user information or roles',
  940:                     'srvu' => 'Search for a user and view user information and roles',
  941:                     'srva' => 'Search for a user and view access log information',
  942: 		    'usr'  => "Username",
  943:                     'dom'  => "Domain",
  944:                     'ecrp' => "Define or Edit Custom Role",
  945:                     'nr'   => "role name",
  946:                     'cre'  => "Next",
  947: 				       );
  948: 
  949:     if ($env{'form.action'} eq 'custom') {
  950:         if (&Apache::lonnet::allowed('mcr','/')) {
  951:             my $newroletext = &mt('Define new custom role:');
  952:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  953:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  954:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  955:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  956:                       &Apache::loncommon::start_data_table().
  957:                       &Apache::loncommon::start_data_table_row().
  958:                       '<td>');
  959:             if (keys(%existingroles) > 0) {
  960:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  961:             } else {
  962:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  963:             }
  964:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  965:                       &Apache::loncommon::end_data_table_row());
  966:             if (keys(%existingroles) > 0) {
  967:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  968:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  969:                           &mt('View/Modify existing role:').'</b></label></td>'.
  970:                           '<td align="center"><br />'.
  971:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  972:                           '<option value="" selected="selected">'.
  973:                           &mt('Select'));
  974:                 foreach my $role (sort(keys(%existingroles))) {
  975:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  976:                 }
  977:                 $r->print('</select>'.
  978:                           '</td>'.
  979:                           &Apache::loncommon::end_data_table_row());
  980:             }
  981:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  982:                       '<input name="customeditor" type="submit" value="'.
  983:                       $lt{'cre'}.'" /></p>'.
  984:                       '</form>');
  985:         }
  986:     } else {
  987:         my $actiontext = $lt{'srad'};
  988:         my $fixeddom;
  989:         if ($env{'form.action'} eq 'singlestudent') {
  990:             if ($crstype eq 'Community') {
  991:                 $actiontext = $lt{'srme'};
  992:             } else {
  993:                 $actiontext = $lt{'srst'};
  994:             }
  995:         } elsif ($env{'form.action'} eq 'accesslogs') {
  996:             $actiontext = $lt{'srva'};
  997:             $fixeddom = 1;
  998:         } elsif (($env{'form.action'} eq 'singleuser') &&
  999:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
 1000:             $actiontext = $lt{'srvu'};
 1001:             $fixeddom = 1;
 1002:         }
 1003:         $r->print("<h3>$actiontext</h3>");
 1004:         if ($env{'form.origform'} ne 'crtusername') {
 1005:             if ($response) {
 1006:                $r->print("\n<div>$response</div>".
 1007:                          '<br clear="all" />');
 1008:             }
 1009:         }
 1010:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
 1011:     }
 1012: }
 1013: 
 1014: sub customrole_javascript {
 1015:     my $js = <<"END";
 1016: <script type="text/javascript">
 1017: // <![CDATA[
 1018: 
 1019: function setCustomFields() {
 1020:     if (document.docustom.customroleaction.length > 0) {
 1021:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1022:             if (document.docustom.customroleaction[i].checked) {
 1023:                 if (document.docustom.customroleaction[i].value == 'new') {
 1024:                     document.docustom.rolename.selectedIndex = 0;
 1025:                 } else {
 1026:                     document.docustom.newrolename.value = '';
 1027:                 }
 1028:             }
 1029:         }
 1030:     }
 1031:     return;
 1032: }
 1033: 
 1034: function setCustomAction(caller) {
 1035:     if (document.docustom.customroleaction.length > 0) {
 1036:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1037:             if (document.docustom.customroleaction[i].value == caller) {
 1038:                 document.docustom.customroleaction[i].checked = true;
 1039:             }
 1040:         }
 1041:     }
 1042:     setCustomFields();
 1043:     return;
 1044: }
 1045: 
 1046: // ]]>
 1047: </script>
 1048: END
 1049:     return $js;
 1050: }
 1051: 
 1052: sub entry_form {
 1053:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
 1054:     my ($usertype,$inexact);
 1055:     if (ref($srch) eq 'HASH') {
 1056:         if (($srch->{'srchin'} eq 'dom') &&
 1057:             ($srch->{'srchby'} eq 'uname') &&
 1058:             ($srch->{'srchtype'} eq 'exact') &&
 1059:             ($srch->{'srchdomain'} ne '') &&
 1060:             ($srch->{'srchterm'} ne '')) {
 1061:             my (%curr_rules,%got_rules);
 1062:             my ($rules,$ruleorder) =
 1063:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
 1064:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
 1065:         } else {
 1066:             $inexact = 1;
 1067:         }
 1068:     }
 1069:     my ($cancreate,$noinstd);
 1070:     if ($env{'form.action'} eq 'accesslogs') {
 1071:         $noinstd = 1;
 1072:     } else {
 1073:         $cancreate =
 1074:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
 1075:     }
 1076:     my ($userpicker,$cansearch) = 
 1077:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
 1078:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
 1079:     my $srchbutton = &mt('Search');
 1080:     if ($env{'form.action'} eq 'singlestudent') {
 1081:         $srchbutton = &mt('Search and Enroll');
 1082:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1083:         $srchbutton = &mt('Search');
 1084:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
 1085:         $srchbutton = &mt('Search or Add New User');
 1086:     }
 1087:     my $output;
 1088:     if ($cansearch) {
 1089:         $output = <<"ENDBLOCK";
 1090: <form action="/adm/createuser" method="post" name="crtuser">
 1091: <input type="hidden" name="action" value="$env{'form.action'}" />
 1092: <input type="hidden" name="phase" value="get_user_info" />
 1093: $userpicker
 1094: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 1095: </form>
 1096: ENDBLOCK
 1097:     } else {
 1098:         $output = '<p>'.$userpicker.'</p>';
 1099:     }
 1100:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
 1101:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1102:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
 1103:         my $defdom=$env{'request.role.domain'};
 1104:         my ($trusted,$untrusted);
 1105:         if ($context eq 'course') {
 1106:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
 1107:         } elsif ($context eq 'author') {
 1108:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
 1109:         } elsif ($context eq 'domain') {
 1110:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
 1111:         }
 1112:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
 1113:         my %lt=&Apache::lonlocal::texthash(
 1114:                   'enro' => 'Enroll one student',
 1115:                   'enrm' => 'Enroll one member',
 1116:                   'admo' => 'Add/modify a single user',
 1117:                   'crea' => 'create new user if required',
 1118:                   'uskn' => "username is known",
 1119:                   'crnu' => 'Create a new user',
 1120:                   'usr'  => 'Username',
 1121:                   'dom'  => 'in domain',
 1122:                   'enrl' => 'Enroll',
 1123:                   'cram'  => 'Create/Modify user',
 1124:         );
 1125:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
 1126:         my ($title,$buttontext,$showresponse);
 1127:         if ($env{'form.action'} eq 'singlestudent') {
 1128:             if ($crstype eq 'Community') {
 1129:                 $title = $lt{'enrm'};
 1130:             } else {
 1131:                 $title = $lt{'enro'};
 1132:             }
 1133:             $buttontext = $lt{'enrl'};
 1134:         } else {
 1135:             $title = $lt{'admo'};
 1136:             $buttontext = $lt{'cram'};
 1137:         }
 1138:         if ($cancreate) {
 1139:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
 1140:         } else {
 1141:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
 1142:         }
 1143:         if ($env{'form.origform'} eq 'crtusername') {
 1144:             $showresponse = $responsemsg;
 1145:         }
 1146:         $output .= <<"ENDDOCUMENT";
 1147: <br />
 1148: <form action="/adm/createuser" method="post" name="crtusername">
 1149: <input type="hidden" name="action" value="$env{'form.action'}" />
 1150: <input type="hidden" name="phase" value="createnewuser" />
 1151: <input type="hidden" name="srchtype" value="exact" />
 1152: <input type="hidden" name="srchby" value="uname" />
 1153: <input type="hidden" name="srchin" value="dom" />
 1154: <input type="hidden" name="forcenewuser" value="1" />
 1155: <input type="hidden" name="origform" value="crtusername" />
 1156: <h3>$title</h3>
 1157: $showresponse
 1158: <table>
 1159:  <tr>
 1160:   <td>$lt{'usr'}:</td>
 1161:   <td><input type="text" size="15" name="srchterm" /></td>
 1162:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
 1163:   <td>&nbsp;$sellink&nbsp;</td>
 1164:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
 1165:  </tr>
 1166: </table>
 1167: </form>
 1168: ENDDOCUMENT
 1169:     }
 1170:     return $output;
 1171: }
 1172: 
 1173: sub user_modification_js {
 1174:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1175:     
 1176:     return <<END;
 1177: <script type="text/javascript" language="Javascript">
 1178: // <![CDATA[
 1179: 
 1180:     $pjump_def
 1181:     $dc_setcourse_code
 1182: 
 1183:     function dateset() {
 1184:         eval("document.cu."+document.cu.pres_marker.value+
 1185:             ".value=document.cu.pres_value.value");
 1186:         modalWindow.close();
 1187:     }
 1188: 
 1189:     $nondc_setsection_code
 1190: // ]]>
 1191: </script>
 1192: END
 1193: }
 1194: 
 1195: # =================================================================== Phase two
 1196: sub print_user_selection_page {
 1197:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1198:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1199:     my $sortby = $env{'form.sortby'};
 1200: 
 1201:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1202:         $sortby = 'lastname';
 1203:     }
 1204: 
 1205:     my ($jsback,$elements) = &crumb_utilities();
 1206: 
 1207:     my $jscript = (<<ENDSCRIPT);
 1208: <script type="text/javascript">
 1209: // <![CDATA[
 1210: function pickuser(uname,udom) {
 1211:     document.usersrchform.seluname.value=uname;
 1212:     document.usersrchform.seludom.value=udom;
 1213:     document.usersrchform.phase.value="userpicked";
 1214:     document.usersrchform.submit();
 1215: }
 1216: 
 1217: $jsback
 1218: // ]]>
 1219: </script>
 1220: ENDSCRIPT
 1221: 
 1222:     my %lt=&Apache::lonlocal::texthash(
 1223:                                        'usrch'          => "User Search to add/modify roles",
 1224:                                        'stusrch'        => "User Search to enroll student",
 1225:                                        'memsrch'        => "User Search to enroll member",
 1226:                                        'srcva'          => "Search for a user and view access log information",
 1227:                                        'usrvu'          => "User Search to view user roles",
 1228:                                        'usel'           => "Select a user to add/modify roles",
 1229:                                        'suvr'           => "Select a user to view roles",
 1230:                                        'stusel'         => "Select a user to enroll as a student",
 1231:                                        'memsel'         => "Select a user to enroll as a member",
 1232:                                        'vacsel'         => "Select a user to view access log",
 1233:                                        'username'       => "username",
 1234:                                        'domain'         => "domain",
 1235:                                        'lastname'       => "last name",
 1236:                                        'firstname'      => "first name",
 1237:                                        'permanentemail' => "permanent e-mail",
 1238:                                       );
 1239:     if ($context eq 'requestcrs') {
 1240:         $r->print('<div>');
 1241:     } else {
 1242:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1243:         my $helpitem;
 1244:         if ($env{'form.action'} eq 'singleuser') {
 1245:             $helpitem = 'Course_Change_Privileges';
 1246:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1247:             $helpitem = 'Course_Add_Student';
 1248:         } elsif ($context eq 'author') {
 1249:             $helpitem = 'Author_Change_Privileges';
 1250:         } elsif ($context eq 'domain') {
 1251:             $helpitem = 'Domain_Change_Privileges';
 1252:         }
 1253:         push (@{$brcrum},
 1254:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1255:                    text => $breadcrumb_text{'search'},
 1256:                    faq  => 282,
 1257:                    bug  => 'Instructor Interface',},
 1258:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1259:                    text => $breadcrumb_text{'userpicked'},
 1260:                    faq  => 282,
 1261:                    bug  => 'Instructor Interface',
 1262:                    help => $helpitem}
 1263:                   );
 1264:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1265:         if ($env{'form.action'} eq 'singleuser') {
 1266:             my $readonly;
 1267:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1268:                 $readonly = 1;
 1269:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1270:             } else {
 1271:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1272:             }
 1273:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1274:             if ($readonly) {
 1275:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1276:             } else {
 1277:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1278:             }
 1279:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1280:             $r->print($jscript."<b>");
 1281:             if ($crstype eq 'Community') {
 1282:                 $r->print($lt{'memsrch'});
 1283:             } else {
 1284:                 $r->print($lt{'stusrch'});
 1285:             }
 1286:             $r->print("</b><br />");
 1287:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1288:             $r->print('</form><h3>');
 1289:             if ($crstype eq 'Community') {
 1290:                 $r->print($lt{'memsel'});
 1291:             } else {
 1292:                 $r->print($lt{'stusel'});
 1293:             }
 1294:             $r->print('</h3>');
 1295:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1296:             $r->print("<b>$lt{'srcva'}</b><br />");
 1297:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1298:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1299:         }
 1300:     }
 1301:     $r->print('<form name="usersrchform" method="post" action="">'.
 1302:               &Apache::loncommon::start_data_table()."\n".
 1303:               &Apache::loncommon::start_data_table_header_row()."\n".
 1304:               ' <th> </th>'."\n");
 1305:     foreach my $field (@fields) {
 1306:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1307:                   "'".$field."'".';document.usersrchform.submit();">'.
 1308:                   $lt{$field}.'</a></th>'."\n");
 1309:     }
 1310:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1311: 
 1312:     my @sorted_users = sort {
 1313:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1314:             ||
 1315:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1316:             ||
 1317:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1318: 	    ||
 1319: 	lc($a) cmp lc($b)
 1320:         } (keys(%$srch_results));
 1321: 
 1322:     foreach my $user (@sorted_users) {
 1323:         my ($uname,$udom) = split(/:/,$user);
 1324:         my $onclick;
 1325:         if ($context eq 'requestcrs') {
 1326:             $onclick =
 1327:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1328:                                                "'$srch_results->{$user}->{firstname}',".
 1329:                                                "'$srch_results->{$user}->{lastname}',".
 1330:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1331:         } else {
 1332:             $onclick =
 1333:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1334:         }
 1335:         $r->print(&Apache::loncommon::start_data_table_row().
 1336:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1337:                   $onclick.' /></td>'.
 1338:                   '<td><tt>'.$uname.'</tt></td>'.
 1339:                   '<td><tt>'.$udom.'</tt></td>');
 1340:         foreach my $field ('lastname','firstname','permanentemail') {
 1341:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1342:         }
 1343:         $r->print(&Apache::loncommon::end_data_table_row());
 1344:     }
 1345:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1346:     if (ref($srcharray) eq 'ARRAY') {
 1347:         foreach my $item (@{$srcharray}) {
 1348:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1349:         }
 1350:     }
 1351:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1352:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1353:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1354:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1355:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1356:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1357:     if ($context eq 'requestcrs') {
 1358:         $r->print($opener_elements.'</form></div>');
 1359:     } else {
 1360:         $r->print($response.'</form>');
 1361:     }
 1362: }
 1363: 
 1364: sub print_user_query_page {
 1365:     my ($r,$caller,$brcrum) = @_;
 1366: # FIXME - this is for a network-wide name search (similar to catalog search)
 1367: # To use frames with similar behavior to catalog/portfolio search.
 1368: # To be implemented. 
 1369:     return;
 1370: }
 1371: 
 1372: sub print_user_modification_page {
 1373:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1374:         $brcrum,$showcredits) = @_;
 1375:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1376:         my $usermsg = &mt('No username and/or domain provided.');
 1377:         $env{'form.phase'} = '';
 1378: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1379:                                    $permission);
 1380:         return;
 1381:     }
 1382:     my ($form,$formname);
 1383:     if ($env{'form.action'} eq 'singlestudent') {
 1384:         $form = 'document.enrollstudent';
 1385:         $formname = 'enrollstudent';
 1386:     } else {
 1387:         $form = 'document.cu';
 1388:         $formname = 'cu';
 1389:     }
 1390:     my %abv_auth = &auth_abbrev();
 1391:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1392:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1393:     if ($uhome eq 'no_host') {
 1394:         my $usertype;
 1395:         my ($rules,$ruleorder) =
 1396:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1397:             $usertype =
 1398:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1399:                                                       \%curr_rules,\%got_rules);
 1400:         my $cancreate =
 1401:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1402:                                                    $usertype);
 1403:         if (!$cancreate) {
 1404:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1405:             my %usertypetext = (
 1406:                 official   => 'institutional',
 1407:                 unofficial => 'non-institutional',
 1408:             );
 1409:             my $response;
 1410:             if ($env{'form.origform'} eq 'crtusername') {
 1411:                 $response = '<span class="LC_warning">'.
 1412:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1413:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1414:                             '</span><br />';
 1415:             }
 1416:             $response .= '<p class="LC_warning">'
 1417:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1418:                         .' ';
 1419:             if ($context eq 'domain') {
 1420:                 $response .= &mt('Please contact a [_1] for assistance.',
 1421:                                  &Apache::lonnet::plaintext('dc'));
 1422:             } else {
 1423:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1424:                                 ,'<a href="'.$helplink.'">','</a>');
 1425:             }
 1426:             $response .= '</p><br />';
 1427:             $env{'form.phase'} = '';
 1428:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1429:                                        $permission);
 1430:             return;
 1431:         }
 1432:         $newuser = 1;
 1433:         my $checkhash;
 1434:         my $checks = { 'username' => 1 };
 1435:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1436:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1437:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1438:         if (ref($alerts{'username'}) eq 'HASH') {
 1439:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1440:                 my $domdesc =
 1441:                     &Apache::lonnet::domain($ccdomain,'description');
 1442:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1443:                     my $userchkmsg;
 1444:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1445:                         $userchkmsg = 
 1446:                             &Apache::loncommon::instrule_disallow_msg('username',
 1447:                                                                  $domdesc,1).
 1448:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1449:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1450:                             'username');
 1451:                     }
 1452:                     $env{'form.phase'} = '';
 1453:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1454:                                                $permission);
 1455:                     return;
 1456:                 }
 1457:             }
 1458:         }
 1459:     } else {
 1460:         $newuser = 0;
 1461:     }
 1462:     if ($response) {
 1463:         $response = '<br />'.$response;
 1464:     }
 1465: 
 1466:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1467:     my $dc_setcourse_code = '';
 1468:     my $nondc_setsection_code = '';                                        
 1469:     my %loaditem;
 1470: 
 1471:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1472: 
 1473:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1474:                                     $crstype,$groupslist,$newuser,
 1475:                                     $formname,\%loaditem,$permission);
 1476:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1477:     my $helpitem = 'Course_Change_Privileges';
 1478:     if ($env{'form.action'} eq 'singlestudent') {
 1479:         $helpitem = 'Course_Add_Student';
 1480:     } elsif ($context eq 'author') {
 1481:         $helpitem = 'Author_Change_Privileges';
 1482:     } elsif ($context eq 'domain') {
 1483:         $helpitem = 'Domain_Change_Privileges';
 1484:         $js .= &set_custom_js();
 1485:     }
 1486:     push (@{$brcrum},
 1487:         {href => "javascript:backPage($form)",
 1488:          text => $breadcrumb_text{'search'},
 1489:          faq  => 282,
 1490:          bug  => 'Instructor Interface',});
 1491:     if ($env{'form.phase'} eq 'userpicked') {
 1492:        push(@{$brcrum},
 1493:               {href => "javascript:backPage($form,'get_user_info','select')",
 1494:                text => $breadcrumb_text{'userpicked'},
 1495:                faq  => 282,
 1496:                bug  => 'Instructor Interface',});
 1497:     }
 1498:     push(@{$brcrum},
 1499:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1500:              text => $breadcrumb_text{'modify'},
 1501:              faq  => 282,
 1502:              bug  => 'Instructor Interface',
 1503:              help => $helpitem});
 1504:     my $args = {'add_entries'           => \%loaditem,
 1505:                 'bread_crumbs'          => $brcrum,
 1506:                 'bread_crumbs_component' => 'User Management'};
 1507:     if ($env{'form.popup'}) {
 1508:         $args->{'no_nav_bar'} = 1;
 1509:     }
 1510:     if (($context eq 'domain') && ($env{'request.role.domain'} eq $ccdomain)) {
 1511:         my @toggles;
 1512:         if (&Apache::lonnet::allowed('cau',$ccdomain)) {
 1513:             my ($isadv,$isauthor) =
 1514:                 &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1515:             unless ($isauthor) {
 1516:                 push(@toggles,'requestauthor');
 1517:             }
 1518:             push(@toggles,('webdav','editors'));
 1519:         }
 1520:         if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1521:             push(@toggles,('aboutme','blog','portfolio','portaccess','timezone'));
 1522:         }
 1523:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1524:             push(@toggles,('official','unofficial','community','textbook','placement','lti'));
 1525:         }
 1526:         if (@toggles) {
 1527:             my $onload;
 1528:             foreach my $item (@toggles) {
 1529:                 $onload .= "toggleCustom(document.cu,'customtext_$item','custom$item');";
 1530:             }
 1531:             $args->{'add_entries'} = {
 1532:                                        'onload' => $onload,
 1533:                                      };
 1534:         }
 1535:     }
 1536:     my $start_page =
 1537:         &Apache::loncommon::start_page('User Management',$js,$args);
 1538: 
 1539:     my $forminfo =<<"ENDFORMINFO";
 1540: <form action="/adm/createuser" method="post" name="$formname">
 1541: <input type="hidden" name="phase" value="update_user_data" />
 1542: <input type="hidden" name="ccuname" value="$ccuname" />
 1543: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1544: <input type="hidden" name="pres_value"  value="" />
 1545: <input type="hidden" name="pres_type"   value="" />
 1546: <input type="hidden" name="pres_marker" value="" />
 1547: ENDFORMINFO
 1548:     my (%inccourses,$roledom,$defaultcredits);
 1549:     if ($context eq 'course') {
 1550:         $inccourses{$env{'request.course.id'}}=1;
 1551:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1552:         if ($showcredits) {
 1553:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1554:         }
 1555:     } elsif ($context eq 'author') {
 1556:         $roledom = $env{'request.role.domain'};
 1557:     } elsif ($context eq 'domain') {
 1558:         foreach my $key (keys(%env)) {
 1559:             $roledom = $env{'request.role.domain'};
 1560:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1561:                 $inccourses{$1.'_'.$2}=1;
 1562:             }
 1563:         }
 1564:     } else {
 1565:         foreach my $key (keys(%env)) {
 1566: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1567: 	        $inccourses{$1.'_'.$2}=1;
 1568:             }
 1569:         }
 1570:     }
 1571:     my $title = '';
 1572:     my $need_quota_js;
 1573:     if ($newuser) {
 1574:         my ($portfolioform,$domroleform);
 1575:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1576:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1577:             # Current user has quota or user tools modification privileges
 1578:             $portfolioform = '<br /><h3>'.
 1579:                              &mt('User Tools').
 1580:                              '</h3>'."\n".
 1581:                              &Apache::loncommon::start_data_table();
 1582:             if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1583:                 $portfolioform .= &build_tools_display($ccuname,$ccdomain,'tools');
 1584:             }
 1585:             if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1586:                 $portfolioform .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1587:                 $need_quota_js = 1;
 1588:             }
 1589:             $portfolioform .= &Apache::loncommon::end_data_table();
 1590:         }
 1591:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1592:             ($ccdomain eq $env{'request.role.domain'})) {
 1593:             $domroleform = &domainrole_req($ccuname,$ccdomain).
 1594:                            &authoring_defaults($ccuname,$ccdomain);
 1595:             $need_quota_js = 1;
 1596:         }
 1597:         my $readonly;
 1598:         unless ($permission->{'cusr'}) {
 1599:             $readonly = 1;
 1600:         }
 1601:         &initialize_authen_forms($ccdomain,$formname,'','',$readonly);
 1602:         my %lt=&Apache::lonlocal::texthash(
 1603:                 'lg'             => 'Login Data',
 1604:                 'hs'             => "Home Server",
 1605:         );
 1606: 	$r->print(<<ENDTITLE);
 1607: $start_page
 1608: $response
 1609: $forminfo
 1610: <script type="text/javascript" language="Javascript">
 1611: // <![CDATA[
 1612: $loginscript
 1613: // ]]>
 1614: </script>
 1615: <input type='hidden' name='makeuser' value='1' />
 1616: ENDTITLE
 1617:         if ($env{'form.action'} eq 'singlestudent') {
 1618:             if ($crstype eq 'Community') {
 1619:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1620:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1621:             } else {
 1622:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1623:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1624:             }
 1625:         } else {
 1626:                 $title = &mt('Create New User [_1] in domain [_2]',
 1627:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1628:         }
 1629:         $r->print('<h2>'.$title.'</h2>'."\n");
 1630:         $r->print('<div class="LC_left_float">');
 1631:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1632:                                          $inst_results{$ccuname.':'.$ccdomain},$readonly));
 1633:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1634:         my ($home_server_pick,$numlib) = 
 1635:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1636:                                                       'default','hide');
 1637:         if ($numlib > 1) {
 1638:             $r->print("
 1639: <br />
 1640: $lt{'hs'}: $home_server_pick
 1641: <br />");
 1642:         } else {
 1643:             $r->print($home_server_pick);
 1644:         }
 1645:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1646:             $r->print('<br /><h3>'.
 1647:                       &mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1648:                       &Apache::loncommon::start_data_table().
 1649:                       &build_tools_display($ccuname,$ccdomain,
 1650:                                            'requestcourses').
 1651:                       &Apache::loncommon::end_data_table());
 1652:         }
 1653:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1654:                   $lt{'lg'}.'</h3>');
 1655:         my ($fixedauth,$varauth,$authmsg); 
 1656:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1657:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1658:             my ($rules,$ruleorder) = 
 1659:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1660:             if (ref($rules) eq 'HASH') {
 1661:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1662:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1663:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1664:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1665:                     } else { 
 1666:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1667:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1668:                         if ($authtype =~ /^krb(4|5)$/) {
 1669:                             my $ver = $1;
 1670:                             if ($authparm ne '') {
 1671:                                 $fixedauth = <<"KERB"; 
 1672: <input type="hidden" name="login" value="krb" />
 1673: <input type="hidden" name="krbver" value="$ver" />
 1674: <input type="hidden" name="krbarg" value="$authparm" />
 1675: KERB
 1676:                             }
 1677:                         } else {
 1678:                             $fixedauth = 
 1679: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1680:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1681:                                 $fixedauth .=    
 1682: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1683:                             } else {
 1684:                                 if ($authtype eq 'int') {
 1685:                                     $varauth = '<br />'.
 1686: &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>';
 1687:                                 } elsif ($authtype eq 'loc') {
 1688:                                     $varauth = '<br />'.
 1689: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1690:                                 } else {
 1691:                                     $varauth =
 1692: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1693:                                 }
 1694:                             }
 1695:                         }
 1696:                     }
 1697:                 } else {
 1698:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1699:                 }
 1700:             }
 1701:             if ($authmsg) {
 1702:                 $r->print(<<ENDAUTH);
 1703: $fixedauth
 1704: $authmsg
 1705: $varauth
 1706: ENDAUTH
 1707:             }
 1708:         } else {
 1709:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1710:         }
 1711:         $r->print($portfolioform.$domroleform);
 1712:         if ($env{'form.action'} eq 'singlestudent') {
 1713:             $r->print(&date_sections_select($context,$newuser,$formname,
 1714:                                             $permission,$crstype,$ccuname,
 1715:                                             $ccdomain,$showcredits));
 1716:         }
 1717:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1718:     } else { # user already exists
 1719: 	$r->print($start_page.$forminfo);
 1720:         if ($env{'form.action'} eq 'singlestudent') {
 1721:             if ($crstype eq 'Community') {
 1722:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1723:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1724:             } else {
 1725:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1726:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1727:             }
 1728:         } else {
 1729:             if ($permission->{'cusr'}) {
 1730:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1731:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1732:             } else {
 1733:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1734:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1735:             }
 1736:         }
 1737:         $r->print('<h2>'.$title.'</h2>'."\n");
 1738:         $r->print('<div class="LC_left_float">');
 1739:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1740:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1741:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1742:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1743:             $r->print('<br /><h3>'.&mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1744:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1745:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1746:                 $r->print(&Apache::loncommon::start_data_table());
 1747:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1748:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1749:                 } else {
 1750:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1751:                                                       $env{'request.role.domain'}));
 1752:                 }
 1753:                 $r->print(&Apache::loncommon::end_data_table());
 1754:             } else {
 1755:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1756:                               &Apache::lonnet::domain($ccdomain,'description')));
 1757:             }
 1758:         }
 1759:         $r->print('</div>');
 1760:         my @order = ('auth','quota','tools','requestauthor','authordefaults');
 1761:         my %user_text;
 1762:         my ($isadv,$isauthor) = 
 1763:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1764:         if (((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1765:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1766:             ($env{'request.role.domain'} eq $ccdomain)) {
 1767:             if (!$isauthor) {
 1768:                 $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1769:             }
 1770:             $user_text{'authordefaults'} = &authoring_defaults($ccuname,$ccdomain);
 1771:             if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1772:                 $need_quota_js = 1;
 1773:             }
 1774:         }
 1775:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1776:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1777:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1778:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1779:             $user_text{'quota'} = '<br /><h3>'.&mt('User Tools').'</h3>'."\n".
 1780:                                   &Apache::loncommon::start_data_table();
 1781:             if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1782:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1783:                 $user_text{'quota'} .= &build_tools_display($ccuname,$ccdomain,'tools');
 1784:             }
 1785:             # Current user has quota modification privileges
 1786:             if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1787:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1788:                 $user_text{'quota'} .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1789:                 $need_quota_js = 1;
 1790:             }
 1791:             $user_text{'quota'} .= &Apache::loncommon::end_data_table();
 1792:         }
 1793:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1794:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1795:                 my %lt=&Apache::lonlocal::texthash(
 1796:                     'dska'  => "Disk quotas for user's portfolio",
 1797:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1798:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1799:                 );
 1800:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1801: <h3>$lt{'dska'}</h3>
 1802: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1803: ENDNOPORTPRIV
 1804:             }
 1805:         }
 1806:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1807:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1808:                 my %lt=&Apache::lonlocal::texthash(
 1809:                     'utav'  => "User Tools Availability",
 1810:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, Personal Information Page, or Time Zone settings for this user.",
 1811:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1812:                 );
 1813:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1814: <h3>$lt{'utav'}</h3>
 1815: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1816: ENDNOTOOLSPRIV
 1817:             }
 1818:         }
 1819:         my $gotdiv = 0; 
 1820:         foreach my $item (@order) {
 1821:             if ($user_text{$item} ne '') {
 1822:                 unless ($gotdiv) {
 1823:                     $r->print('<div class="LC_left_float">');
 1824:                     $gotdiv = 1;
 1825:                 }
 1826:                 $r->print('<br />'.$user_text{$item});
 1827:             }
 1828:         }
 1829:         if ($env{'form.action'} eq 'singlestudent') {
 1830:             unless ($gotdiv) {
 1831:                 $r->print('<div class="LC_left_float">');
 1832:             }
 1833:             my $credits;
 1834:             if ($showcredits) {
 1835:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1836:                 if ($credits eq '') {
 1837:                     $credits = $defaultcredits;
 1838:                 }
 1839:             }
 1840:             $r->print(&date_sections_select($context,$newuser,$formname,
 1841:                                             $permission,$crstype,$ccuname,
 1842:                                             $ccdomain,$showcredits));
 1843:         }
 1844:         if ($gotdiv) {
 1845:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1846:         }
 1847:         my $statuses;
 1848:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1849:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1850:             $statuses = ['active'];
 1851:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1852:                  ($env{'request.course.sec'} &&
 1853:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1854:             $statuses = ['active'];
 1855:         }
 1856:         if ($env{'form.action'} ne 'singlestudent') {
 1857:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1858:                                     $roledom,$crstype,$showcredits,$statuses);
 1859:         }
 1860:     } ## End of new user/old user logic
 1861:     if ($env{'form.action'} eq 'singlestudent') {
 1862:         my $btntxt;
 1863:         if ($crstype eq 'Community') {
 1864:             $btntxt = &mt('Enroll Member');
 1865:         } else {
 1866:             $btntxt = &mt('Enroll Student');
 1867:         }
 1868:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1869:     } elsif ($permission->{'cusr'}) {
 1870:         $r->print('<div class="LC_left_float">'.
 1871:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1872:         my $addrolesdisplay = 0;
 1873:         if ($context eq 'domain' || $context eq 'author') {
 1874:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1875:         }
 1876:         if ($context eq 'domain') {
 1877:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1878:             if (!$addrolesdisplay) {
 1879:                 $addrolesdisplay = $add_domainroles;
 1880:             }
 1881:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1882:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1883:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1884:         } elsif ($context eq 'author') {
 1885:             if ($addrolesdisplay) {
 1886:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1887:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1888:                 if ($newuser) {
 1889:                     $r->print(' onclick="auth_check()" \>'."\n");
 1890:                 } else {
 1891:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1892:                 }
 1893:             } else {
 1894:                 $r->print('</fieldset></div>'.
 1895:                           '<div class="LC_clear_float_footer"></div>'.
 1896:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1897:                           &mt('Back to previous page').'</a>');
 1898:             }
 1899:         } else {
 1900:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1901:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1902:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1903:         }
 1904:     }
 1905:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1906:     $r->print('<input type="hidden" name="currstate" value="" />');
 1907:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1908:     if ($need_quota_js) {
 1909:         $r->print(&user_quota_js());
 1910:     }
 1911:     return;
 1912: }
 1913: 
 1914: sub singleuser_breadcrumb {
 1915:     my ($crstype,$context,$domain) = @_;
 1916:     my %breadcrumb_text;
 1917:     if ($env{'form.action'} eq 'singlestudent') {
 1918:         if ($crstype eq 'Community') {
 1919:             $breadcrumb_text{'search'} = 'Enroll a member';
 1920:         } else {
 1921:             $breadcrumb_text{'search'} = 'Enroll a student';
 1922:         }
 1923:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1924:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1925:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1926:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1927:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1928:         $breadcrumb_text{'activity'} = 'Activity';
 1929:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1930:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1931:         $breadcrumb_text{'search'} = "View user's roles";
 1932:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1933:         $breadcrumb_text{'modify'} = 'User roles';
 1934:     } else {
 1935:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1936:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1937:         $breadcrumb_text{'modify'} = 'Set user role';
 1938:     }
 1939:     return %breadcrumb_text;
 1940: }
 1941: 
 1942: sub date_sections_select {
 1943:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1944:         $showcredits) = @_;
 1945:     my $credits;
 1946:     if ($showcredits) {
 1947:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1948:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1949:         if ($credits eq '') {
 1950:             $credits = $defaultcredits;
 1951:         }
 1952:     }
 1953:     my $cid = $env{'request.course.id'};
 1954:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1955:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1956:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1957:                                                   undef,$formname,$permission);
 1958:     my $rowtitle = 'Section';
 1959:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1960:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1961:                                               $permission,$context,'',$crstype,
 1962:                                               $showcredits,$credits);
 1963:     my $output = $date_table.$secbox;
 1964:     return $output;
 1965: }
 1966: 
 1967: sub validation_javascript {
 1968:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1969:         $loaditem,$permission) = @_;
 1970:     my $dc_setcourse_code = '';
 1971:     my $nondc_setsection_code = '';
 1972:     if ($context eq 'domain') {
 1973:         if ((ref($permission) eq 'HASH') && ($permission->{'cusr'})) {
 1974:             my $dcdom = $env{'request.role.domain'};
 1975:             $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1976:             $dc_setcourse_code =
 1977:                 &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1978:         }
 1979:     } else {
 1980:         my $checkauth; 
 1981:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1982:             $checkauth = 1;
 1983:         }
 1984:         if ($context eq 'course') {
 1985:             $nondc_setsection_code =
 1986:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1987:                                                               undef,$checkauth,
 1988:                                                               $crstype);
 1989:         }
 1990:         if ($checkauth) {
 1991:             $nondc_setsection_code .= 
 1992:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1993:         }
 1994:     }
 1995:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1996:                                    $nondc_setsection_code,$groupslist);
 1997:     my ($jsback,$elements) = &crumb_utilities();
 1998:     $js .= "\n".
 1999:            '<script type="text/javascript">'."\n".
 2000:            '// <![CDATA['."\n".
 2001:            $jsback."\n".
 2002:            '// ]]>'."\n".
 2003:            '</script>'."\n";
 2004:     return $js;
 2005: }
 2006: 
 2007: sub display_existing_roles {
 2008:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 2009:         $showcredits,$statuses) = @_;
 2010:     my $now=time;
 2011:     my $showall = 1;
 2012:     my ($showexpired,$showactive);
 2013:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 2014:         $showall = 0;
 2015:         if (grep(/^expired$/,@{$statuses})) {
 2016:             $showexpired = 1;
 2017:         }
 2018:         if (grep(/^active$/,@{$statuses})) {
 2019:             $showactive = 1;
 2020:         }
 2021:         if ($showexpired && $showactive) {
 2022:             $showall = 1;
 2023:         }
 2024:     }
 2025:     my %lt=&Apache::lonlocal::texthash(
 2026:                     'rer'  => "Existing Roles",
 2027:                     'rev'  => "Revoke",
 2028:                     'del'  => "Delete",
 2029:                     'ren'  => "Re-Enable",
 2030:                     'rol'  => "Role",
 2031:                     'ext'  => "Extent",
 2032:                     'crd'  => "Credits",
 2033:                     'sta'  => "Start",
 2034:                     'end'  => "End",
 2035:                                        );
 2036:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 2037:     if ($context eq 'course' || $context eq 'author') {
 2038:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 2039:         my %roleshash = 
 2040:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 2041:                               ['active','previous','future'],\@roles,$roledom,1);
 2042:         foreach my $key (keys(%roleshash)) {
 2043:             my ($start,$end) = split(':',$roleshash{$key});
 2044:             next if ($start eq '-1' || $end eq '-1');
 2045:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 2046:             if ($context eq 'course') {
 2047:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 2048:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 2049:             } elsif ($context eq 'author') {
 2050:                 if ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2051:                     my ($audom,$auname) = ($1,$2);
 2052:                     next unless (($rnum eq $auname) && ($rdom eq $audom));
 2053:                 } else {
 2054:                     next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 2055:                 }
 2056:             }
 2057:             my ($newkey,$newvalue,$newrole);
 2058:             $newkey = '/'.$rdom.'/'.$rnum;
 2059:             if ($sec ne '') {
 2060:                 $newkey .= '/'.$sec;
 2061:             }
 2062:             $newvalue = $role;
 2063:             if ($role =~ /^cr/) {
 2064:                 $newrole = 'cr';
 2065:             } else {
 2066:                 $newrole = $role;
 2067:             }
 2068:             $newkey .= '_'.$newrole;
 2069:             if ($start ne '' && $end ne '') {
 2070:                 $newvalue .= '_'.$end.'_'.$start;
 2071:             } elsif ($end ne '') {
 2072:                 $newvalue .= '_'.$end;
 2073:             }
 2074:             $rolesdump{$newkey} = $newvalue;
 2075:         }
 2076:     } else {
 2077:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 2078:     }
 2079:     # Build up table of user roles to allow revocation and re-enabling of roles.
 2080:     my ($tmp) = keys(%rolesdump);
 2081:     return if ($tmp =~ /^(con_lost|error)/i);
 2082:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 2083:                                 my $b1=join('_',(split('_',$b))[1,0]);
 2084:                                 return $a1 cmp $b1;
 2085:                             } keys(%rolesdump)) {
 2086:         next if ($area =~ /^rolesdef/);
 2087:         my $envkey=$area;
 2088:         my $role = $rolesdump{$area};
 2089:         my $thisrole=$area;
 2090:         $area =~ s/\_\w\w$//;
 2091:         my ($role_code,$role_end_time,$role_start_time) =
 2092:             split(/_/,$role);
 2093:         my $active=1;
 2094:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 2095:         if ($active) {
 2096:             next unless($showall || $showactive);
 2097:         } else {
 2098:             next unless($showall || $showexpired);
 2099:         }
 2100: # Is this a custom role? Get role owner and title.
 2101:         my ($croleudom,$croleuname,$croletitle)=
 2102:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 2103:         my $allowed=0;
 2104:         my $delallowed=0;
 2105:         my $sortkey=$role_code;
 2106:         my $class='Unknown';
 2107:         my $credits='';
 2108:         my $csec;
 2109:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 2110:             $class='Course';
 2111:             my ($coursedom,$coursedir) = ($1,$2);
 2112:             my $cid = $1.'_'.$2;
 2113:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 2114:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 2115:             my %coursedata=
 2116:                 &Apache::lonnet::coursedescription($cid);
 2117:             if ($coursedir =~ /^$match_community$/) {
 2118:                 $class='Community';
 2119:             }
 2120:             $sortkey.="\0$coursedom";
 2121:             my $carea;
 2122:             if (defined($coursedata{'description'})) {
 2123:                 $carea=$coursedata{'description'}.
 2124:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 2125:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 2126:                 $sortkey.="\0".$coursedata{'description'};
 2127:             } else {
 2128:                 if ($class eq 'Community') {
 2129:                     $carea=&mt('Unavailable community').': '.$area;
 2130:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 2131:                 } else {
 2132:                     $carea=&mt('Unavailable course').': '.$area;
 2133:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 2134:                 }
 2135:             }
 2136:             $sortkey.="\0$coursedir";
 2137:             $inccourses->{$cid}=1;
 2138:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 2139:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 2140:                 $credits =
 2141:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 2142:                                       $coursedom,$coursedir);
 2143:                 if ($credits eq '') {
 2144:                     $credits = $defaultcredits;
 2145:                 }
 2146:             }
 2147:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 2148:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2149:                 $allowed=1;
 2150:             }
 2151:             unless ($allowed) {
 2152:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 2153:                 if ($isowner) {
 2154:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 2155:                         $allowed = 1;
 2156:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 2157:                         $allowed = 1;
 2158:                     }
 2159:                 }
 2160:             } 
 2161:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 2162:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 2163:                 $delallowed=1;
 2164:             }
 2165: # - custom role. Needs more info, too
 2166:             if ($croletitle) {
 2167:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 2168:                     $allowed=1;
 2169:                     $thisrole.='.'.$role_code;
 2170:                 }
 2171:             }
 2172:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 2173:                 $csec = $2;
 2174:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 2175:                 $sortkey.="\0$csec";
 2176:                 if (!$allowed) {
 2177:                     if ($env{'request.course.sec'} eq $csec) {
 2178:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 2179:                             $allowed = 1;
 2180:                         }
 2181:                     }
 2182:                 }
 2183:             }
 2184:             $area=$carea;
 2185:         } else {
 2186:             $sortkey.="\0".$area;
 2187:             # Determine if current user is able to revoke privileges
 2188:             if ($area=~m{^/($match_domain)/}) {
 2189:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 2190:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2191:                    $allowed=1;
 2192:                 }
 2193:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 2194:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 2195:                     ($role_code ne 'dc')) {
 2196:                     $delallowed=1;
 2197:                 }
 2198:             } else {
 2199:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 2200:                     $allowed=1;
 2201:                 }
 2202:             }
 2203:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 2204:                 $class='Authoring Space';
 2205:             } elsif ($role_code eq 'su') {
 2206:                 $class='System';
 2207:             } else {
 2208:                 $class='Domain';
 2209:             }
 2210:         }
 2211:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 2212:             $area=~m{/($match_domain)/($match_username)};
 2213:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 2214:                 $allowed=1;
 2215:             } elsif (&Apache::lonuserutils::coauthorpriv($2,$1)) {
 2216:                 $allowed=1;
 2217:             } else {
 2218:                 $allowed=0;
 2219:             }
 2220:         }
 2221:         my $row = '';
 2222:         if ($showall) {
 2223:             $row.= '<td>';
 2224:             if (($active) && ($allowed)) {
 2225:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 2226:             } else {
 2227:                 if ($active) {
 2228:                     $row.='&nbsp;';
 2229:                 } else {
 2230:                     $row.=&mt('expired or revoked');
 2231:                 }
 2232:             }
 2233:             $row.='</td><td>';
 2234:             if ($allowed && !$active) {
 2235:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 2236:             } else {
 2237:                 $row.='&nbsp;';
 2238:             }
 2239:             $row.='</td><td>';
 2240:             if ($delallowed) {
 2241:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 2242:             } else {
 2243:                 $row.='&nbsp;';
 2244:             }
 2245:             $row.= '</td>';
 2246:         }
 2247:         my $plaintext='';
 2248:         if (!$croletitle) {
 2249:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2250:             if (($showcredits) && ($credits ne '')) {
 2251:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2252:                               '<span class="LC_fontsize_small">'.
 2253:                               &mt('Credits: [_1]',$credits).
 2254:                               '</span></span>';
 2255:             }
 2256:         } else {
 2257:             $plaintext=
 2258:                 &mt('Custom role [_1][_2]defined by [_3]',
 2259:                         '"'.$croletitle.'"',
 2260:                         '<br />',
 2261:                         $croleuname.':'.$croleudom);
 2262:         }
 2263:         $row.= '<td>'.$plaintext.'</td>'.
 2264:                '<td>'.$area.'</td>'.
 2265:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2266:                                             : '&nbsp;' ).'</td>'.
 2267:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2268:                                             : '&nbsp;' ).'</td>';
 2269:         $sortrole{$sortkey}=$envkey;
 2270:         $roletext{$envkey}=$row;
 2271:         $roleclass{$envkey}=$class;
 2272:         if ($allowed) {
 2273:             $rolepriv{$envkey}='edit';
 2274:         } else {
 2275:             if ($context eq 'domain') {
 2276:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2277:                     ($envkey=~m{^/$ccdomain/})) {
 2278:                     $rolepriv{$envkey}='view';
 2279:                 }
 2280:             } elsif ($context eq 'course') {
 2281:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2282:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2283:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2284:                     $rolepriv{$envkey}='view';
 2285:                 }
 2286:             }
 2287:         }
 2288:     } # end of foreach        (table building loop)
 2289: 
 2290:     my $rolesdisplay = 0;
 2291:     my %output = ();
 2292:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2293:         $output{$type} = '';
 2294:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2295:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2296:                  $output{$type}.=
 2297:                       &Apache::loncommon::start_data_table_row().
 2298:                       $roletext{$sortrole{$which}}.
 2299:                       &Apache::loncommon::end_data_table_row();
 2300:             }
 2301:         }
 2302:         unless($output{$type} eq '') {
 2303:             $output{$type} = '<tr class="LC_info_row">'.
 2304:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2305:                       $output{$type};
 2306:             $rolesdisplay = 1;
 2307:         }
 2308:     }
 2309:     if ($rolesdisplay == 1) {
 2310:         my $contextrole='';
 2311:         if ($env{'request.course.id'}) {
 2312:             if (&Apache::loncommon::course_type() eq 'Community') {
 2313:                 $contextrole = &mt('Existing Roles in this Community');
 2314:             } else {
 2315:                 $contextrole = &mt('Existing Roles in this Course');
 2316:             }
 2317:         } elsif ($env{'request.role'} =~ /^au\./) {
 2318:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2319:         } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)/$}) {
 2320:             $contextrole = &mt('Existing Co-Author Roles in [_1] Authoring Space',
 2321:                                '<i>'.$1.'_'.$2.'</i>');
 2322:         } else {
 2323:             if ($showall) {
 2324:                 $contextrole = &mt('Existing Roles in this Domain');
 2325:             } elsif ($showactive) {
 2326:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2327:             } elsif ($showexpired) {
 2328:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2329:             }
 2330:         }
 2331:         $r->print('<div class="LC_left_float">'.
 2332: '<fieldset><legend>'.$contextrole.'</legend>'.
 2333: &Apache::loncommon::start_data_table("LC_createuser").
 2334: &Apache::loncommon::start_data_table_header_row());
 2335:         if ($showall) {
 2336:             $r->print(
 2337: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2338:             );
 2339:         } elsif ($showexpired) {
 2340:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2341:         }
 2342:         $r->print(
 2343: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2344: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2345: &Apache::loncommon::end_data_table_header_row());
 2346:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2347:             if ($output{$type}) {
 2348:                 $r->print($output{$type}."\n");
 2349:             }
 2350:         }
 2351:         $r->print(&Apache::loncommon::end_data_table().
 2352:                   '</fieldset></div>');
 2353:     }
 2354:     return;
 2355: }
 2356: 
 2357: sub new_coauthor_roles {
 2358:     my ($r,$ccuname,$ccdomain) = @_;
 2359:     my $addrolesdisplay = 0;
 2360:     #
 2361:     # Co-Author
 2362:     #
 2363:     my ($cuname,$cudom);
 2364:     if (($env{'request.role'} eq "au./$env{'user.domain'}/") ||
 2365:         ($env{'request.role'} eq "dc./$env{'user.domain'}/")) {
 2366:         $cuname=$env{'user.name'};
 2367:         $cudom=$env{'request.role.domain'};
 2368:         # No sense in assigning co-author role to yourself
 2369:         if ((&Apache::lonuserutils::authorpriv($cuname,$cudom)) &&
 2370:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2371:             $addrolesdisplay = 1;
 2372:         }
 2373:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2374:         ($cudom,$cuname) = ($1,$2);
 2375:         if ((&Apache::lonuserutils::coauthorpriv($cuname,$cudom)) &&
 2376:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain) &&
 2377:             ($cudom ne $ccdomain || $cuname ne $ccuname)) {
 2378:             $addrolesdisplay = 1;
 2379:         }
 2380:     }
 2381:     if ($addrolesdisplay) {
 2382:         my %lt=&Apache::lonlocal::texthash(
 2383:                     'cs'   => "Authoring Space",
 2384:                     'act'  => "Activate",
 2385:                     'rol'  => "Role",
 2386:                     'ext'  => "Extent",
 2387:                     'sta'  => "Start",
 2388:                     'end'  => "End",
 2389:                     'cau'  => "Co-Author",
 2390:                     'caa'  => "Assistant Co-Author",
 2391:                     'ssd'  => "Set Start Date",
 2392:                     'sed'  => "Set End Date"
 2393:                                        );
 2394:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2395:                   &Apache::loncommon::start_data_table()."\n".
 2396:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2397:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2398:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2399:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2400:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2401:                   &Apache::loncommon::start_data_table_row().'
 2402:            <td>
 2403:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2404:            </td>
 2405:            <td>'.$lt{'cau'}.'</td>
 2406:            <td>'.$cudom.'_'.$cuname.'</td>
 2407:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2408:              <a href=
 2409: "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>
 2410: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2411: <a href=
 2412: "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".
 2413:               &Apache::loncommon::end_data_table_row()."\n".
 2414:               &Apache::loncommon::start_data_table_row()."\n".
 2415: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2416: <td>'.$lt{'caa'}.'</td>
 2417: <td>'.$cudom.'_'.$cuname.'</td>
 2418: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2419: <a href=
 2420: "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>
 2421: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2422: <a href=
 2423: "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".
 2424:              &Apache::loncommon::end_data_table_row()."\n".
 2425:              &Apache::loncommon::end_data_table());
 2426:     } elsif ($env{'request.role'} =~ /^au\./) {
 2427:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2428:                                                 $env{'request.role.domain'}))) {
 2429:             $r->print('<span class="LC_error">'.
 2430:                       &mt('You do not have privileges to assign co-author roles.').
 2431:                       '</span>');
 2432:         } elsif (($env{'user.name'} eq $ccuname) &&
 2433:              ($env{'user.domain'} eq $ccdomain)) {
 2434:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2435:         }
 2436:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2437:         if (!(&Apache::lonuserutils::coauthorpriv($2,$1))) {
 2438:             $r->print('<span class="LC_error">'.
 2439:                       &mt('You do not have privileges to assign co-author roles.').
 2440:                       '</span>');
 2441:         } elsif (($env{'user.name'} eq $ccuname) &&
 2442:              ($env{'user.domain'} eq $ccdomain)) {
 2443:             $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'));
 2444:         } elsif (($cudom eq $ccdomain) && ($cuname eq $ccuname)) {
 2445:             $r->print(&mt("Assigning a co-author or assistant co-author role to an Authoring Space's author is not permitted"));
 2446:         }
 2447:     }
 2448:     return $addrolesdisplay;;
 2449: }
 2450: 
 2451: sub new_domain_roles {
 2452:     my ($r,$ccdomain) = @_;
 2453:     my $addrolesdisplay = 0;
 2454:     #
 2455:     # Domain level
 2456:     #
 2457:     my $num_domain_level = 0;
 2458:     my $domaintext =
 2459:     '<h4>'.&mt('Domain Level').'</h4>'.
 2460:     &Apache::loncommon::start_data_table().
 2461:     &Apache::loncommon::start_data_table_header_row().
 2462:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2463:     &mt('Extent').'</th>'.
 2464:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2465:     &Apache::loncommon::end_data_table_header_row();
 2466:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2467:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2468:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2469:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2470:         foreach my $role (@allroles) {
 2471:             next if ($role eq 'ad');
 2472:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2473:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2474:                if ($role eq 'dc') {
 2475:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2476:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2477:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2478:                        next unless ($uintdom eq $intdom);
 2479:                    }
 2480:                }
 2481:                my $plrole=&Apache::lonnet::plaintext($role);
 2482:                my %lt=&Apache::lonlocal::texthash(
 2483:                     'ssd'  => "Set Start Date",
 2484:                     'sed'  => "Set End Date"
 2485:                                        );
 2486:                $num_domain_level ++;
 2487:                $domaintext .=
 2488: &Apache::loncommon::start_data_table_row().
 2489: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2490: <td>'.$plrole.'</td>
 2491: <td>'.$thisdomain.'</td>
 2492: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2493: <a href=
 2494: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2495: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2496: <a href=
 2497: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2498: &Apache::loncommon::end_data_table_row();
 2499:             }
 2500:         }
 2501:     }
 2502:     $domaintext.= &Apache::loncommon::end_data_table();
 2503:     if ($num_domain_level > 0) {
 2504:         $r->print($domaintext);
 2505:         $addrolesdisplay = 1;
 2506:     }
 2507:     return $addrolesdisplay;
 2508: }
 2509: 
 2510: sub user_authentication {
 2511:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2512:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2513:     my $outcome;
 2514:     my %lt=&Apache::lonlocal::texthash(
 2515:                    'err'   => "ERROR",
 2516:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2517:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2518:                    'sldb'  => "Please specify login data below",
 2519:                    'ld'    => "Login Data"
 2520:     );
 2521:     # Check for a bad authentication type
 2522:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2523:         # bad authentication scheme
 2524:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2525:             &initialize_authen_forms($ccdomain,$formname);
 2526: 
 2527:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2528:             $outcome = <<ENDBADAUTH;
 2529: <script type="text/javascript" language="Javascript">
 2530: // <![CDATA[
 2531: $loginscript
 2532: // ]]>
 2533: </script>
 2534: <span class="LC_error">$lt{'err'}:
 2535: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2536: <h3>$lt{'ld'}</h3>
 2537: $choices
 2538: ENDBADAUTH
 2539:         } else {
 2540:             # This user is not allowed to modify the user's
 2541:             # authentication scheme, so just notify them of the problem
 2542:             $outcome = <<ENDBADAUTH;
 2543: <span class="LC_error"> $lt{'err'}: 
 2544: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2545: </span>
 2546: ENDBADAUTH
 2547:         }
 2548:     } else { # Authentication type is valid
 2549:         
 2550:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2551:         my ($authformcurrent,$can_modify,@authform_others) =
 2552:             &modify_login_block($ccdomain,$currentauth);
 2553:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2554:             # Current user has login modification privileges
 2555:             $outcome =
 2556:                        '<script type="text/javascript" language="Javascript">'."\n".
 2557:                        '// <![CDATA['."\n".
 2558:                        $loginscript."\n".
 2559:                        '// ]]>'."\n".
 2560:                        '</script>'."\n".
 2561:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2562:                        &Apache::loncommon::start_data_table().
 2563:                        &Apache::loncommon::start_data_table_row().
 2564:                        '<td>'.$authformnop;
 2565:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2566:                 $outcome .= '</td>'."\n".
 2567:                             &Apache::loncommon::end_data_table_row().
 2568:                             &Apache::loncommon::start_data_table_row().
 2569:                             '<td>'.$authformcurrent.'</td>'.
 2570:                             &Apache::loncommon::end_data_table_row()."\n";
 2571:             } else {
 2572:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2573:                             &Apache::loncommon::end_data_table_row()."\n";
 2574:             }
 2575:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2576:                 foreach my $item (@authform_others) { 
 2577:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2578:                                 '<td>'.$item.'</td>'.
 2579:                                 &Apache::loncommon::end_data_table_row()."\n";
 2580:                 }
 2581:             }
 2582:             $outcome .= &Apache::loncommon::end_data_table();
 2583:         } else {
 2584:             if (($currentauth =~ /^internal:/) &&
 2585:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2586:                 $outcome = <<"ENDJS";
 2587: <script type="text/javascript">
 2588: // <![CDATA[
 2589: function togglePwd(form) {
 2590:     if (form.newintpwd.length) {
 2591:         if (document.getElementById('LC_ownersetpwd')) {
 2592:             for (var i=0; i<form.newintpwd.length; i++) {
 2593:                 if (form.newintpwd[i].checked) {
 2594:                     if (form.newintpwd[i].value == 1) {
 2595:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2596:                     } else {
 2597:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2598:                     }
 2599:                 }
 2600:             }
 2601:         }
 2602:     }
 2603: }
 2604: // ]]>
 2605: </script>
 2606: ENDJS
 2607: 
 2608:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2609:                             &Apache::loncommon::start_data_table().
 2610:                             &Apache::loncommon::start_data_table_row().
 2611:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2612:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2613:                             &mt('No').'</label>'.('&nbsp;'x2).
 2614:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2615:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2616:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2617:                             '<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>'.
 2618:                             &Apache::loncommon::end_data_table_row().
 2619:                             &Apache::loncommon::end_data_table();
 2620:             }
 2621:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2622:                 # Current user has rights to view domain preferences for user's domain
 2623:                 my $result;
 2624:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2625:                     my ($krbver,$krbrealm) = ($1,$2);
 2626:                     if ($krbrealm eq '') {
 2627:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2628:                     } else {
 2629:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2630:                                       $krbrealm,$krbver);
 2631:                     }
 2632:                 } elsif ($currentauth =~ /^internal:/) {
 2633:                     $result = &mt('Currently internally authenticated.');
 2634:                 } elsif ($currentauth =~ /^localauth:/) {
 2635:                     $result = &mt('Currently using local (institutional) authentication.');
 2636:                 } elsif ($currentauth =~ /^unix:/) {
 2637:                     $result = &mt('Currently Filesystem Authenticated.');
 2638:                 } elsif ($currentauth =~ /^lti:/) {
 2639:                     $result = &mt('Currently LTI authenticated.');
 2640:                 }
 2641:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2642:                            &Apache::loncommon::start_data_table().
 2643:                            &Apache::loncommon::start_data_table_row().
 2644:                            '<td>'.$result.'</td>'.
 2645:                            &Apache::loncommon::end_data_table_row()."\n".
 2646:                            &Apache::loncommon::end_data_table();
 2647:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2648:                 my %lt=&Apache::lonlocal::texthash(
 2649:                            'ccld'  => "Change Current Login Data",
 2650:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2651:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2652:                 );
 2653:                 $outcome .= <<ENDNOPRIV;
 2654: <h3>$lt{'ccld'}</h3>
 2655: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2656: <input type="hidden" name="login" value="nochange" />
 2657: ENDNOPRIV
 2658:             }
 2659:         }
 2660:     }  ## End of "check for bad authentication type" logic
 2661:     return $outcome;
 2662: }
 2663: 
 2664: sub modify_login_block {
 2665:     my ($dom,$currentauth) = @_;
 2666:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2667:     my ($authnum,%can_assign) =
 2668:         &Apache::loncommon::get_assignable_auth($dom);
 2669:     my ($authformcurrent,@authform_others,$show_override_msg);
 2670:     if ($currentauth=~/^krb(4|5):/) {
 2671:         $authformcurrent=$authformkrb;
 2672:         if ($can_assign{'int'}) {
 2673:             push(@authform_others,$authformint);
 2674:         }
 2675:         if ($can_assign{'loc'}) {
 2676:             push(@authform_others,$authformloc);
 2677:         }
 2678:         if ($can_assign{'lti'}) {
 2679:             push(@authform_others,$authformlti);
 2680:         }
 2681:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2682:             $show_override_msg = 1;
 2683:         }
 2684:     } elsif ($currentauth=~/^internal:/) {
 2685:         $authformcurrent=$authformint;
 2686:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2687:             push(@authform_others,$authformkrb);
 2688:         }
 2689:         if ($can_assign{'loc'}) {
 2690:             push(@authform_others,$authformloc);
 2691:         }
 2692:         if ($can_assign{'lti'}) {
 2693:             push(@authform_others,$authformlti);
 2694:         }
 2695:         if ($can_assign{'int'}) {
 2696:             $show_override_msg = 1;
 2697:         }
 2698:     } elsif ($currentauth=~/^unix:/) {
 2699:         $authformcurrent=$authformfsys;
 2700:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2701:             push(@authform_others,$authformkrb);
 2702:         }
 2703:         if ($can_assign{'int'}) {
 2704:             push(@authform_others,$authformint);
 2705:         }
 2706:         if ($can_assign{'loc'}) {
 2707:             push(@authform_others,$authformloc);
 2708:         }
 2709:         if ($can_assign{'lti'}) {
 2710:             push(@authform_others,$authformlti);
 2711:         }
 2712:         if ($can_assign{'fsys'}) {
 2713:             $show_override_msg = 1;
 2714:         }
 2715:     } elsif ($currentauth=~/^localauth:/) {
 2716:         $authformcurrent=$authformloc;
 2717:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2718:             push(@authform_others,$authformkrb);
 2719:         }
 2720:         if ($can_assign{'int'}) {
 2721:             push(@authform_others,$authformint);
 2722:         }
 2723:         if ($can_assign{'lti'}) {
 2724:             push(@authform_others,$authformlti);
 2725:         }
 2726:         if ($can_assign{'loc'}) {
 2727:             $show_override_msg = 1;
 2728:         }
 2729:     } elsif ($currentauth=~/^lti:/) {
 2730:         $authformcurrent=$authformlti;
 2731:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2732:             push(@authform_others,$authformkrb);
 2733:         }
 2734:         if ($can_assign{'int'}) {
 2735:             push(@authform_others,$authformint);
 2736:         }
 2737:         if ($can_assign{'loc'}) {
 2738:             push(@authform_others,$authformloc);
 2739:         }
 2740:     }
 2741:     if ($show_override_msg) {
 2742:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2743:                            '</td></tr>'."\n".
 2744:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2745:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2746:                            '<td align="right"><span class="LC_cusr_emph">'.
 2747:                             &mt('will override current values').
 2748:                             '</span></td></tr></table>';
 2749:     }
 2750:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2751: }
 2752: 
 2753: sub personal_data_display {
 2754:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$readonly,$rolesarray,$now,
 2755:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2756:     my ($output,%userenv,%canmodify,%canmodify_status,$disabled);
 2757:     my @userinfo = ('firstname','middlename','lastname','generation',
 2758:                     'permanentemail','id');
 2759:     my $rowcount = 0;
 2760:     my $editable = 0;
 2761:     my %textboxsize = (
 2762:                        firstname      => '15',
 2763:                        middlename     => '15',
 2764:                        lastname       => '15',
 2765:                        generation     => '5',
 2766:                        permanentemail => '25',
 2767:                        id             => '15',
 2768:                       );
 2769: 
 2770:     my %lt=&Apache::lonlocal::texthash(
 2771:                 'pd'             => "Personal Data",
 2772:                 'firstname'      => "First Name",
 2773:                 'middlename'     => "Middle Name",
 2774:                 'lastname'       => "Last Name",
 2775:                 'generation'     => "Generation",
 2776:                 'permanentemail' => "Permanent e-mail address",
 2777:                 'id'             => "Student/Employee ID",
 2778:                 'lg'             => "Login Data",
 2779:                 'inststatus'     => "Affiliation",
 2780:                 'email'          => 'E-mail address',
 2781:                 'valid'          => 'Validation',
 2782:                 'username'       => 'Username',
 2783:     );
 2784: 
 2785:     %canmodify_status =
 2786:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2787:                                                    ['inststatus'],$rolesarray);
 2788:     if (!$newuser) {
 2789:         # Get the users information
 2790:         %userenv = &Apache::lonnet::get('environment',
 2791:                    ['firstname','middlename','lastname','generation',
 2792:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2793:         %canmodify =
 2794:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2795:                                                        \@userinfo,$rolesarray);
 2796:     } elsif ($context eq 'selfcreate') {
 2797:         if ($newuser eq 'email') {
 2798:             if (ref($emailusername) eq 'HASH') {
 2799:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2800:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2801:                     @userinfo = ();
 2802:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2803:                         foreach my $field (@{$infofields}) { 
 2804:                             if ($emailusername->{$usertype}->{$field}) {
 2805:                                 push(@userinfo,$field);
 2806:                                 $canmodify{$field} = 1;
 2807:                                 unless ($textboxsize{$field}) {
 2808:                                     $textboxsize{$field} = 25;
 2809:                                 }
 2810:                                 unless ($lt{$field}) {
 2811:                                     $lt{$field} = $infotitles->{$field};
 2812:                                 }
 2813:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2814:                                     $lt{$field} .= '<b>*</b>';
 2815:                                 }
 2816:                             }
 2817:                         }
 2818:                     }
 2819:                 }
 2820:             }
 2821:         } else {
 2822:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2823:                                                $inst_results,$rolesarray);
 2824:         }
 2825:     } elsif ($readonly) {
 2826:         $disabled = ' disabled="disabled"';
 2827:     }
 2828: 
 2829:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2830:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2831:               &Apache::lonhtmlcommon::start_pick_box();
 2832:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2833:         my $size = 25;
 2834:         if ($condition) {
 2835:             if ($condition =~ /^\@[^\@]+$/) {
 2836:                 $size = 10;
 2837:             } else {
 2838:                 undef($condition);
 2839:             }
 2840:         } 
 2841:         if ($excluded) {
 2842:             unless ($excluded =~ /^\@[^\@]+$/) {
 2843:                 undef($condition);
 2844:             }
 2845:         }
 2846:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2847:                                                      'LC_oddrow_value')."\n".
 2848:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2849:         if ($condition) {
 2850:             $output .= $condition;
 2851:         } elsif ($excluded) {
 2852:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2853:                                                                      $excluded).'</span>';
 2854:         }
 2855:         if ($usernameset eq 'first') {
 2856:             $output .= '<br /><span style="font-size: smaller">';
 2857:             if ($condition) {
 2858:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2859:                                       $condition);
 2860:             } else {
 2861:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2862:             }
 2863:             $output .= '</span>';
 2864:         }
 2865:         $rowcount ++;
 2866:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2867:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2868:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2869:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2870:                                                     'LC_pick_box_title',
 2871:                                                     'LC_oddrow_value')."\n".
 2872:                    $upassone."\n".
 2873:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2874:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2875:                                                      'LC_pick_box_title',
 2876:                                                      'LC_oddrow_value')."\n".
 2877:                    $upasstwo.
 2878:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2879:         if ($usernameset eq 'free') {
 2880:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2881:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2882:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2883:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2884:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2885:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2886:                        &mt('No').'</label></span>'."\n".
 2887:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2888:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2889:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2890:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2891:             $rowcount ++;
 2892:         }
 2893:     }
 2894:     foreach my $item (@userinfo) {
 2895:         my $rowtitle = $lt{$item};
 2896:         my $hiderow = 0;
 2897:         if ($item eq 'generation') {
 2898:             $rowtitle = $genhelp.$rowtitle;
 2899:         }
 2900:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2901:         if ($newuser) {
 2902:             if (ref($inst_results) eq 'HASH') {
 2903:                 if ($inst_results->{$item} ne '') {
 2904:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2905:                 } else {
 2906:                     if ($context eq 'selfcreate') {
 2907:                         if ($canmodify{$item}) {
 2908:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2909:                             $editable ++;
 2910:                         } else {
 2911:                             $hiderow = 1;
 2912:                         }
 2913:                     } else {
 2914:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2915:                     }
 2916:                 }
 2917:             } else {
 2918:                 if ($context eq 'selfcreate') {
 2919:                     if ($canmodify{$item}) {
 2920:                         if ($newuser eq 'email') {
 2921:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2922:                         } else {
 2923:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2924:                         }
 2925:                         $editable ++;
 2926:                     } else {
 2927:                         $hiderow = 1;
 2928:                     }
 2929:                 } else {
 2930:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2931:                 }
 2932:             }
 2933:         } else {
 2934:             if ($canmodify{$item}) {
 2935:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2936:                 if (($item eq 'id') && (!$newuser)) {
 2937:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2938:                 }
 2939:             } else {
 2940:                 $row .= $userenv{$item};
 2941:             }
 2942:         }
 2943:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2944:         if (!$hiderow) {
 2945:             $output .= $row;
 2946:             $rowcount ++;
 2947:         }
 2948:     }
 2949:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2950:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2951:         if (ref($types) eq 'ARRAY') {
 2952:             if (@{$types} > 0) {
 2953:                 my ($hiderow,$shown);
 2954:                 if ($canmodify_status{'inststatus'}) {
 2955:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2956:                 } else {
 2957:                     if ($userenv{'inststatus'} eq '') {
 2958:                         $hiderow = 1;
 2959:                     } else {
 2960:                         my @showitems;
 2961:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2962:                             if (exists($usertypes->{$item})) {
 2963:                                 push(@showitems,$usertypes->{$item});
 2964:                             } else {
 2965:                                 push(@showitems,$item);
 2966:                             }
 2967:                         }
 2968:                         if (@showitems) {
 2969:                             $shown = join(', ',@showitems);
 2970:                         } else {
 2971:                             $hiderow = 1;
 2972:                         }
 2973:                     }
 2974:                 }
 2975:                 if (!$hiderow) {
 2976:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2977:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2978:                     if ($context eq 'selfcreate') {
 2979:                         $rowcount ++;
 2980:                     }
 2981:                     $output .= $row;
 2982:                 }
 2983:             }
 2984:         }
 2985:     }
 2986:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2987:         if ($captchaform) {
 2988:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2989:                                                          'LC_pick_box_title')."\n".
 2990:                        $captchaform."\n".'<br /><br />'.
 2991:                        &Apache::lonhtmlcommon::row_closure(1); 
 2992:             $rowcount ++;
 2993:         }
 2994:         if ($showsubmit) {
 2995:             my $submit_text = &mt('Create account');
 2996:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2997:                        '<br /><input type="submit" name="createaccount" value="'.
 2998:                        $submit_text.'" />';
 2999:             if ($usertype ne '') {
 3000:                 $output .= '<input type="hidden" name="type" value="'.
 3001:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 3002:             }
 3003:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 3004:         }
 3005:     }
 3006:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 3007:     if (wantarray) {
 3008:         if ($context eq 'selfcreate') {
 3009:             return($output,$rowcount,$editable);
 3010:         } else {
 3011:             return $output;
 3012:         }
 3013:     } else {
 3014:         return $output;
 3015:     }
 3016: }
 3017: 
 3018: sub pick_inst_statuses {
 3019:     my ($curr,$usertypes,$types) = @_;
 3020:     my ($output,$rem,@currtypes);
 3021:     if ($curr ne '') {
 3022:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 3023:     }
 3024:     my $numinrow = 2;
 3025:     if (ref($types) eq 'ARRAY') {
 3026:         $output = '<table>';
 3027:         my $lastcolspan; 
 3028:         for (my $i=0; $i<@{$types}; $i++) {
 3029:             if (defined($usertypes->{$types->[$i]})) {
 3030:                 my $rem = $i%($numinrow);
 3031:                 if ($rem == 0) {
 3032:                     if ($i<@{$types}-1) {
 3033:                         if ($i > 0) { 
 3034:                             $output .= '</tr>';
 3035:                         }
 3036:                         $output .= '<tr>';
 3037:                     }
 3038:                 } elsif ($i==@{$types}-1) {
 3039:                     my $colsleft = $numinrow - $rem;
 3040:                     if ($colsleft > 1) {
 3041:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 3042:                     }
 3043:                 }
 3044:                 my $check = ' ';
 3045:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 3046:                     $check = ' checked="checked" ';
 3047:                 }
 3048:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 3049:                            '<span class="LC_nobreak"><label>'.
 3050:                            '<input type="checkbox" name="inststatus" '.
 3051:                            'value="'.$types->[$i].'"'.$check.'/>'.
 3052:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 3053:             }
 3054:         }
 3055:         $output .= '</tr></table>';
 3056:     }
 3057:     return $output;
 3058: }
 3059: 
 3060: sub selfcreate_canmodify {
 3061:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 3062:     if (ref($inst_results) eq 'HASH') {
 3063:         my @inststatuses = &get_inststatuses($inst_results);
 3064:         if (@inststatuses == 0) {
 3065:             @inststatuses = ('default');
 3066:         }
 3067:         $rolesarray = \@inststatuses;
 3068:     }
 3069:     my %canmodify =
 3070:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 3071:                                                    $rolesarray);
 3072:     return %canmodify;
 3073: }
 3074: 
 3075: sub get_inststatuses {
 3076:     my ($insthashref) = @_;
 3077:     my @inststatuses = ();
 3078:     if (ref($insthashref) eq 'HASH') {
 3079:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 3080:             @inststatuses = @{$insthashref->{'inststatus'}};
 3081:         }
 3082:     }
 3083:     return @inststatuses;
 3084: }
 3085: 
 3086: # ================================================================= Phase Three
 3087: sub update_user_data {
 3088:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 3089:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 3090:                                           $env{'form.ccdomain'});
 3091:     # Error messages
 3092:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 3093:     my $end       = '</span><br /><br />';
 3094:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 3095:                     "'$env{'form.prevphase'}','modify')".'" />'.
 3096:                     &mt('Return to previous page').'</a>'.
 3097:                     &Apache::loncommon::end_page();
 3098:     my $now = time;
 3099:     my $title;
 3100:     if (exists($env{'form.makeuser'})) {
 3101: 	$title='Set Privileges for New User';
 3102:     } else {
 3103:         $title='Modify User Privileges';
 3104:     }
 3105:     my $newuser = 0;
 3106:     my ($jsback,$elements) = &crumb_utilities();
 3107:     my $jscript = '<script type="text/javascript">'."\n".
 3108:                   '// <![CDATA['."\n".
 3109:                   $jsback."\n".
 3110:                   '// ]]>'."\n".
 3111:                   '</script>'."\n";
 3112:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 3113:     push (@{$brcrum},
 3114:              {href => "javascript:backPage(document.userupdate)",
 3115:               text => $breadcrumb_text{'search'},
 3116:               faq  => 282,
 3117:               bug  => 'Instructor Interface',}
 3118:              );
 3119:     if ($env{'form.prevphase'} eq 'userpicked') {
 3120:         push(@{$brcrum},
 3121:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 3122:                 text => $breadcrumb_text{'userpicked'},
 3123:                 faq  => 282,
 3124:                 bug  => 'Instructor Interface',});
 3125:     }
 3126:     my $helpitem = 'Course_Change_Privileges';
 3127:     if ($env{'form.action'} eq 'singlestudent') {
 3128:         $helpitem = 'Course_Add_Student';
 3129:     } elsif ($context eq 'author') {
 3130:         $helpitem = 'Author_Change_Privileges';
 3131:     } elsif ($context eq 'domain') {
 3132:         $helpitem = 'Domain_Change_Privileges';
 3133:     }
 3134:     push(@{$brcrum}, 
 3135:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 3136:              text => $breadcrumb_text{'modify'},
 3137:              faq  => 282,
 3138:              bug  => 'Instructor Interface',},
 3139:             {href => "/adm/createuser",
 3140:              text => "Result",
 3141:              faq  => 282,
 3142:              bug  => 'Instructor Interface',
 3143:              help => $helpitem});
 3144:     my $args = {bread_crumbs          => $brcrum,
 3145:                 bread_crumbs_component => 'User Management'};
 3146:     if ($env{'form.popup'}) {
 3147:         $args->{'no_nav_bar'} = 1;
 3148:     }
 3149:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 3150:     $r->print(&update_result_form($uhome));
 3151:     # Check Inputs
 3152:     if (! $env{'form.ccuname'} ) {
 3153: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 3154: 	return;
 3155:     }
 3156:     if (  $env{'form.ccuname'} ne 
 3157: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 3158: 	$r->print($error.&mt('Invalid login name.').'  '.
 3159: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 3160: 		  $end.$rtnlink);
 3161: 	return;
 3162:     }
 3163:     if (! $env{'form.ccdomain'}       ) {
 3164: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 3165: 	return;
 3166:     }
 3167:     if (  $env{'form.ccdomain'} ne
 3168: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 3169: 	$r->print($error.&mt('Invalid domain name.').'  '.
 3170: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 3171: 		  $end.$rtnlink);
 3172: 	return;
 3173:     }
 3174:     if ($uhome eq 'no_host') {
 3175:         $newuser = 1;
 3176:     }
 3177:     if (! exists($env{'form.makeuser'})) {
 3178:         # Modifying an existing user, so check the validity of the name
 3179:         if ($uhome eq 'no_host') {
 3180:             $r->print(
 3181:                 $error
 3182:                .'<p class="LC_error">'
 3183:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 3184:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 3185:                .'</p>');
 3186:             return;
 3187:         }
 3188:     }
 3189:     # Determine authentication method and password for the user being modified
 3190:     my $amode='';
 3191:     my $genpwd='';
 3192:     if ($env{'form.login'} eq 'krb') {
 3193: 	$amode='krb';
 3194: 	$amode.=$env{'form.krbver'};
 3195: 	$genpwd=$env{'form.krbarg'};
 3196:     } elsif ($env{'form.login'} eq 'int') {
 3197: 	$amode='internal';
 3198: 	$genpwd=$env{'form.intarg'};
 3199:     } elsif ($env{'form.login'} eq 'fsys') {
 3200: 	$amode='unix';
 3201: 	$genpwd=$env{'form.fsysarg'};
 3202:     } elsif ($env{'form.login'} eq 'loc') {
 3203: 	$amode='localauth';
 3204: 	$genpwd=$env{'form.locarg'};
 3205: 	$genpwd=" " if (!$genpwd);
 3206:     } elsif ($env{'form.login'} eq 'lti') {
 3207:         $amode='lti';
 3208:         $genpwd=" ";
 3209:     } elsif (($env{'form.login'} eq 'nochange') ||
 3210:              ($env{'form.login'} eq ''        )) { 
 3211:         # There is no need to tell the user we did not change what they
 3212:         # did not ask us to change.
 3213:         # If they are creating a new user but have not specified login
 3214:         # information this will be caught below.
 3215:     } else {
 3216:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 3217:             return;
 3218:     }
 3219: 
 3220:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 3221:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 3222:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 3223:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 3224: 
 3225:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 3226:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3227:     my @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
 3228:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 3229:     my @requestauthor = ('requestauthor');
 3230:     my @authordefaults = ('webdav','editors','managers');
 3231:     my ($othertitle,$usertypes,$types) = 
 3232:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 3233:     my %canmodify_status =
 3234:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 3235:                                                    ['inststatus']);
 3236:     if ($env{'form.makeuser'}) {
 3237: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 3238:         # Check for the authentication mode and password
 3239:         if (! $amode || ! $genpwd) {
 3240: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 3241: 	    return;
 3242: 	}
 3243:         # Determine desired host
 3244:         my $desiredhost = $env{'form.hserver'};
 3245:         if (lc($desiredhost) eq 'default') {
 3246:             $desiredhost = undef;
 3247:         } else {
 3248:             my %home_servers = 
 3249: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 3250:             if (! exists($home_servers{$desiredhost})) {
 3251:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 3252:                 return;
 3253:             }
 3254:         }
 3255:         # Check ID format
 3256:         my %checkhash;
 3257:         my %checks = ('id' => 1);
 3258:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 3259:             'newuser' => $newuser, 
 3260:             'id' => $env{'form.cid'},
 3261:         );
 3262:         if ($env{'form.cid'} ne '') {
 3263:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 3264:                                           \%rulematch,\%inst_results,\%curr_rules);
 3265:             if (ref($alerts{'id'}) eq 'HASH') {
 3266:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3267:                     my $domdesc =
 3268:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 3269:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 3270:                         my $userchkmsg;
 3271:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 3272:                             $userchkmsg  = 
 3273:                                 &Apache::loncommon::instrule_disallow_msg('id',
 3274:                                                                     $domdesc,1).
 3275:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 3276:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 3277:                         }
 3278:                         $r->print($error.&mt('Invalid ID format').$end.
 3279:                                   $userchkmsg.$rtnlink);
 3280:                         return;
 3281:                     }
 3282:                 }
 3283:             }
 3284:         }
 3285:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 3286: 	# Call modifyuser
 3287: 	my $result = &Apache::lonnet::modifyuser
 3288: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 3289:              $amode,$genpwd,$env{'form.cfirstname'},
 3290:              $env{'form.cmiddlename'},$env{'form.clastname'},
 3291:              $env{'form.cgeneration'},undef,$desiredhost,
 3292:              $env{'form.cpermanentemail'});
 3293: 	$r->print(&mt('Generating user').': '.$result);
 3294:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 3295:                                                $env{'form.ccdomain'});
 3296:         my (%changeHash,%newcustom,%changed,%changedinfo);
 3297:         if ($uhome ne 'no_host') {
 3298:             if ($context eq 'domain') {
 3299:                 foreach my $name ('portfolio','author') {
 3300:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3301:                         if ($env{'form.'.$name.'quota'} eq '') {
 3302:                             $newcustom{$name.'quota'} = 0;
 3303:                         } else {
 3304:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 3305:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 3306:                         }
 3307:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 3308:                             $changed{$name.'quota'} = 1;
 3309:                         }
 3310:                     }
 3311:                 }
 3312:                 foreach my $item (@usertools) {
 3313:                     if ($env{'form.custom'.$item} == 1) {
 3314:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3315:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3316:                                                      \%changeHash,'tools');
 3317:                     }
 3318:                 }
 3319:                 foreach my $item (@requestcourses) {
 3320:                     if ($env{'form.custom'.$item} == 1) {
 3321:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3322:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3323:                             $newcustom{$item} .= '=';
 3324:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3325:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3326:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3327:                             }
 3328:                         }
 3329:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3330:                                                       \%changeHash,'requestcourses');
 3331:                     }
 3332:                 }
 3333:                 if ($env{'form.customrequestauthor'} == 1) {
 3334:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3335:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3336:                                                     $newcustom{'requestauthor'},
 3337:                                                     \%changeHash,'requestauthor');
 3338:                 }
 3339:                 if ($env{'form.customeditors'} == 1) {
 3340:                     my @editors;
 3341:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 3342:                     if (@posseditors) {
 3343:                         foreach my $editor (@posseditors) {
 3344:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 3345:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 3346:                                     push(@editors,$editor);
 3347:                                 }
 3348:                             }
 3349:                         }
 3350:                     }
 3351:                     if (@editors) {
 3352:                         @editors = sort(@editors);
 3353:                         $changed{'editors'} = &tool_admin('editors',join(',',@editors),
 3354:                                                           \%changeHash,'authordefaults');
 3355:                     }
 3356:                 }
 3357:                 if ($env{'form.customwebdav'} == 1) {
 3358:                     $newcustom{'webdav'} = $env{'form.authordefaults_webdav'};
 3359:                     $changed{'webdav'} = &tool_admin('webdav',$newcustom{'webdav'},
 3360:                                                   \%changeHash,'authordefaults');
 3361:                 }
 3362:             }
 3363:             if ($canmodify_status{'inststatus'}) {
 3364:                 if (exists($env{'form.inststatus'})) {
 3365:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3366:                     if (@inststatuses > 0) {
 3367:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3368:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3369:                     }
 3370:                 }
 3371:             }
 3372:             if (keys(%changed)) {
 3373:                 foreach my $item (@userinfo) {
 3374:                     $changeHash{$item}  = $env{'form.c'.$item};
 3375:                 }
 3376:                 my $chgresult =
 3377:                      &Apache::lonnet::put('environment',\%changeHash,
 3378:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3379:             }
 3380:         }
 3381:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3382:                   &Apache::lonnet::hostname($uhome));
 3383:     } elsif (($env{'form.login'} ne 'nochange') &&
 3384:              ($env{'form.login'} ne ''        )) {
 3385: 	# Modify user privileges
 3386:         if (! $amode || ! $genpwd) {
 3387: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3388: 	    return;
 3389: 	}
 3390: 	# Only allow authentication modification if the person has authority
 3391: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3392: 	    $r->print('Modifying authentication: '.
 3393:                       &Apache::lonnet::modifyuserauth(
 3394: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3395:                        $amode,$genpwd));
 3396:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3397: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3398: 	} else {
 3399: 	    # Okay, this is a non-fatal error.
 3400: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3401: 	}
 3402:     } elsif (($env{'form.intarg'} ne '') &&
 3403:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3404:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3405:         $r->print('Modifying authentication: '.
 3406:                   &Apache::lonnet::modifyuserauth(
 3407:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3408:                   'internal',$env{'form.intarg'}));
 3409:     }
 3410:     $r->rflush(); # Finish display of header before time consuming actions start
 3411:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3412:     ##
 3413:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3414:     if ($context eq 'course') {
 3415:         ($cnum,$cdom) =
 3416:             &Apache::lonuserutils::get_course_identity();
 3417:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3418:         if ($showcredits) {
 3419:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3420:         }
 3421:     }
 3422:     if (! $env{'form.makeuser'} ) {
 3423:         # Check for need to change
 3424:         my %userenv = &Apache::lonnet::get
 3425:             ('environment',['firstname','middlename','lastname','generation',
 3426:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3427:              'tools.aboutme','tools.blog','tools.webdav',
 3428:              'tools.portfolio','tools.timezone','tools.portaccess',
 3429:              'authormanagers','authoreditors','requestauthor',
 3430:              'requestcourses.official','requestcourses.unofficial',
 3431:              'requestcourses.community','requestcourses.textbook',
 3432:              'requestcourses.placement','requestcourses.lti',
 3433:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3434:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3435:              'reqcrsotherdom.placement'],
 3436:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3437:         my ($tmp) = keys(%userenv);
 3438:         if ($tmp =~ /^(con_lost|error)/i) { 
 3439:             %userenv = ();
 3440:         }
 3441:         my $no_forceid_alert;
 3442:         # Check to see if user information can be changed
 3443:         my %domconfig =
 3444:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3445:                                      $env{'form.ccdomain'});
 3446:         my @statuses = ('active','future');
 3447:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3448:         my ($auname,$audom);
 3449:         if ($context eq 'author') {
 3450:             $auname = $env{'user.name'};
 3451:             $audom = $env{'user.domain'};     
 3452:         }
 3453:         foreach my $item (keys(%roles)) {
 3454:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3455:             if ($context eq 'course') {
 3456:                 if ($cnum ne '' && $cdom ne '') {
 3457:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3458:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3459:                             push(@userroles,$role);
 3460:                         }
 3461:                     }
 3462:                 }
 3463:             } elsif ($context eq 'author') {
 3464:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3465:                     if (!grep(/^\Q$role\E$/,@userroles)) {
 3466:                         push(@userroles,$role);
 3467:                     }
 3468:                 }
 3469:             }
 3470:         }
 3471:         if ($env{'form.action'} eq 'singlestudent') {
 3472:             if (!grep(/^st$/,@userroles)) {
 3473:                 push(@userroles,'st');
 3474:             }
 3475:         } else {
 3476:             # Check for course or co-author roles being activated or re-enabled
 3477:             if ($context eq 'author' || $context eq 'course') {
 3478:                 foreach my $key (keys(%env)) {
 3479:                     if ($context eq 'author') {
 3480:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3481:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3482:                                 push(@userroles,$1);
 3483:                             }
 3484:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3485:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3486:                                 push(@userroles,$1);
 3487:                             }
 3488:                         }
 3489:                     } elsif ($context eq 'course') {
 3490:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3491:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3492:                                 push(@userroles,$1);
 3493:                             }
 3494:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3495:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3496:                                 push(@userroles,$1);
 3497:                             }
 3498:                         }
 3499:                     }
 3500:                 }
 3501:             }
 3502:         }
 3503:         #Check to see if we can change personal data for the user 
 3504:         my (@mod_disallowed,@longroles);
 3505:         foreach my $role (@userroles) {
 3506:             if ($role eq 'cr') {
 3507:                 push(@longroles,'Custom');
 3508:             } else {
 3509:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3510:             }
 3511:         }
 3512:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3513:         foreach my $item (@userinfo) {
 3514:             # Strip leading and trailing whitespace
 3515:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3516:             if (!$canmodify{$item}) {
 3517:                 if (defined($env{'form.c'.$item})) {
 3518:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3519:                         push(@mod_disallowed,$item);
 3520:                     }
 3521:                 }
 3522:                 $env{'form.c'.$item} = $userenv{$item};
 3523:             }
 3524:         }
 3525:         # Check to see if we can change the Student/Employee ID
 3526:         my $forceid = $env{'form.forceid'};
 3527:         my $recurseid = $env{'form.recurseid'};
 3528:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3529:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3530:                                             $env{'form.ccuname'});
 3531:         if (($uidhash{$env{'form.ccuname'}}) && 
 3532:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3533:             (!$forceid)) {
 3534:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3535:                 $env{'form.cid'} = $userenv{'id'};
 3536:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3537:                                    .'<br />'
 3538:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3539:                                    .'<br />'."\n";
 3540:             }
 3541:         }
 3542:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3543:             my $checkhash;
 3544:             my $checks = { 'id' => 1 };
 3545:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3546:                    { 'newuser' => $newuser,
 3547:                      'id'  => $env{'form.cid'}, 
 3548:                    };
 3549:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3550:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3551:             if (ref($alerts{'id'}) eq 'HASH') {
 3552:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3553:                    $env{'form.cid'} = $userenv{'id'};
 3554:                 }
 3555:             }
 3556:         }
 3557:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3558:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3559:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3560:             %oldsettingstatus,%newsettingstatus);
 3561:         @disporder = ('inststatus');
 3562:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3563:             push(@disporder,('requestcourses','requestauthor','authordefaults'));
 3564:         } else {
 3565:             push(@disporder,'reqcrsotherdom');
 3566:         }
 3567:         push(@disporder,('quota','tools'));
 3568:         $oldinststatus = $userenv{'inststatus'};
 3569:         foreach my $name ('portfolio','author') {
 3570:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3571:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3572:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3573:         }
 3574:         my %canshow;
 3575:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3576:             $canshow{'quota'} = 1;
 3577:         }
 3578:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3579:             $canshow{'tools'} = 1;
 3580:         }
 3581:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3582:             $canshow{'requestcourses'} = 1;
 3583:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3584:             $canshow{'reqcrsotherdom'} = 1;
 3585:         }
 3586:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3587:             $canshow{'inststatus'} = 1;
 3588:         }
 3589:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3590:             $canshow{'requestauthor'} = 1;
 3591:             $canshow{'authordefaults'} = 1;
 3592:         }
 3593:         my (%changeHash,%changed);
 3594:         if ($oldinststatus eq '') {
 3595:             $oldsettings{'inststatus'} = $othertitle; 
 3596:         } else {
 3597:             if (ref($usertypes) eq 'HASH') {
 3598:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3599:             } else {
 3600:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3601:             }
 3602:         }
 3603:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3604:         if ($canmodify_status{'inststatus'}) {
 3605:             $canshow{'inststatus'} = 1;
 3606:             if (exists($env{'form.inststatus'})) {
 3607:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3608:                 if (@inststatuses > 0) {
 3609:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3610:                     $changeHash{'inststatus'} = $newinststatus;
 3611:                     if ($newinststatus ne $oldinststatus) {
 3612:                         $changed{'inststatus'} = $newinststatus;
 3613:                         foreach my $name ('portfolio','author') {
 3614:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3615:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3616:                         }
 3617:                     }
 3618:                     if (ref($usertypes) eq 'HASH') {
 3619:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3620:                     } else {
 3621:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3622:                     }
 3623:                 }
 3624:             } else {
 3625:                 $newinststatus = '';
 3626:                 $changeHash{'inststatus'} = $newinststatus;
 3627:                 $newsettings{'inststatus'} = $othertitle;
 3628:                 if ($newinststatus ne $oldinststatus) {
 3629:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3630:                     foreach my $name ('portfolio','author') {
 3631:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3632:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3633:                     }
 3634:                 }
 3635:             }
 3636:         } elsif ($context ne 'selfcreate') {
 3637:             $canshow{'inststatus'} = 1;
 3638:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3639:         }
 3640:         foreach my $name ('portfolio','author') {
 3641:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3642:         }
 3643:         if ($context eq 'domain') {
 3644:             foreach my $name ('portfolio','author') {
 3645:                 if ($userenv{$name.'quota'} ne '') {
 3646:                     $oldquota{$name} = $userenv{$name.'quota'};
 3647:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3648:                         if ($env{'form.'.$name.'quota'} eq '') {
 3649:                             $newquota{$name} = 0;
 3650:                         } else {
 3651:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3652:                             $newquota{$name} =~ s/[^\d\.]//g;
 3653:                         }
 3654:                         if ($newquota{$name} != $oldquota{$name}) {
 3655:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3656:                                 $changed{$name.'quota'} = 1;
 3657:                             }
 3658:                         }
 3659:                     } else {
 3660:                         if (&quota_admin('',\%changeHash,$name)) {
 3661:                             $changed{$name.'quota'} = 1;
 3662:                             $newquota{$name} = $newdefquota{$name};
 3663:                             $newisdefault{$name} = 1;
 3664:                         }
 3665:                     }
 3666:                 } else {
 3667:                     $oldisdefault{$name} = 1;
 3668:                     $oldquota{$name} = $olddefquota{$name};
 3669:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3670:                         if ($env{'form.'.$name.'quota'} eq '') {
 3671:                             $newquota{$name} = 0;
 3672:                         } else {
 3673:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3674:                             $newquota{$name} =~ s/[^\d\.]//g;
 3675:                         }
 3676:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3677:                             $changed{$name.'quota'} = 1;
 3678:                         }
 3679:                     } else {
 3680:                         $newquota{$name} = $newdefquota{$name};
 3681:                         $newisdefault{$name} = 1;
 3682:                     }
 3683:                 }
 3684:                 if ($oldisdefault{$name}) {
 3685:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3686:                 }  else {
 3687:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3688:                 }
 3689:                 if ($newisdefault{$name}) {
 3690:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3691:                 } else {
 3692:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3693:                 }
 3694:             }
 3695:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3696:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3697:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3698:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3699:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3700:                 my ($isadv,$isauthor) =
 3701:                     &Apache::lonnet::is_advanced_user($env{'form.ccdomain'},$env{'form.ccuname'});
 3702:                 unless ($isauthor) {
 3703:                     &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3704:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3705:                 }
 3706:                 &tool_changes('authordefaults',\@authordefaults,\%oldsettings,\%oldsettingstext,
 3707:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3708:             } else {
 3709:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3710:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3711:             }
 3712:         }
 3713:         foreach my $item (@userinfo) {
 3714:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3715:                 $namechanged{$item} = 1;
 3716:             }
 3717:         }
 3718:         foreach my $name ('portfolio','author') {
 3719:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3720:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3721:         }
 3722:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3723:             my ($chgresult,$namechgresult);
 3724:             if (keys(%changed) > 0) {
 3725:                 $chgresult =
 3726:                     &Apache::lonnet::put('environment',\%changeHash,
 3727:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3728:                 if ($chgresult eq 'ok') {
 3729:                     my ($ca_mgr_del,%ca_mgr_add);
 3730:                     if ($changed{'managers'}) {
 3731:                         my (@adds,@dels);
 3732:                         if ($changeHash{'authormanagers'} eq '') {
 3733:                             @dels = split(/,/,$userenv{'authormanagers'});
 3734:                         } elsif ($userenv{'authormanagers'} eq '') {
 3735:                             @adds = split(/,/,$changeHash{'authormanagers'});
 3736:                         } else {
 3737:                             my @old = split(/,/,$userenv{'authormanagers'});
 3738:                             my @new = split(/,/,$changeHash{'authormanagers'});
 3739:                             my @diffs = &Apache::loncommon::compare_arrays(\@old,\@new);
 3740:                             if (@diffs) {
 3741:                                 foreach my $user (@diffs) {
 3742:                                     if (grep(/^\Q$user\E$/,@old)) {
 3743:                                         push(@dels,$user);
 3744:                                     } elsif (grep(/^\Q$user\E$/,@new)) {
 3745:                                         push(@adds,$user);
 3746:                                     }
 3747:                                 }
 3748:                             }
 3749:                         }
 3750:                         my $key = "internal.manager./$env{'form.ccdomain'}/$env{'form.ccuname'}";
 3751:                         if (@dels) {
 3752:                             foreach my $user (@dels) {
 3753:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3754:                                     &Apache::lonnet::del('environment',[$key],$2,$1);
 3755:                                 }
 3756:                             }
 3757:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3758:                             if (grep(/^\Q$curruser\E$/,@dels)) {
 3759:                                 $ca_mgr_del = $key;
 3760:                             }
 3761:                         }
 3762:                         if (@adds) {
 3763:                             foreach my $user (@adds) {
 3764:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3765:                                     &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 3766:                                 }
 3767:                             }
 3768:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3769:                             if (grep(/^\Q$curruser\E$/,@adds)) {
 3770:                                 $ca_mgr_add{$key} = 1;
 3771:                             }
 3772:                         }
 3773:                     }
 3774:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3775:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3776:                         my %newenvhash;
 3777:                         foreach my $key (keys(%changed)) {
 3778:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3779:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3780:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3781:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3782:                                     $changeHash{'requestcourses.'.$key};
 3783:                                 if ($changeHash{'requestcourses.'.$key}) {
 3784:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3785:                                 } else {
 3786:                                     $newenvhash{'environment.canrequest.'.$key} =
 3787:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3788:                                             $key,'reload','requestcourses');
 3789:                                 }
 3790:                             } elsif ($key eq 'requestauthor') {
 3791:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3792:                                 if ($changeHash{$key}) {
 3793:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3794:                                 } else {
 3795:                                     $newenvhash{'environment.canrequest.author'} =
 3796:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3797:                                             $key,'reload','requestauthor');
 3798:                                 }
 3799:                             } elsif ($key eq 'editors') {
 3800:                                 $newenvhash{'environment.author'.$key} = $changeHash{'author'.$key};
 3801:                                 if ($key eq 'editors') {
 3802:                                     if ($env{'form.customeditors'}) {
 3803:                                         $newenvhash{'environment.editors'} = $changeHash{'author'.$key};
 3804:                                     } else {
 3805:                                         $newenvhash{'environment.editors'} =
 3806:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3807:                                             $key,'reload','authordefaults');
 3808:                                     }
 3809:                                 }
 3810:                             } elsif ($key ne 'quota') {
 3811:                                 $newenvhash{'environment.tools.'.$key} = 
 3812:                                     $changeHash{'tools.'.$key};
 3813:                                 if ($changeHash{'tools.'.$key} ne '') {
 3814:                                     $newenvhash{'environment.availabletools.'.$key} =
 3815:                                         $changeHash{'tools.'.$key};
 3816:                                 } else {
 3817:                                     $newenvhash{'environment.availabletools.'.$key} =
 3818:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3819:                                             $key,'reload','tools');
 3820:                                 }
 3821:                             }
 3822:                         }
 3823:                         if (keys(%newenvhash)) {
 3824:                             &Apache::lonnet::appenv(\%newenvhash);
 3825:                         }
 3826:                     } else {
 3827:                         if ($ca_mgr_del) {
 3828:                             &Apache::lonnet::delenv($ca_mgr_del);
 3829:                         }
 3830:                         if (keys(%ca_mgr_add)) {
 3831:                             &Apache::lonnet::appenv(\%ca_mgr_add);
 3832:                         }
 3833:                     }
 3834:                     if ($changed{'aboutme'}) {
 3835:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3836:                                                                      $env{'form.ccdomain'});
 3837:                     }
 3838:                 }
 3839:             }
 3840:             if (keys(%namechanged) > 0) {
 3841:                 foreach my $field (@userinfo) {
 3842:                     $changeHash{$field}  = $env{'form.c'.$field};
 3843:                 }
 3844: # Make the change
 3845:                 $namechgresult =
 3846:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3847:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3848:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3849:                         $changeHash{'lastname'},$changeHash{'generation'},
 3850:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3851:                 %userupdate = (
 3852:                                lastname   => $env{'form.clastname'},
 3853:                                middlename => $env{'form.cmiddlename'},
 3854:                                firstname  => $env{'form.cfirstname'},
 3855:                                generation => $env{'form.cgeneration'},
 3856:                                id         => $env{'form.cid'},
 3857:                              );
 3858:             }
 3859:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3860:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3861:             # Tell the user we changed the name
 3862:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3863:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3864:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3865:                                   \%newsettingstext);
 3866:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3867:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3868:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3869:                     if (($recurseid) &&
 3870:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3871:                         my $idresult = 
 3872:                             &Apache::lonuserutils::propagate_id_change(
 3873:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3874:                                 \%userupdate);
 3875:                         $r->print('<br />'.$idresult.'<br />');
 3876:                     }
 3877:                 }
 3878:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3879:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3880:                     my %newenvhash;
 3881:                     foreach my $key (keys(%changeHash)) {
 3882:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3883:                     }
 3884:                     &Apache::lonnet::appenv(\%newenvhash);
 3885:                 }
 3886:             } else { # error occurred
 3887:                 $r->print(
 3888:                     '<p class="LC_error">'
 3889:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3890:                             '"'.$env{'form.ccuname'}.'"',
 3891:                             '"'.$env{'form.ccdomain'}.'"')
 3892:                    .'</p>');
 3893:             }
 3894:         } else { # End of if ($env ... ) logic
 3895:             # They did not want to change the users name, quota, tool availability,
 3896:             # or ability to request creation of courses, 
 3897:             # but we can still tell them what the name and quota and availabilities are  
 3898:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3899:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3900:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3901:         }
 3902:         if (@mod_disallowed) {
 3903:             my ($rolestr,$contextname);
 3904:             if (@longroles > 0) {
 3905:                 $rolestr = join(', ',@longroles);
 3906:             } else {
 3907:                 $rolestr = &mt('No roles');
 3908:             }
 3909:             if ($context eq 'course') {
 3910:                 $contextname = 'course';
 3911:             } elsif ($context eq 'author') {
 3912:                 $contextname = 'co-author';
 3913:             }
 3914:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3915:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3916:             foreach my $field (@mod_disallowed) {
 3917:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3918:             }
 3919:             $r->print('</ul>');
 3920:             if (@mod_disallowed == 1) {
 3921:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3922:             } else {
 3923:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3924:             }
 3925:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3926:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3927:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3928:                          ,'<a href="'.$helplink.'">','</a>')
 3929:                       .'<br />');
 3930:         }
 3931:         $r->print('<span class="LC_warning">'
 3932:                   .$no_forceid_alert
 3933:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3934:                   .'</span>');
 3935:     }
 3936:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3937:     if ($env{'form.action'} eq 'singlestudent') {
 3938:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3939:                                $crstype,$showcredits,$defaultcredits);
 3940:         my $linktext = ($crstype eq 'Community' ?
 3941:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3942:         $r->print(
 3943:             &Apache::lonhtmlcommon::actionbox([
 3944:                 '<a href="javascript:backPage(document.userupdate)">'
 3945:                .($crstype eq 'Community' ? 
 3946:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3947:                .'</a>']));
 3948:     } else {
 3949:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3950:         if (keys(%namechanged) > 0) {
 3951:             if ($context eq 'course') {
 3952:                 if (@userroles > 0) {
 3953:                     if ((@rolechanges == 0) || 
 3954:                         (!(grep(/^st$/,@rolechanges)))) {
 3955:                         if (grep(/^st$/,@userroles)) {
 3956:                             my $classlistupdated =
 3957:                                 &Apache::lonuserutils::update_classlist($cdom,
 3958:                                               $cnum,$env{'form.ccdomain'},
 3959:                                        $env{'form.ccuname'},\%userupdate);
 3960:                         }
 3961:                     }
 3962:                 }
 3963:             }
 3964:         }
 3965:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3966:                                                      $env{'form.ccdomain'});
 3967:         if ($env{'form.popup'}) {
 3968:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3969:         } else {
 3970:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3971:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3972:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3973:         }
 3974:     }
 3975: }
 3976: 
 3977: sub display_userinfo {
 3978:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3979:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3980:         $newsetting,$newsettingtext) = @_;
 3981:     return unless (ref($order) eq 'ARRAY' &&
 3982:                    ref($canshow) eq 'HASH' && 
 3983:                    ref($requestcourses) eq 'ARRAY' && 
 3984:                    ref($requestauthor) eq 'ARRAY' &&
 3985:                    ref($usertools) eq 'ARRAY' && 
 3986:                    ref($userenv) eq 'HASH' &&
 3987:                    ref($changedhash) eq 'HASH' &&
 3988:                    ref($oldsetting) eq 'HASH' &&
 3989:                    ref($oldsettingtext) eq 'HASH' &&
 3990:                    ref($newsetting) eq 'HASH' &&
 3991:                    ref($newsettingtext) eq 'HASH');
 3992:     my %lt=&Apache::lonlocal::texthash(
 3993:          'ui'             => 'User Information',
 3994:          'uic'            => 'User Information Changed',
 3995:          'firstname'      => 'First Name',
 3996:          'middlename'     => 'Middle Name',
 3997:          'lastname'       => 'Last Name',
 3998:          'generation'     => 'Generation',
 3999:          'id'             => 'Student/Employee ID',
 4000:          'permanentemail' => 'Permanent e-mail address',
 4001:          'portfolioquota' => 'Disk space allocated to portfolio files',
 4002:          'authorquota'    => 'Disk space allocated to Authoring Space',
 4003:          'blog'           => 'Blog Availability',
 4004:          'webdav'         => 'WebDAV Availability',
 4005:          'aboutme'        => 'Personal Information Page Availability',
 4006:          'portfolio'      => 'Portfolio Availability',
 4007:          'portaccess'     => 'Portfolio Shareable',
 4008:          'timezone'       => 'Can set own Time Zone',
 4009:          'official'       => 'Can Request Official Courses',
 4010:          'unofficial'     => 'Can Request Unofficial Courses',
 4011:          'community'      => 'Can Request Communities',
 4012:          'textbook'       => 'Can Request Textbook Courses',
 4013:          'placement'      => 'Can Request Placement Tests',
 4014:          'lti'            => 'Can Request LTI Courses',
 4015:          'requestauthor'  => 'Can Request Author Role',
 4016:          'inststatus'     => "Affiliation",
 4017:          'prvs'           => 'Previous Value:',
 4018:          'chto'           => 'Changed To:',
 4019:          'editors'        => "Available Editors in Authoring Space",
 4020:          'managers'       => "Co-authors who can add/revoke co-authors",
 4021:          'edit'           => 'Standard editor (Edit)',
 4022:          'xml'            => 'Text editor (EditXML)',
 4023:          'daxe'           => 'Daxe editor (Daxe)',
 4024:     );
 4025:     if ($changed) {
 4026:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 4027:                 &Apache::loncommon::start_data_table().
 4028:                 &Apache::loncommon::start_data_table_header_row());
 4029:         $r->print("<th>&nbsp;</th>\n");
 4030:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 4031:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 4032:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4033:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 4034: 
 4035:         foreach my $item (@userinfo) {
 4036:             my $value = $env{'form.c'.$item};
 4037:             #show changes only:
 4038:             unless ($value eq $userenv->{$item}){
 4039:                 $r->print(&Apache::loncommon::start_data_table_row());
 4040:                 $r->print("<td>$lt{$item}</td>\n");
 4041:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 4042:                 $r->print("<td>$value </td>\n");
 4043:                 $r->print(&Apache::loncommon::end_data_table_row());
 4044:             }
 4045:         }
 4046:         foreach my $entry (@{$order}) {
 4047:             if ($canshow->{$entry}) {
 4048:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') ||
 4049:                     ($entry eq 'requestauthor') || ($entry eq 'authordefaults')) {
 4050:                     my @items;
 4051:                     if ($entry eq 'requestauthor') {
 4052:                         @items = ($entry);
 4053:                     } elsif ($entry eq 'authordefaults') {
 4054:                         @items = ('webdav','managers','editors');
 4055:                     } else {
 4056:                         @items = @{$requestcourses};
 4057:                     }
 4058:                     foreach my $item (@items) {
 4059:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 4060:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 4061:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 4062:                             $r->print("<td>$lt{$item}</td><td>\n");
 4063:                             unless ($item eq 'managers') {
 4064:                                 $r->print($oldsetting->{$item});
 4065:                             }
 4066:                             if ($oldsettingtext->{$item}) {
 4067:                                 if ($oldsetting->{$item}) {
 4068:                                     unless ($item eq 'managers') {
 4069:                                         $r->print(' -- ');
 4070:                                     }
 4071:                                 }
 4072:                                 $r->print($oldsettingtext->{$item});
 4073:                             }
 4074:                             $r->print("</td>\n<td>");
 4075:                             unless ($item eq 'managers') {
 4076:                                 $r->print($newsetting->{$item});
 4077:                             }
 4078:                             if ($newsettingtext->{$item}) {
 4079:                                 if ($newsetting->{$item}) {
 4080:                                     unless ($item eq 'managers') {
 4081:                                         $r->print(' -- ');
 4082:                                     }
 4083:                                 }
 4084:                                 $r->print($newsettingtext->{$item});
 4085:                             }
 4086:                             $r->print("</td>\n");
 4087:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4088:                         }
 4089:                     }
 4090:                 } elsif ($entry eq 'tools') {
 4091:                     foreach my $item (@{$usertools}) {
 4092:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 4093:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4094:                             $r->print("<td>$lt{$item}</td>\n");
 4095:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 4096:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 4097:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4098:                         }
 4099:                     }
 4100:                 } elsif ($entry eq 'quota') {
 4101:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 4102:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 4103:                         foreach my $name ('portfolio','author') {
 4104:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 4105:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4106:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 4107:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 4108:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 4109:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4110:                             }
 4111:                         }
 4112:                     }
 4113:                 } else {
 4114:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 4115:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4116:                         $r->print("<td>$lt{$entry}</td>\n");
 4117:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 4118:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 4119:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4120:                     }
 4121:                 }
 4122:             }
 4123:         }
 4124:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 4125:     } else {
 4126:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 4127:                   '<p>'.&mt('No changes made to user information').'</p>');
 4128:     }
 4129:     return;
 4130: }
 4131: 
 4132: sub tool_changes {
 4133:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 4134:         $changed,$newaccess,$newaccesstext) = @_;
 4135:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 4136:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 4137:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 4138:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 4139:         return;
 4140:     }
 4141:     my %reqdisplay = &requestchange_display();
 4142:     if ($context eq 'reqcrsotherdom') {
 4143:         my @options = ('approval','validate','autolimit');
 4144:         my $optregex = join('|',@options);
 4145:         my $cdom = $env{'request.role.domain'};
 4146:         foreach my $tool (@{$usertools}) {
 4147:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4148:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4149:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 4150:             my ($newop,$limit);
 4151:             if ($env{'form.'.$context.'_'.$tool}) {
 4152:                 $newop = $env{'form.'.$context.'_'.$tool};
 4153:                 if ($newop eq 'autolimit') {
 4154:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4155:                     $limit =~ s/\D+//g;
 4156:                     $newop .= '='.$limit;
 4157:                 }
 4158:             }
 4159:             if ($userenv->{$context.'.'.$tool} eq '') {
 4160:                 if ($newop) {
 4161:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 4162:                                                   $changeHash,$context);
 4163:                     if ($changed->{$tool}) {
 4164:                         if ($newop =~ /^autolimit/) {
 4165:                             if ($limit) {
 4166:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4167:                             } else {
 4168:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4169:                             }
 4170:                         } else {
 4171:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 4172:                         }
 4173:                     } else {
 4174:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4175:                     }
 4176:                 }
 4177:             } else {
 4178:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 4179:                 my @new;
 4180:                 my $changedoms;
 4181:                 foreach my $req (@curr) {
 4182:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 4183:                         my $oldop = $1;
 4184:                         if ($oldop =~ /^autolimit=(\d*)/) {
 4185:                             my $limit = $1;
 4186:                             if ($limit) {
 4187:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4188:                             } else {
 4189:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4190:                             }
 4191:                         } else {
 4192:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 4193:                         }
 4194:                         if ($oldop ne $newop) {
 4195:                             $changedoms = 1;
 4196:                             foreach my $item (@curr) {
 4197:                                 my ($reqdom,$option) = split(':',$item);
 4198:                                 unless ($reqdom eq $cdom) {
 4199:                                     push(@new,$item);
 4200:                                 }
 4201:                             }
 4202:                             if ($newop) {
 4203:                                 push(@new,$cdom.':'.$newop);
 4204:                             }
 4205:                             @new = sort(@new);
 4206:                         }
 4207:                         last;
 4208:                     }
 4209:                 }
 4210:                 if ((!$changedoms) && ($newop)) {
 4211:                     $changedoms = 1;
 4212:                     @new = sort(@curr,$cdom.':'.$newop);
 4213:                 }
 4214:                 if ($changedoms) {
 4215:                     my $newdomstr;
 4216:                     if (@new) {
 4217:                         $newdomstr = join(',',@new);
 4218:                     }
 4219:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 4220:                                                   $context);
 4221:                     if ($changed->{$tool}) {
 4222:                         if ($env{'form.'.$context.'_'.$tool}) {
 4223:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 4224:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4225:                                 $limit =~ s/\D+//g;
 4226:                                 if ($limit) {
 4227:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4228:                                 } else {
 4229:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4230:                                 }
 4231:                             } else {
 4232:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 4233:                             }
 4234:                         } else {
 4235:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4236:                         }
 4237:                     }
 4238:                 }
 4239:             }
 4240:         }
 4241:         return;
 4242:     }
 4243:     my %tooldesc = &Apache::lonlocal::texthash(
 4244:         'edit' => 'Standard editor (Edit)',
 4245:         'xml'  => 'Text editor (EditXML)',
 4246:         'daxe' => 'Daxe editor (Daxe)',
 4247:     );
 4248:     foreach my $tool (@{$usertools}) {
 4249:         my ($newval,$limit,$envkey);
 4250:         $envkey = $context.'.'.$tool;
 4251:         if ($context eq 'requestcourses') {
 4252:             $newval = $env{'form.crsreq_'.$tool};
 4253:             if ($newval eq 'autolimit') {
 4254:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 4255:                 $limit =~ s/\D+//g;
 4256:                 $newval .= '='.$limit;
 4257:             }
 4258:         } elsif ($context eq 'requestauthor') {
 4259:             $newval = $env{'form.'.$context};
 4260:             $envkey = $context;
 4261:         } elsif ($context eq 'authordefaults') {
 4262:             if ($tool eq 'editors') {
 4263:                 $envkey = 'authoreditors';
 4264:                 if ($env{'form.customeditors'} == 1) {
 4265:                     my @editors;
 4266:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 4267:                     if (@posseditors) {
 4268:                         foreach my $editor (@posseditors) {
 4269:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 4270:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 4271:                                     push(@editors,$editor);
 4272:                                 }
 4273:                             }
 4274:                         }
 4275:                     }
 4276:                     if (@editors) {
 4277:                         $newval = join(',',(sort(@editors)));
 4278:                     }
 4279:                 }
 4280:             } elsif ($tool eq 'managers') {
 4281:                 $envkey = 'authormanagers';
 4282:                 my @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 4283:                 if (@possibles) {
 4284:                     my %ca_roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},
 4285:                                                                  undef,['active','future'],['ca']);
 4286:                     if (keys(%ca_roles)) {
 4287:                         my @custommanagers;
 4288:                         foreach my $user (@possibles) {
 4289:                             if ($user =~ /^($match_username):($match_domain)$/) {
 4290:                                 if (exists($ca_roles{$user.':ca'})) {
 4291:                                     unless ($user eq $env{'form.ccuname'}.':'.$env{'form.ccdomain'}) {
 4292:                                         push(@custommanagers,$user);
 4293:                                     }
 4294:                                 }
 4295:                             }
 4296:                         }
 4297:                         if (@custommanagers) {
 4298:                             $newval = join(',',sort(@custommanagers));
 4299:                         }
 4300:                     }
 4301:                 }
 4302:             } elsif ($tool eq 'webdav') {
 4303:                 $envkey = 'tools.webdav';
 4304:                 $newval = $env{'form.'.$context.'_'.$tool};
 4305:             }
 4306:         } else {
 4307:             $newval = $env{'form.'.$context.'_'.$tool};
 4308:         }
 4309:         if ($userenv->{$envkey} ne '') {
 4310:             $oldaccess->{$tool} = &mt('custom');
 4311:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4312:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 4313:                     my $currlimit = $1;
 4314:                     if ($currlimit eq '') {
 4315:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4316:                     } else {
 4317:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 4318:                     }
 4319:                 } elsif ($userenv->{$envkey}) {
 4320:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4321:                 } else {
 4322:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4323:                 }
 4324:             } elsif ($context eq 'authordefaults') {
 4325:                 if ($tool eq 'managers') {
 4326:                     if ($userenv->{$envkey} eq '') {
 4327:                         $oldaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4328:                     } else {
 4329:                         my $managers = $userenv->{$envkey};
 4330:                         $managers =~ s/,/, /g;
 4331:                         $oldaccesstext->{$tool} = $managers;
 4332:                     }
 4333:                 } elsif ($tool eq 'editors') {
 4334:                     $oldaccesstext->{$tool} = &mt('can use: [_1]',
 4335:                                                   join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4336:                 } elsif ($tool eq 'webdav') {
 4337:                     if ($userenv->{$envkey}) {
 4338:                         $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4339:                     } else {
 4340:                         $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4341:                     }
 4342:                 }
 4343:             } else {
 4344:                 if ($userenv->{$envkey}) {
 4345:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4346:                 } else {
 4347:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4348:                 }
 4349:             }
 4350:             $changeHash->{$envkey} = $userenv->{$envkey};
 4351:             if (($env{'form.custom'.$tool} == 1) ||
 4352:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4353:                 if ($newval ne $userenv->{$envkey}) {
 4354:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4355:                                                     $context);
 4356:                     if ($changed->{$tool}) {
 4357:                         $newaccess->{$tool} = &mt('custom');
 4358:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4359:                             if ($newval =~ /^autolimit/) {
 4360:                                 if ($limit) {
 4361:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4362:                                 } else {
 4363:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4364:                                 }
 4365:                             } elsif ($newval) {
 4366:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 4367:                             } else {
 4368:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4369:                             }
 4370:                         } elsif ($context eq 'authordefaults') {
 4371:                             if ($tool eq 'editors') {
 4372:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4373:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$changeHash->{$envkey})));
 4374:                             } elsif ($tool eq 'managers') {
 4375:                                 if ($changeHash->{$envkey} eq '') {
 4376:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4377:                                 } else {
 4378:                                     my $managers = $changeHash->{$envkey};
 4379:                                     $managers =~ s/,/, /g;
 4380:                                     $newaccesstext->{$tool} = $managers;
 4381:                                 }
 4382:                             } elsif ($tool eq 'webdav') {
 4383:                                 if ($newval) {
 4384:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4385:                                 } else {
 4386:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4387:                                 }
 4388:                             }
 4389:                         } else {
 4390:                             if ($newval) {
 4391:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4392:                             } else {
 4393:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4394:                             }
 4395:                         }
 4396:                     } else {
 4397:                         $newaccess->{$tool} = $oldaccess->{$tool};
 4398:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4399:                             if ($userenv->{$envkey} =~ /^autolimit/) {
 4400:                                 if ($limit) {
 4401:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4402:                                 } else {
 4403:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4404:                                 }
 4405:                             } elsif ($userenv->{$envkey}) {
 4406:                                 $newaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4407:                             } else {
 4408:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4409:                             }
 4410:                         } elsif ($context eq 'authordefaults') {
 4411:                             if ($tool eq 'editors') {
 4412:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4413:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4414:                             } elsif ($tool eq 'managers') {
 4415:                                 if ($userenv->{$envkey} eq '') {
 4416:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4417:                                 } else {
 4418:                                     my $managers = $userenv->{$envkey};
 4419:                                     $managers =~ s/,/, /g;
 4420:                                     $newaccesstext->{$tool} = $managers;
 4421:                                 }
 4422:                             } elsif ($tool eq 'webdav') {
 4423:                                 if ($userenv->{$envkey}) {
 4424:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4425:                                 } else {
 4426:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4427:                                 }
 4428:                             }
 4429:                         } else {
 4430:                             if ($userenv->{$context.'.'.$tool}) {
 4431:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4432:                             } else {
 4433:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4434:                             }
 4435:                         }
 4436:                     }
 4437:                 } else {
 4438:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4439:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4440:                 }
 4441:             } else {
 4442:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 4443:                 if ($changed->{$tool}) {
 4444:                     $newaccess->{$tool} = &mt('default');
 4445:                 } else {
 4446:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4447:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4448:                         if ($newval =~ /^autolimit/) {
 4449:                             if ($limit) {
 4450:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4451:                             } else {
 4452:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4453:                             }
 4454:                         } elsif ($newval) {
 4455:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4456:                         } else {
 4457:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4458:                         }
 4459:                     } elsif ($context eq 'authordefaults') {
 4460:                         if ($tool eq 'editors') {
 4461:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4462:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4463:                         } elsif ($tool eq 'managers') {
 4464:                             if ($newval eq '') {
 4465:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4466:                             } else {
 4467:                                 my $managers = $newval;
 4468:                                 $managers =~ s/,/, /g;
 4469:                                 $newaccesstext->{$tool} = $managers;
 4470:                             }
 4471:                         } elsif ($tool eq 'webdav') {
 4472:                             if ($userenv->{$envkey}) {
 4473:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4474:                             } else {
 4475:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4476:                             }
 4477:                         }
 4478:                     } else {
 4479:                         if ($userenv->{$context.'.'.$tool}) {
 4480:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4481:                         } else {
 4482:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4483:                         }
 4484:                     }
 4485:                 }
 4486:             }
 4487:         } else {
 4488:             $oldaccess->{$tool} = &mt('default');
 4489:             if (($env{'form.custom'.$tool} == 1) ||
 4490:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4491:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4492:                                                 $context);
 4493:                 if ($changed->{$tool}) {
 4494:                     $newaccess->{$tool} = &mt('custom');
 4495:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4496:                         if ($newval =~ /^autolimit/) {
 4497:                             if ($limit) {
 4498:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4499:                             } else {
 4500:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4501:                             }
 4502:                         } elsif ($newval) {
 4503:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4504:                         } else {
 4505:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4506:                         }
 4507:                     } elsif ($context eq 'authordefaults') {
 4508:                         if ($tool eq 'managers') {
 4509:                             if ($newval eq '') {
 4510:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4511:                             } else {
 4512:                                 my $managers = $newval;
 4513:                                 $managers =~ s/,/, /g;
 4514:                                 $newaccesstext->{$tool} = $managers;
 4515:                             }
 4516:                         } elsif ($tool eq 'editors') {
 4517:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4518:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4519:                         } elsif ($tool eq 'webdav') {
 4520:                             if ($newval) {
 4521:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4522:                             } else {
 4523:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4524:                             }
 4525:                         }
 4526:                     } else {
 4527:                         if ($newval) {
 4528:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4529:                         } else {
 4530:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4531:                         }
 4532:                     }
 4533:                 } else {
 4534:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4535:                 }
 4536:             } else {
 4537:                 $newaccess->{$tool} = $oldaccess->{$tool};
 4538:             }
 4539:         }
 4540:     }
 4541:     return;
 4542: }
 4543: 
 4544: sub update_roles {
 4545:     my ($r,$context,$showcredits) = @_;
 4546:     my $now=time;
 4547:     my @rolechanges;
 4548:     my (%disallowed,%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 4549:         %pending,%reject,%notifydc,%status,%unauthorized,%currqueued);
 4550:     $got_role_approvals{$context} = '';
 4551:     $process_by{$context} = {};
 4552:     my @domroles = &Apache::lonuserutils::domain_roles();
 4553:     my @cstrroles = &Apache::lonuserutils::construction_space_roles();
 4554:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
 4555:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 4556:     foreach my $key (keys(%env)) {
 4557: 	next if (! $env{$key});
 4558:         next if ($key eq 'form.action');
 4559: 	# Revoke roles
 4560: 	if ($key=~/^form\.rev/) {
 4561: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 4562: # Revoke standard role
 4563: 		my ($scope,$role) = ($1,$2);
 4564: 		my $result =
 4565: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 4566: 						$env{'form.ccuname'},
 4567: 						$scope,$role,'','',$context);
 4568:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4569:                             &mt('Revoking [_1] in [_2]',
 4570:                                 &Apache::lonnet::plaintext($role),
 4571:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4572:                                 $result ne "ok").'<br />');
 4573:                 if ($result ne "ok") {
 4574:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4575:                 }
 4576: 		if ($role eq 'st') {
 4577: 		    my $result = 
 4578:                         &Apache::lonuserutils::classlist_drop($scope,
 4579:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4580: 			    $now);
 4581:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4582: 		}
 4583:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4584:                     push(@rolechanges,$role);
 4585:                 }
 4586: 	    }
 4587: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4588: # Revoke custom role
 4589:                 my $result = &Apache::lonnet::revokecustomrole(
 4590:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4591:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4592:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4593:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4594:                             $result ne 'ok').'<br />');
 4595:                 if ($result ne "ok") {
 4596:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4597:                 }
 4598:                 if (!grep(/^cr$/,@rolechanges)) {
 4599:                     push(@rolechanges,'cr');
 4600:                 }
 4601: 	    }
 4602: 	} elsif ($key=~/^form\.del/) {
 4603: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4604: # Delete standard role
 4605: 		my ($scope,$role) = ($1,$2);
 4606: 		my $result =
 4607: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4608: 						$env{'form.ccuname'},
 4609: 						$scope,$role,$now,0,1,'',
 4610:                                                 $context);
 4611:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4612:                             &mt('Deleting [_1] in [_2]',
 4613:                                 &Apache::lonnet::plaintext($role),
 4614:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4615:                             $result ne 'ok').'<br />');
 4616:                 if ($result ne "ok") {
 4617:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4618:                 }
 4619: 
 4620: 		if ($role eq 'st') {
 4621: 		    my $result = 
 4622:                         &Apache::lonuserutils::classlist_drop($scope,
 4623:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4624: 			    $now);
 4625: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4626: 		}
 4627:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4628:                     push(@rolechanges,$role);
 4629:                 }
 4630:             }
 4631: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4632:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4633: # Delete custom role
 4634:                 my $result =
 4635:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4636:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4637:                         0,1,$context);
 4638:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4639:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4640:                       $result ne "ok").'<br />');
 4641:                 if ($result ne "ok") {
 4642:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4643:                 }
 4644: 
 4645:                 if (!grep(/^cr$/,@rolechanges)) {
 4646:                     push(@rolechanges,'cr');
 4647:                 }
 4648:             }
 4649: 	} elsif ($key=~/^form\.ren/) {
 4650:             my $udom = $env{'form.ccdomain'};
 4651:             my $uname = $env{'form.ccuname'};
 4652: # Re-enable standard role
 4653: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4654:                 my $url = $1;
 4655:                 my $role = $2;
 4656:                 my $id = $url.'_'.$role;
 4657:                 my $logmsg;
 4658:                 my $output;
 4659:                 if ($role eq 'st') {
 4660:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4661:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4662:                         my $credits;
 4663:                         if ($showcredits) {
 4664:                             my $defaultcredits =
 4665:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4666:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4667:                         }
 4668:                         unless ($udom eq $cdom) {
 4669:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4670:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,$credits,
 4671:                                          \%process_by,\%instdoms,\%got_role_approvals,
 4672:                                          \%got_instdoms,\%reject,\%pending,\%notifydc,
 4673:                                          \%status,\%unauthorized,\%currqueued));
 4674:                         }
 4675:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4676:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4677:                             if ($result eq 'refused' && $logmsg) {
 4678:                                 $output = $logmsg;
 4679:                             } else { 
 4680:                                 $output = &mt('Error: [_1]',$result)."\n";
 4681:                             }
 4682:                         } else {
 4683:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4684:                                         &Apache::lonnet::plaintext($role),
 4685:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4686:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4687:                         }
 4688:                     }
 4689:                 } else {
 4690:                     my ($cdom,$cnum,$csec);
 4691:                     if (grep(/^\Q$role\E$/,@cstrroles)) {
 4692:                         ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_username)$});
 4693:                     } elsif (grep(/^\Q$role\E$/,@domroles)) {
 4694:                         ($cdom) = ($url =~ m{^/($match_domain)/$});
 4695:                     } elsif ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4696:                         ($cdom,$cnum,$csec) = ($1,$2,$3);
 4697:                     }
 4698:                     if ($cdom ne '') {
 4699:                         unless ($udom eq $cdom) {
 4700:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4701:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4702:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4703:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4704:                         }
 4705:                     }
 4706: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4707:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4708:                                $context);
 4709:                     $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4710:                                     &Apache::lonnet::plaintext($role),
 4711:                                     &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4712:                     if ($result ne "ok") {
 4713:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4714:                     }
 4715:                 }
 4716:                 $r->print($output);
 4717:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4718:                     push(@rolechanges,$role);
 4719:                 }
 4720: 	    }
 4721: # Re-enable custom role
 4722: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4723:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4724:                 my $id = $url.'_cr'."/$rdom/$rnam/$rolename";
 4725:                 my $role = "cr/$rdom/$rnam/$rolename";
 4726:                 if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4727:                     my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4728:                     unless ($udom eq $cdom) {
 4729:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4730:                                      $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4731:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4732:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4733:                     }
 4734:                 }
 4735:                 my $result = &Apache::lonnet::assigncustomrole(
 4736:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4737:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4738:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4739:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4740:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4741:                     $result ne "ok").'<br />');
 4742:                 if ($result ne "ok") {
 4743:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4744:                 }
 4745:                 if (!grep(/^cr$/,@rolechanges)) {
 4746:                     push(@rolechanges,'cr');
 4747:                 }
 4748:             }
 4749: 	} elsif ($key=~/^form\.act/) {
 4750:             my $udom = $env{'form.ccdomain'};
 4751:             my $uname = $env{'form.ccuname'};
 4752: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4753:                 # Activate a custom role
 4754: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4755: 		my $url='/'.$one.'/'.$two;
 4756:                 my $id = $url.'_cr/'."$three/$four/$five";
 4757:                 my $role = "cr/$three/$four/$five";
 4758: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4759: 
 4760:                 my $start = ( $env{'form.start_'.$full} ?
 4761:                               $env{'form.start_'.$full} :
 4762:                               $now );
 4763:                 my $end   = ( $env{'form.end_'.$full} ?
 4764:                               $env{'form.end_'.$full} :
 4765:                               0 );
 4766: 
 4767:                 # split multiple sections
 4768:                 my %sections = ();
 4769:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$five);
 4770:                 if ($num_sections == 0) {
 4771:                     unless ($udom eq $one) {
 4772:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4773:                                      $uname,$role,$start,$end,$one,$two,'','',\%process_by,
 4774:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4775:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4776:                     }
 4777:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4778:                 } else {
 4779: 		    my %curr_groups =
 4780: 			&Apache::longroup::coursegroups($one,$two);
 4781:                     my ($restricted,$numchanges);
 4782:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4783:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4784:                             exists($curr_groups{$sec})) {
 4785:                             $disallowed{$sec} = $url;
 4786:                             next;
 4787:                         }
 4788:                         my $securl = $url.'/'.$sec;
 4789:                         my $secid = $securl.'_cr'."/$three/$four/$five";
 4790:                         undef($restricted);
 4791:                         unless ($udom eq $one) {
 4792:                             next if (&Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4793:                                          $uname,$role,$start,$end,$one,$two,$sec,'',\%process_by,
 4794:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4795:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4796:                         }
 4797:                         $numchanges ++;
 4798: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4799:                     }
 4800:                     next unless ($numchanges);
 4801:                 }
 4802:                 if (!grep(/^cr$/,@rolechanges)) {
 4803:                     push(@rolechanges,'cr');
 4804:                 }
 4805: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4806: 		# Activate roles for sections with 3 id numbers
 4807: 		# set start, end times, and the url for the class
 4808: 		my ($one,$two,$three)=($1,$2,$3);
 4809: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ?
 4810: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} :
 4811: 			      $now );
 4812: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ?
 4813: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4814: 			      0 );
 4815: 		my $url='/'.$one.'/'.$two;
 4816:                 my $id = $url.'_'.$three;
 4817:                 # split multiple sections
 4818:                 my %sections = ();
 4819:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4820:                 my ($credits,$numchanges);
 4821:                 if ($three eq 'st') {
 4822:                     if ($showcredits) {
 4823:                         my $defaultcredits = 
 4824:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4825:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4826:                         $credits =~ s/[^\d\.]//g;
 4827:                         if ($credits eq $defaultcredits) {
 4828:                             undef($credits);
 4829:                         }
 4830:                     }
 4831:                 }
 4832:                 if ($num_sections == 0) {
 4833:                     unless ($udom eq $one) {
 4834:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4835:                                      $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4836:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4837:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4838:                     }
 4839:                     $numchanges ++;
 4840:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4841:                 } else {
 4842:                     my %curr_groups = 
 4843: 			&Apache::longroup::coursegroups($one,$two);
 4844:                     my $emptysec = 0;
 4845:                     my $restricted;
 4846:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4847:                         $sec =~ s/\W//g;
 4848:                         if ($sec ne '') {
 4849:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4850:                                 exists($curr_groups{$sec})) {
 4851:                                 $disallowed{$sec} = $url;
 4852:                                 next;
 4853:                             }
 4854:                             my $securl = $url.'/'.$sec;
 4855:                             my $secid = $securl.'_'.$three;
 4856:                             unless ($udom eq $one) {
 4857:                                 undef($restricted);
 4858:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4859:                                                   $uname,$three,$start,$end,$one,$two,$sec,$credits,\%process_by,
 4860:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4861:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4862:                                 next if ($restricted);
 4863:                             }
 4864:                             $numchanges ++;
 4865:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4866:                         } else {
 4867:                             $emptysec = 1;
 4868:                         }
 4869:                     }
 4870:                     if ($emptysec) {
 4871:                         unless ($udom eq $one) {
 4872:                             undef($restricted);
 4873:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4874:                                               $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4875:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4876:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4877:                             next if ($restricted);
 4878:                         }
 4879:                         $numchanges ++;
 4880:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4881:                     }
 4882:                     next unless ($numchanges);
 4883:                 }
 4884:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4885:                     push(@rolechanges,$three);
 4886:                 }
 4887: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4888: 		# Activate roles for sections with two id numbers
 4889: 		# set start, end times, and the url for the class
 4890: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ?
 4891: 			      $env{'form.start_'.$1.'_'.$2} :
 4892: 			      $now );
 4893: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ?
 4894: 			      $env{'form.end_'.$1.'_'.$2} :
 4895: 			      0 );
 4896:                 my $one = $1;
 4897:                 my $two = $2;
 4898: 		my $url='/'.$one.'/';
 4899:                 my $id = $url.'_'.$two;
 4900:                 my ($cdom,$cnum) = split(/\//,$one);
 4901:                 # split multiple sections
 4902:                 my %sections = ();
 4903:                 my ($restricted,$numchanges);
 4904:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4905:                 if ($num_sections == 0) {
 4906:                     unless ($udom eq $one) {
 4907:                         $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4908:                                           $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4909:                                           \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4910:                                           \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4911:                         next if ($restricted);
 4912:                     }
 4913:                     $numchanges ++;
 4914:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4915:                 } else {
 4916:                     my $emptysec = 0;
 4917:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4918:                         if ($sec ne '') {
 4919:                             my $securl = $url.'/'.$sec;
 4920:                             my $secid = $securl.'_'.$two;
 4921:                             unless ($udom eq $one) {
 4922:                                 undef($restricted);
 4923:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4924:                                                   $uname,$two,$start,$end,$cdom,$cnum,$sec,'',\%process_by,
 4925:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4926:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4927:                                 next if ($restricted);
 4928:                             }
 4929:                             $numchanges ++;
 4930:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4931:                         } else {
 4932:                             $emptysec = 1;
 4933:                         }
 4934:                     }
 4935:                     if ($emptysec) {
 4936:                         unless ($udom eq $one) {
 4937:                             undef($restricted);
 4938:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4939:                                               $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4940:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4941:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4942:                             next if ($restricted);
 4943:                         }
 4944:                         $numchanges ++;
 4945:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4946:                     }
 4947:                     next unless ($numchanges); 
 4948:                 }
 4949:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4950:                     push(@rolechanges,$two);
 4951:                 }
 4952: 	    } else {
 4953: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4954:             }
 4955:             foreach my $key (sort(keys(%disallowed))) {
 4956:                 $r->print('<p class="LC_warning">');
 4957:                 if (($key eq 'none') || ($key eq 'all')) {  
 4958:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4959:                 } else {
 4960:                     $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>'));
 4961:                 }
 4962:                 $r->print('</p><p>'
 4963:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4964:                              ,'<a href="javascript:history.go(-1)'
 4965:                              ,'</a>')
 4966:                          .'</p><br />'
 4967:                 );
 4968:             }
 4969: 	}
 4970:     } # End of foreach (keys(%env))
 4971:     if ((keys(%reject)) || (keys(%unauthorized))) {
 4972:         $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 4973:     }
 4974:     if ((keys(%pending)) || (keys(%currqueued))) {
 4975:         $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 4976:     }
 4977: # Flush the course logs so reverse user roles immediately updated
 4978:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4979:     if (@rolechanges == 0) {
 4980:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4981:     }
 4982:     return @rolechanges;
 4983: }
 4984: 
 4985: sub get_user_credits {
 4986:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4987:     if ($cdom eq '' || $cnum eq '') {
 4988:         return unless ($env{'request.course.id'});
 4989:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4990:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4991:     }
 4992:     my $credits;
 4993:     my %currhash =
 4994:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4995:     if (keys(%currhash) > 0) {
 4996:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4997:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4998:         $credits = $items[$crdidx];
 4999:         $credits =~ s/[^\d\.]//g;
 5000:     }
 5001:     if ($credits eq $defaultcredits) {
 5002:         undef($credits);
 5003:     }
 5004:     return $credits;
 5005: }
 5006: 
 5007: sub enroll_single_student {
 5008:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 5009:         $showcredits,$defaultcredits) = @_;
 5010:     $r->print('<h3>');
 5011:     if ($crstype eq 'Community') {
 5012:         $r->print(&mt('Enrolling Member'));
 5013:     } else {
 5014:         $r->print(&mt('Enrolling Student'));
 5015:     }
 5016:     $r->print('</h3>');
 5017: 
 5018:     # Remove non alphanumeric values from section
 5019:     $env{'form.sections'}=~s/\W//g;
 5020: 
 5021:     my $credits;
 5022:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 5023:         $credits = $env{'form.credits'};
 5024:         $credits =~ s/[^\d\.]//g;
 5025:         if ($credits ne '') {
 5026:             if ($credits eq $defaultcredits) {
 5027:                 undef($credits);
 5028:             }
 5029:         }
 5030:     }
 5031:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 5032:     my (%got_role_approvals,%got_instdoms,%process_by,%instdoms,%pending,%reject,%notifydc,
 5033:         %status,%unauthorized,%currqueued);
 5034:     unless ($env{'form.ccdomain'} eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 5035:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5036:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5037:         my $csec = $env{'form.sections'};
 5038:         my $id = "/$cdom/$cnum";
 5039:         if ($csec ne '') {
 5040:             $id .= "/$csec";
 5041:         }
 5042:         $id .= '_st';
 5043:         if (&Apache::lonuserutils::restricted_dom($context,$id,$env{'form.ccdomain'},$env{'form.ccuname'},
 5044:                                                   'st',$startdate,$enddate,$cdom,$cnum,$csec,$credits,
 5045:                                                   \%process_by,\%instdoms,\%got_role_approvals,\%got_instdoms,
 5046:                                                   \%reject,\%pending,\%notifydc,\%status,\%unauthorized,\%currqueued)) {
 5047:             if ((keys(%reject)) || (keys(%unauthorized))) {
 5048:                 $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5049:             }
 5050:             if ((keys(%pending)) || (keys(%currqueued))) {
 5051:                 $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5052:             }
 5053:             return;
 5054:         }
 5055:     }
 5056: 
 5057:     # Clean out any old student roles the user has in this class.
 5058:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 5059:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 5060:     my $enroll_result =
 5061:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 5062:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 5063:             $env{'form.cmiddlename'},$env{'form.clastname'},
 5064:             $env{'form.generation'},$env{'form.sections'},$enddate,
 5065:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 5066:             $credits);
 5067:     if ($enroll_result =~ /^ok/) {
 5068:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 5069:         if ($env{'form.sections'} ne '') {
 5070:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 5071:         }
 5072:         my ($showstart,$showend);
 5073:         if ($startdate <= $now) {
 5074:             $showstart = &mt('Access starts immediately');
 5075:         } else {
 5076:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 5077:         }
 5078:         if ($enddate == 0) {
 5079:             $showend = &mt('ends: no ending date');
 5080:         } else {
 5081:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 5082:         }
 5083:         $r->print('.<br />'.$showstart.'; '.$showend);
 5084:         if ($startdate <= $now && !$newuser) {
 5085:             $r->print('<p class="LC_info">');
 5086:             if ($crstype eq 'Community') {
 5087:                 $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.'));
 5088:             } else {
 5089:                 $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.'));
 5090:            }
 5091:            $r->print('</p>');
 5092:         }
 5093:     } else {
 5094:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 5095:     }
 5096:     return;
 5097: }
 5098: 
 5099: sub get_defaultquota_text {
 5100:     my ($settingstatus) = @_;
 5101:     my $defquotatext; 
 5102:     if ($settingstatus eq '') {
 5103:         $defquotatext = &mt('default');
 5104:     } else {
 5105:         my ($usertypes,$order) =
 5106:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 5107:         if ($usertypes->{$settingstatus} eq '') {
 5108:             $defquotatext = &mt('default');
 5109:         } else {
 5110:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 5111:         }
 5112:     }
 5113:     return $defquotatext;
 5114: }
 5115: 
 5116: sub update_result_form {
 5117:     my ($uhome) = @_;
 5118:     my $outcome = 
 5119:     '<form name="userupdate" method="post" action="">'."\n";
 5120:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 5121:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5122:     }
 5123:     if ($env{'form.origname'} ne '') {
 5124:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 5125:     }
 5126:     foreach my $item ('sortby','seluname','seludom') {
 5127:         if (exists($env{'form.'.$item})) {
 5128:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5129:         }
 5130:     }
 5131:     if ($uhome eq 'no_host') {
 5132:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 5133:     }
 5134:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 5135:                 '<input type="hidden" name="currstate" value="" />'."\n".
 5136:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5137:                 '</form>';
 5138:     return $outcome;
 5139: }
 5140: 
 5141: sub quota_admin {
 5142:     my ($setquota,$changeHash,$name) = @_;
 5143:     my $quotachanged;
 5144:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 5145:         # Current user has quota modification privileges
 5146:         if (ref($changeHash) eq 'HASH') {
 5147:             $quotachanged = 1;
 5148:             $changeHash->{$name.'quota'} = $setquota;
 5149:         }
 5150:     }
 5151:     return $quotachanged;
 5152: }
 5153: 
 5154: sub tool_admin {
 5155:     my ($tool,$settool,$changeHash,$context) = @_;
 5156:     my $canchange = 0; 
 5157:     if ($context eq 'requestcourses') {
 5158:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 5159:             $canchange = 1;
 5160:         }
 5161:     } elsif ($context eq 'reqcrsotherdom') {
 5162:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 5163:             $canchange = 1;
 5164:         }
 5165:     } elsif ($context eq 'requestauthor') {
 5166:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5167:             $canchange = 1;
 5168:         }
 5169:     } elsif ($context eq 'authordefaults') {
 5170:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5171:             $canchange = 1;
 5172:         }
 5173:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 5174:         # Current user has quota modification privileges
 5175:         $canchange = 1;
 5176:     }
 5177:     my $toolchanged;
 5178:     if ($canchange) {
 5179:         if (ref($changeHash) eq 'HASH') {
 5180:             $toolchanged = 1;
 5181:             if ($tool eq 'requestauthor') {
 5182:                 $changeHash->{$context} = $settool;
 5183:             } elsif (($tool eq 'managers') || ($tool eq 'editors')) {
 5184:                 $changeHash->{'author'.$tool} = $settool;
 5185:             } elsif ($tool eq 'webdav') {
 5186:                 $changeHash->{'tools.'.$tool} = $settool;
 5187:             } else {
 5188:                 $changeHash->{$context.'.'.$tool} = $settool;
 5189:             }
 5190:         }
 5191:     }
 5192:     return $toolchanged;
 5193: }
 5194: 
 5195: sub build_roles {
 5196:     my ($sectionstr,$sections,$role) = @_;
 5197:     my $num_sections = 0;
 5198:     if ($sectionstr=~ /,/) {
 5199:         my @secnums = split/,/,$sectionstr;
 5200:         if ($role eq 'st') {
 5201:             $secnums[0] =~ s/\W//g;
 5202:             $$sections{$secnums[0]} = 1;
 5203:             $num_sections = 1;
 5204:         } else {
 5205:             foreach my $sec (@secnums) {
 5206:                 $sec =~ ~s/\W//g;
 5207:                 if (!($sec eq "")) {
 5208:                     if (exists($$sections{$sec})) {
 5209:                         $$sections{$sec} ++;
 5210:                     } else {
 5211:                         $$sections{$sec} = 1;
 5212:                         $num_sections ++;
 5213:                     }
 5214:                 }
 5215:             }
 5216:         }
 5217:     } else {
 5218:         $sectionstr=~s/\W//g;
 5219:         unless ($sectionstr eq '') {
 5220:             $$sections{$sectionstr} = 1;
 5221:             $num_sections ++;
 5222:         }
 5223:     }
 5224: 
 5225:     return $num_sections;
 5226: }
 5227: 
 5228: # ========================================================== Custom Role Editor
 5229: 
 5230: sub custom_role_editor {
 5231:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5232:     my $action = $env{'form.customroleaction'};
 5233:     my ($rolename,$helpitem);
 5234:     if ($action eq 'new') {
 5235:         $rolename=$env{'form.newrolename'};
 5236:     } else {
 5237:         $rolename=$env{'form.rolename'};
 5238:     }
 5239: 
 5240:     my ($crstype,$context);
 5241:     if ($env{'request.course.id'}) {
 5242:         $crstype = &Apache::loncommon::course_type();
 5243:         $context = 'course';
 5244:         $helpitem = 'Course_Editing_Custom_Roles';
 5245:     } else {
 5246:         $context = 'domain';
 5247:         $crstype = 'course';
 5248:         $helpitem = 'Domain_Editing_Custom_Roles';
 5249:     }
 5250: 
 5251:     $rolename=~s/[^A-Za-z0-9]//gs;
 5252:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 5253: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 5254:                                    $permission);
 5255:         return;
 5256:     }
 5257: 
 5258:     my $formname = 'form1';
 5259:     my %privs=();
 5260:     my $body_top = '<h2>';
 5261: # ------------------------------------------------------- Does this role exist?
 5262:     my ($rdummy,$roledef)=
 5263: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5264:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5265:         $body_top .= &mt('Existing Role').' "';
 5266: # ------------------------------------------------- Get current role privileges
 5267:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 5268:         if ($privs{'system'} =~ /bre\&S/) {
 5269:             if ($context eq 'domain') {
 5270:                 $crstype = 'Course';
 5271:             } elsif ($crstype eq 'Community') {
 5272:                 $privs{'system'} =~ s/bre\&S//;
 5273:             }
 5274:         } elsif ($context eq 'domain') {
 5275:             $crstype = 'Course';
 5276:         }
 5277:     } else {
 5278:         $body_top .= &mt('New Role').' "';
 5279:         $roledef='';
 5280:     }
 5281:     $body_top .= $rolename.'"</h2>';
 5282: 
 5283: # ------------------------------------------------------- What can be assigned?
 5284:     my %full=();
 5285:     my %levels=(
 5286:                  course => {},
 5287:                  domain => {},
 5288:                  system => {},
 5289:                );
 5290:     my %levelscurrent=(
 5291:                         course => {},
 5292:                         domain => {},
 5293:                         system => {},
 5294:                       );
 5295:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5296:     my ($jsback,$elements) = &crumb_utilities();
 5297:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5298:     my $head_script =
 5299:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 5300:                                                   \%full,\@templateroles,$jsback);
 5301:     push (@{$brcrum},
 5302:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 5303:                text => "Pick custom role",
 5304:                faq  => 282,bug=>'Instructor Interface',},
 5305:               {href => "javascript:backPage(document.$formname,'','')",
 5306:                text => "Edit custom role",
 5307:                faq  => 282,
 5308:                bug  => 'Instructor Interface',
 5309:                help => $helpitem}
 5310:               );
 5311:     my $args = { bread_crumbs          => $brcrum,
 5312:                  bread_crumbs_component => 'User Management'};
 5313:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 5314:                                              $head_script,$args).
 5315:               $body_top);
 5316:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 5317:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 5318:                                                         \@templateroles,$prefix));
 5319: 
 5320:     $r->print(<<ENDCCF);
 5321: <input type="hidden" name="phase" value="set_custom_roles" />
 5322: <input type="hidden" name="rolename" value="$rolename" />
 5323: ENDCCF
 5324:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5325:                                                        \%levelscurrent,$prefix));
 5326:     $r->print(&Apache::loncommon::end_data_table().
 5327:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 5328:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 5329:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 5330:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 5331:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 5332: }
 5333: 
 5334: # ---------------------------------------------------------- Call to definerole
 5335: sub set_custom_role {
 5336:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5337:     my $rolename=$env{'form.rolename'};
 5338:     $rolename=~s/[^A-Za-z0-9]//gs;
 5339:     if (!$rolename) {
 5340: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5341:         return;
 5342:     }
 5343:     my ($jsback,$elements) = &crumb_utilities();
 5344:     my $jscript = '<script type="text/javascript">'
 5345:                  .'// <![CDATA['."\n"
 5346:                  .$jsback."\n"
 5347:                  .'// ]]>'."\n"
 5348:                  .'</script>'."\n";
 5349:     my $helpitem = 'Course_Editing_Custom_Roles';
 5350:     if ($context eq 'domain') {
 5351:         $helpitem = 'Domain_Editing_Custom_Roles';
 5352:     }
 5353:     push(@{$brcrum},
 5354:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 5355:          text => "Pick custom role",
 5356:          faq  => 282,
 5357:          bug  => 'Instructor Interface',},
 5358:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 5359:          text => "Edit custom role",
 5360:          faq  => 282,
 5361:          bug  => 'Instructor Interface',},
 5362:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 5363:          text => "Result",
 5364:          faq  => 282,
 5365:          bug  => 'Instructor Interface',
 5366:          help => $helpitem,}
 5367:         );
 5368:     my $args = { bread_crumbs           => $brcrum,
 5369:                  bread_crumbs_component => 'User Management'};
 5370:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 5371: 
 5372:     my $newrole;
 5373:     my ($rdummy,$roledef)=
 5374: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5375: 
 5376: # ------------------------------------------------------- Does this role exist?
 5377:     $r->print('<h3>');
 5378:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5379: 	$r->print(&mt('Existing Role').' "');
 5380:     } else {
 5381: 	$r->print(&mt('New Role').' "');
 5382: 	$roledef='';
 5383:         $newrole = 1;
 5384:     }
 5385:     $r->print($rolename.'"</h3>');
 5386: # ------------------------------------------------- Assign role and show result
 5387: 
 5388:     my $errmsg;
 5389:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 5390:     # Assign role and return result
 5391:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 5392:                                              $newprivs{'c'});
 5393:     if ($result ne 'ok') {
 5394:         $errmsg = ': '.$result;
 5395:     }
 5396:     my $message =
 5397:         &Apache::lonhtmlcommon::confirm_success(
 5398:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 5399:     if ($env{'request.course.id'}) {
 5400:         my $url='/'.$env{'request.course.id'};
 5401:         $url=~s/\_/\//g;
 5402:         $result =
 5403:             &Apache::lonnet::assigncustomrole(
 5404:                 $env{'user.domain'},$env{'user.name'},
 5405:                 $url,
 5406:                 $env{'user.domain'},$env{'user.name'},
 5407:                 $rolename,undef,undef,undef,$context);
 5408:         if ($result ne 'ok') {
 5409:             $errmsg = ': '.$result;
 5410:         }
 5411:         $message .=
 5412:             '<br />'
 5413:            .&Apache::lonhtmlcommon::confirm_success(
 5414:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 5415:     }
 5416:     $r->print(
 5417:         &Apache::loncommon::confirmwrapper($message)
 5418:        .'<br />'
 5419:        .&Apache::lonhtmlcommon::actionbox([
 5420:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 5421:            .&mt('Create or edit another custom role')
 5422:            .'</a>'])
 5423:        .'<form name="customresult" method="post" action="">'
 5424:        .&Apache::lonhtmlcommon::echo_form_input([])
 5425:        .'</form>'
 5426:     );
 5427: }
 5428: 
 5429: sub show_role_requests {
 5430:     my ($caller,$dom) = @_;
 5431:     my $showrolereqs;
 5432:     my %domconfig = &Apache::lonnet::get_dom('configuration',['privacy'],$dom);
 5433:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 5434:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 5435:             my %approvalconf = %{$domconfig{'privacy'}{'approval'}};
 5436:             foreach my $key ('instdom','extdom') {
 5437:                 if (ref($approvalconf{$key}) eq 'HASH') {
 5438:                     if (keys(%{$approvalconf{$key}})) {
 5439:                         foreach my $context ('domain','author','course','community') {
 5440:                             if ($approvalconf{$key}{$context} eq $caller) {
 5441:                                 $showrolereqs = 1;
 5442:                                 last if ($showrolereqs);
 5443:                             }
 5444:                         }
 5445:                     }
 5446:                 }
 5447:                 last if ($showrolereqs);
 5448:             }
 5449:         }
 5450:     }
 5451:     return $showrolereqs;
 5452: }
 5453: 
 5454: sub display_coauthor_managers {
 5455:     my ($permission) = @_;
 5456:     my $output;
 5457:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5458:         $output = '<form action="/adm/createuser" method="post" name="camanagers">'.
 5459:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5460:                   '<p>';
 5461:         my (@possmanagers,@custommanagers);
 5462:         my %userenv =
 5463:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5464:                                              $env{'user.name'},
 5465:                                              'authormanagers');
 5466:         my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5467:                                                      ['active','future'],['ca']);
 5468:         if (keys(%ca_roles)) {
 5469:             foreach my $entry (sort(keys(%ca_roles))) {
 5470:                 if ($entry =~ /^($match_username\:$match_domain):ca$/) {
 5471:                     my $user = $1;
 5472:                     unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5473:                         push(@possmanagers,$user);
 5474:                     }
 5475:                 }
 5476:             }
 5477:         }
 5478:         if ($userenv{'authormanagers'} eq '') {
 5479:             $output .= &mt('Currently author manages co-author roles');
 5480:         } else {
 5481:             if (keys(%ca_roles)) {
 5482:                 foreach my $user (split(/,/,$userenv{'authormanagers'})) {
 5483:                     if ($user =~ /^($match_username)\:($match_domain)$/) {
 5484:                         if (exists($ca_roles{$user.':ca'})) {
 5485:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5486:                                 push(@custommanagers,$user);
 5487:                             }
 5488:                         }
 5489:                     }
 5490:                 }
 5491:             }
 5492:             if (@custommanagers) {
 5493:                 $output .= &mt('Co-authors with active or future roles who currently manage co-author roles: [_1]',
 5494:                               '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @custommanagers));
 5495:             } else {
 5496:                 $output .= &mt('Currently author manages co-author roles');
 5497:             }
 5498:         }
 5499:         $output .= "</p>\n";
 5500:         if (@possmanagers) {
 5501:             $output .= '<p>'.&mt('Select manager(s)').': ';
 5502:             foreach my $user (@possmanagers) {
 5503:                  my $checked;
 5504:                  if (grep(/^\Q$user\E$/,@custommanagers)) {
 5505:                      $checked = ' checked="checked"';
 5506:                  }
 5507:                  $output .= '<span style="LC_nobreak"><label>'.
 5508:                             '<input type="checkbox" name="custommanagers" '.
 5509:                             'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
 5510:                             &Apache::loncommon::plainname(split(/:/,$user))." ($user)".'</label></span> '."\n";
 5511:             }
 5512:             $output .= '<input type="hidden" name="state" value="process" /></p>'."\n".
 5513:                        '<p><input type="submit" value="'.&mt('Save changes').'" /></p>'."\n";
 5514:         } else {
 5515:             $output .= '<p>'.&mt('No co-author roles assignable as manager').'</p>';
 5516:         }
 5517:         $output .= '</form>';
 5518:     } else {
 5519:         $output = '<span class="LC_warning">'.
 5520:                   &mt('You do not have permission to perform this action').
 5521:                   '</span>';
 5522:     }
 5523:     return $output;
 5524: }
 5525: 
 5526: sub update_coauthor_managers {
 5527:     my ($permission) = @_;
 5528:     my $output;
 5529:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5530:         my ($current,$newval,@possibles,@managers);
 5531:         my %userenv =
 5532:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5533:                                              $env{'user.name'},
 5534:                                              'authormanagers');
 5535:         $current = $userenv{'authormanagers'};
 5536:         @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 5537:         if (@possibles) {
 5538:             my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5539:                                                          ['active','future'],['ca']);
 5540:             if (keys(%ca_roles)) {
 5541:                 foreach my $user (@possibles) {
 5542:                     if ($user =~ /^($match_username):($match_domain)$/) {
 5543:                         if (exists($ca_roles{$user.':ca'})) {
 5544:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5545:                                 push(@managers,$user);
 5546:                             }
 5547:                         }
 5548:                     }
 5549:                 }
 5550:                 if (@managers) {
 5551:                     $newval = join(',',sort(@managers));
 5552:                 }
 5553:             }
 5554:         }
 5555:         if ($current eq $newval) {
 5556:             $output = &mt('No changes made to management of co-author roles');
 5557:         } else {
 5558:             my $chgresult =
 5559:                 &Apache::lonnet::put('environment',{'authormanagers' => $newval},
 5560:                                      $env{'user.domain'},$env{'user.name'});
 5561:             if ($chgresult eq 'ok') {
 5562:                 &Apache::lonnet::appenv({'environment.authormanagers' => $newval});
 5563:                 my (@adds,@dels);
 5564:                 if ($newval eq '') {
 5565:                     @dels = split(/,/,$current);
 5566:                 } elsif ($current eq '') {
 5567:                     @adds = @managers;
 5568:                 } else {
 5569:                     my @old = split(/,/,$current);
 5570:                     my @diffs = &Apache::loncommon::compare_arrays(\@old,\@managers);
 5571:                     if (@diffs) {
 5572:                         foreach my $user (@diffs) {
 5573:                             if (grep(/^\Q$user\E$/,@old)) {
 5574:                                 push(@dels,$user);
 5575:                             } elsif (grep(/^\Q$user\E$/,@managers)) {
 5576:                                 push(@adds,$user);
 5577:                             }
 5578:                         }
 5579:                     }
 5580:                 }
 5581:                 my $key = "internal.manager./$env{'user.domain'}/$env{'user.name'}";
 5582:                 if (@dels) {
 5583:                     foreach my $user (@dels) {
 5584:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5585:                             &Apache::lonnet::del('environment',[$key],$2,$1);
 5586:                         }
 5587:                     }
 5588:                 }
 5589:                 if (@adds) {
 5590:                     foreach my $user (@adds) {
 5591:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5592:                             &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 5593:                         }
 5594:                     }
 5595:                 }
 5596:                 if ($newval eq '') {
 5597:                     $output = &mt('Management of co-authors set to be author-only');
 5598:                 } else {
 5599:                     $output .= &mt('Co-authors who can manage co-author roles set to: [_1]',
 5600:                                    '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @managers));
 5601:                 }
 5602:             }
 5603:         }
 5604:     } else {
 5605:         $output = '<span class="LC_warning">'.
 5606:                   &mt('You do not have permission to perform this action').
 5607:                   '</span>';
 5608:     }
 5609:     return $output;
 5610: }
 5611: 
 5612: # ================================================================ Main Handler
 5613: sub handler {
 5614:     my $r = shift;
 5615:     if ($r->header_only) {
 5616:        &Apache::loncommon::content_type($r,'text/html');
 5617:        $r->send_http_header;
 5618:        return OK;
 5619:     }
 5620:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 5621: 
 5622:     if ($env{'request.course.id'}) {
 5623:         $context = 'course';
 5624:         $crstype = &Apache::loncommon::course_type();
 5625:     } elsif ($env{'request.role'} =~ /^au\./) {
 5626:         $context = 'author';
 5627:     } elsif ($env{'request.role'} =~ m{^(ca|aa)\./$match_domain/$match_username$}) {
 5628:         $context = 'coauthor';
 5629:     } else {
 5630:         $context = 'domain';
 5631:     }
 5632: 
 5633:     my ($permission,$allowed) =
 5634:         &Apache::lonuserutils::get_permission($context,$crstype);
 5635:     if (($context eq 'coauthor') && ($allowed)) {
 5636:         $context = 'author';
 5637:     }
 5638: 
 5639:     if ($allowed) {
 5640:         my @allhelp;
 5641:         if ($context eq 'course') {
 5642:             $cid = $env{'request.course.id'};
 5643:             $cdom = $env{'course.'.$cid.'.domain'};
 5644:             $cnum = $env{'course.'.$cid.'.num'};
 5645: 
 5646:             if ($permission->{'cusr'}) {
 5647:                 push(@allhelp,'Course_Create_Class_List');
 5648:             }
 5649:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5650:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 5651:             }
 5652:             if ($permission->{'custom'}) {
 5653:                 push(@allhelp,'Course_Editing_Custom_Roles');
 5654:             }
 5655:             if ($permission->{'cusr'}) {
 5656:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 5657:             }
 5658:             unless ($permission->{'cusr_section'}) {
 5659:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 5660:                     push(@allhelp,'Course_Automated_Enrollment');
 5661:                 }
 5662:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 5663:                     push(@allhelp,'Course_Approve_Selfenroll');
 5664:                 }
 5665:             }
 5666:             if ($permission->{'grp_manage'}) {
 5667:                 push(@allhelp,'Course_Manage_Group');
 5668:             }
 5669:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5670:                 push(@allhelp,'Course_User_Logs');
 5671:             }
 5672:         } elsif ($context eq 'author') {
 5673:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5674:                            'Author_View_Coauthor_List','Author_User_Logs'));
 5675:         } elsif ($context eq 'coauthor') {
 5676:             if ($permission->{'cusr'}) {
 5677:                 push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5678:                                'Author_View_Coauthor_List','Author_User_Logs'));
 5679:             } elsif ($permission->{'view'}) {
 5680:                 push(@allhelp,'Author_View_Coauthor_List');
 5681:             }
 5682:         } else {
 5683:             if ($permission->{'cusr'}) {
 5684:                 push(@allhelp,'Domain_Change_Privileges');
 5685:                 if ($permission->{'activity'}) {
 5686:                     push(@allhelp,'Domain_User_Access_Logs');
 5687:                 }
 5688:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 5689:                 if ($permission->{'custom'}) {
 5690:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 5691:                 }
 5692:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 5693:             } elsif ($permission->{'view'}) {
 5694:                 push(@allhelp,'Domain_View_Privileges');
 5695:                 if ($permission->{'activity'}) {
 5696:                     push(@allhelp,'Domain_User_Access_Logs');
 5697:                 }
 5698:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 5699:             }
 5700:         }
 5701:         if (@allhelp) {
 5702:             $allhelpitems = join(',',@allhelp);
 5703:         }
 5704:     }
 5705: 
 5706:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5707:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 5708:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue',
 5709:          'forceedit']);
 5710:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5711:     my $args;
 5712:     my $brcrum = [];
 5713:     my $bread_crumbs_component = 'User Management';
 5714:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 5715:         $brcrum = [{href=>"/adm/createuser",
 5716:                     text=>"User Management",
 5717:                     help=>$allhelpitems}
 5718:                   ];
 5719:     }
 5720:     if (!$allowed) {
 5721:         if ($context eq 'course') {
 5722:             $r->internal_redirect('/adm/viewclasslist');
 5723:             return OK;
 5724:         } elsif ($context eq 'coauthor') {
 5725:             $r->internal_redirect('/adm/viewcoauthors');
 5726:             return OK;
 5727:         }
 5728:         $env{'user.error.msg'}=
 5729:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 5730:                                  "or view user status.";
 5731:         return HTTP_NOT_ACCEPTABLE;
 5732:     }
 5733: 
 5734:     &Apache::loncommon::content_type($r,'text/html');
 5735:     $r->send_http_header;
 5736: 
 5737:     my $showcredits;
 5738:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 5739:          ($context eq 'domain')) {
 5740:         my %domdefaults = 
 5741:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 5742:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 5743:             $showcredits = 1;
 5744:         }
 5745:     }
 5746: 
 5747:     # Main switch on form.action and form.state, as appropriate
 5748:     if (! exists($env{'form.action'})) {
 5749:         $args = {bread_crumbs => $brcrum,
 5750:                  bread_crumbs_component => $bread_crumbs_component}; 
 5751:         $r->print(&header(undef,$args));
 5752:         $r->print(&print_main_menu($permission,$context,$crstype));
 5753:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 5754:         my $helpitem = 'Course_Create_Class_List';
 5755:         if ($context eq 'author') {
 5756:             $helpitem = 'Author_Create_Coauthor_List';
 5757:         } elsif ($context eq 'domain') {
 5758:             $helpitem = 'Domain_Create_Users';
 5759:         }
 5760:         push(@{$brcrum},
 5761:               { href => '/adm/createuser?action=upload&state=',
 5762:                 text => 'Upload Users List',
 5763:                 help => $helpitem,
 5764:               });
 5765:         $bread_crumbs_component = 'Upload Users List';
 5766:         $args = {bread_crumbs           => $brcrum,
 5767:                  bread_crumbs_component => $bread_crumbs_component};
 5768:         $r->print(&header(undef,$args));
 5769:         $r->print('<form name="studentform" method="post" '.
 5770:                   'enctype="multipart/form-data" '.
 5771:                   ' action="/adm/createuser">'."\n");
 5772:         if (! exists($env{'form.state'})) {
 5773:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5774:         } elsif ($env{'form.state'} eq 'got_file') {
 5775:             my $result = 
 5776:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 5777:                                                                  $permission,
 5778:                                                                  $crstype,$showcredits);
 5779:             if ($result eq 'missingdata') {
 5780:                 delete($env{'form.state'});
 5781:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5782:             }
 5783:         } elsif ($env{'form.state'} eq 'enrolling') {
 5784:             if ($env{'form.datatoken'}) {
 5785:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 5786:                                                                     $permission,
 5787:                                                                     $showcredits);
 5788:                 if ($result eq 'missingdata') {
 5789:                     delete($env{'form.state'});
 5790:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5791:                 } elsif ($result eq 'invalidhome') {
 5792:                     $env{'form.state'} = 'got_file';
 5793:                     delete($env{'form.lcserver'});
 5794:                     my $result =
 5795:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 5796:                                                                          $crstype,$showcredits);
 5797:                     if ($result eq 'missingdata') {
 5798:                         delete($env{'form.state'});
 5799:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5800:                     }
 5801:                 }
 5802:             } else {
 5803:                 delete($env{'form.state'});
 5804:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5805:             }
 5806:         } else {
 5807:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5808:         }
 5809:         $r->print('</form>');
 5810:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 5811:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 5812:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 5813:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 5814:         my $phase = $env{'form.phase'};
 5815:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 5816: 	&Apache::loncreateuser::restore_prev_selections();
 5817: 	my $srch;
 5818: 	foreach my $item (@search) {
 5819: 	    $srch->{$item} = $env{'form.'.$item};
 5820: 	}
 5821:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 5822:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 5823:             if ($env{'form.phase'} eq 'createnewuser') {
 5824:                 my $response;
 5825:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 5826:                     my $response =
 5827:                         '<span class="LC_warning">'
 5828:                        .&mt('You must specify a valid username. Only the following are allowed:'
 5829:                            .' letters numbers - . @')
 5830:                        .'</span>';
 5831:                     $env{'form.phase'} = '';
 5832:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 5833:                                                $crstype,$brcrum,$permission);
 5834:                 } else {
 5835:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 5836:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 5837:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 5838:                                                   $srch,$response,$context,
 5839:                                                   $permission,$crstype,$brcrum,
 5840:                                                   $showcredits);
 5841:                 }
 5842:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 5843:                 my ($currstate,$response,$forcenewuser,$results) = 
 5844:                     &user_search_result($context,$srch);
 5845:                 if ($env{'form.currstate'} eq 'modify') {
 5846:                     $currstate = $env{'form.currstate'};
 5847:                 }
 5848:                 if ($currstate eq 'select') {
 5849:                     &print_user_selection_page($r,$response,$srch,$results,
 5850:                                                \@search,$context,undef,$crstype,
 5851:                                                $brcrum);
 5852:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 5853:                     my ($ccuname,$ccdomain,$uhome);
 5854:                     if (($srch->{'srchby'} eq 'uname') && 
 5855:                         ($srch->{'srchtype'} eq 'exact')) {
 5856:                         $ccuname = $srch->{'srchterm'};
 5857:                         $ccdomain= $srch->{'srchdomain'};
 5858:                     } else {
 5859:                         my @matchedunames = keys(%{$results});
 5860:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 5861:                     }
 5862:                     $ccuname =&LONCAPA::clean_username($ccuname);
 5863:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 5864:                     if ($env{'form.action'} eq 'accesslogs') {
 5865:                         my $uhome;
 5866:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 5867:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 5868:                         }
 5869:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 5870:                             $env{'form.phase'} = '';
 5871:                             undef($forcenewuser);
 5872:                             #if ($response) {
 5873:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 5874:                             #        $response .= '<br /><br />';
 5875:                             #    }
 5876:                             #}
 5877:                             &print_username_entry_form($r,$context,$response,$srch,
 5878:                                                        $forcenewuser,$crstype,$brcrum,
 5879:                                                        $permission);
 5880:                         } else {
 5881:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5882:                         }
 5883:                     } else {
 5884:                         if ($env{'form.forcenewuser'}) {
 5885:                             $response = '';
 5886:                         }
 5887:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 5888:                                                       $srch,$response,$context,
 5889:                                                       $permission,$crstype,$brcrum);
 5890:                     }
 5891:                 } elsif ($currstate eq 'query') {
 5892:                     &print_user_query_page($r,'createuser',$brcrum);
 5893:                 } else {
 5894:                     $env{'form.phase'} = '';
 5895:                     &print_username_entry_form($r,$context,$response,$srch,
 5896:                                                $forcenewuser,$crstype,$brcrum,
 5897:                                                $permission);
 5898:                 }
 5899:             } elsif ($env{'form.phase'} eq 'userpicked') {
 5900:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 5901:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 5902:                 if ($env{'form.action'} eq 'accesslogs') {
 5903:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5904:                 } else {
 5905:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 5906:                                                   $context,$permission,$crstype,
 5907:                                                   $brcrum);
 5908:                 }
 5909:             } elsif ($env{'form.action'} eq 'accesslogs') {
 5910:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 5911:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 5912:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5913:             }
 5914:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 5915:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 5916:         } else {
 5917:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 5918:                                        $brcrum,$permission);
 5919:         }
 5920:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 5921:         my $prefix;
 5922:         if ($env{'form.phase'} eq 'set_custom_roles') {
 5923:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 5924:         } else {
 5925:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5926:         }
 5927:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 5928:              ($permission->{'cusr'}) && 
 5929:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5930:         push(@{$brcrum},
 5931:                  {href => '/adm/createuser?action=processauthorreq',
 5932:                   text => 'Authoring Space requests',
 5933:                   help => 'Domain_Role_Approvals'});
 5934:         $bread_crumbs_component = 'Authoring requests';
 5935:         if ($env{'form.state'} eq 'done') {
 5936:             push(@{$brcrum},
 5937:                      {href => '/adm/createuser?action=authorreqqueue',
 5938:                       text => 'Result',
 5939:                       help => 'Domain_Role_Approvals'});
 5940:             $bread_crumbs_component = 'Authoring request result';
 5941:         }
 5942:         $args = { bread_crumbs           => $brcrum,
 5943:                   bread_crumbs_component => $bread_crumbs_component};
 5944:         my $js = &usernamerequest_javascript();
 5945:         $r->print(&header(&add_script($js),$args));
 5946:         if (!exists($env{'form.state'})) {
 5947:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 5948:                                                                             $env{'request.role.domain'}));
 5949:         } elsif ($env{'form.state'} eq 'done') {
 5950:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 5951:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 5952:                                                                          $env{'request.role.domain'}));
 5953:         }
 5954:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 5955:              ($permission->{'cusr'}) &&
 5956:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5957:         push(@{$brcrum},
 5958:                  {href => '/adm/createuser?action=processusernamereq',
 5959:                   text => 'LON-CAPA account requests',
 5960:                   help => 'Domain_Username_Approvals'});
 5961:         $bread_crumbs_component = 'Account requests';
 5962:         if ($env{'form.state'} eq 'done') {
 5963:             push(@{$brcrum},
 5964:                      {href => '/adm/createuser?action=usernamereqqueue',
 5965:                       text => 'Result',
 5966:                       help => 'Domain_Username_Approvals'});
 5967:             $bread_crumbs_component = 'LON-CAPA account request result';
 5968:         }
 5969:         $args = { bread_crumbs           => $brcrum,
 5970:                   bread_crumbs_component => $bread_crumbs_component};
 5971:         my $js = &usernamerequest_javascript();
 5972:         $r->print(&header(&add_script($js),$args));
 5973:         if (!exists($env{'form.state'})) {
 5974:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 5975:                                                                             $env{'request.role.domain'}));
 5976:         } elsif ($env{'form.state'} eq 'done') {
 5977:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 5978:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 5979:                                                                          $env{'request.role.domain'}));
 5980:         }
 5981:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 5982:              ($permission->{'cusr'})) {
 5983:         my $dom = $env{'form.domain'};
 5984:         my $uname = $env{'form.username'};
 5985:         my $warning;
 5986:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 5987:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 5988:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 5989:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 5990:                     if ($uhome eq 'no_host') {
 5991:                         my $queue = $env{'form.queue'};
 5992:                         my $reqkey = &escape($uname).'_'.$queue; 
 5993:                         my $namespace = 'usernamequeue';
 5994:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 5995:                         my %queued =
 5996:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 5997:                         unless ($queued{$reqkey}) {
 5998:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 5999:                         }
 6000:                     } else {
 6001:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 6002:                     }
 6003:                 } else {
 6004:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 6005:                 }
 6006:             } else {
 6007:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 6008:             }
 6009:         } else {
 6010:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 6011:         }
 6012:         my $args = { only_body => 1 };
 6013:         $r->print(&header(undef,$args).
 6014:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 6015:         if ($warning ne '') {
 6016:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 6017:         } else {
 6018:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 6019:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 6020:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6021:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6022:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 6023:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 6024:                         my %info =
 6025:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 6026:                         if (ref($info{$uname}) eq 'HASH') {
 6027:                             my $usertype = $info{$uname}{'inststatus'};
 6028:                             unless ($usertype) {
 6029:                                 $usertype = 'default';
 6030:                             }
 6031:                             my ($showstatus,$showemail,$pickstart);
 6032:                             my $numextras = 0;
 6033:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6034:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 6035:                                 if (ref($usertypes) eq 'HASH') {
 6036:                                     if ($usertypes->{$usertype}) {
 6037:                                         $showstatus = $usertypes->{$usertype};
 6038:                                     } else {
 6039:                                         $showstatus = $othertitle;
 6040:                                     }
 6041:                                     if ($showstatus) {
 6042:                                         $numextras ++;
 6043:                                     }
 6044:                                 }
 6045:                             }
 6046:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 6047:                                 $showemail = $info{$uname}{'email'};
 6048:                                 $numextras ++;
 6049:                             }
 6050:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 6051:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 6052:                                     $pickstart = 1;
 6053:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6054:                                     my ($num,$count);
 6055:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 6056:                                     $count += $numextras;
 6057:                                     foreach my $field (@{$infofields}) {
 6058:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 6059:                                         next unless ($infotitles->{$field});
 6060:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 6061:                                                   $info{$uname}{$field});
 6062:                                         $num ++;
 6063:                                         unless ($count == $num) {
 6064:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 6065:                                         }
 6066:                                     }
 6067:                                 }
 6068:                             }
 6069:                             if ($numextras) {
 6070:                                 unless ($pickstart) {
 6071:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6072:                                     $pickstart = 1;
 6073:                                 }
 6074:                                 if ($showemail) {
 6075:                                     my $closure = '';
 6076:                                     unless ($showstatus) {
 6077:                                         $closure = 1;
 6078:                                     }
 6079:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 6080:                                               $showemail.
 6081:                                               &Apache::lonhtmlcommon::row_closure($closure));
 6082:                                 }
 6083:                                 if ($showstatus) {
 6084:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 6085:                                               $showstatus.
 6086:                                               &Apache::lonhtmlcommon::row_closure(1));
 6087:                                 }
 6088:                             }
 6089:                             if ($pickstart) { 
 6090:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 6091:                             } else {
 6092:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 6093:                             }
 6094:                         } else {
 6095:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 6096:                         }
 6097:                     }
 6098:                 }
 6099:             }
 6100:         }
 6101:         $r->print(&close_popup_form());
 6102:     } elsif (($env{'form.action'} eq 'listusers') && 
 6103:              ($permission->{'view'} || $permission->{'cusr'})) {
 6104:         my $helpitem = 'Course_View_Class_List';
 6105:         if ($context eq 'author') {
 6106:             $helpitem = 'Author_View_Coauthor_List';
 6107:         } elsif ($context eq 'domain') {
 6108:             $helpitem = 'Domain_View_Users_List';
 6109:         }
 6110:         if ($env{'form.phase'} eq 'bulkchange') {
 6111:             push(@{$brcrum},
 6112:                     {href => '/adm/createuser?action=listusers',
 6113:                      text => "List Users"},
 6114:                     {href => "/adm/createuser",
 6115:                      text => "Result",
 6116:                      help => $helpitem});
 6117:             $bread_crumbs_component = 'Update Users';
 6118:             $args = {bread_crumbs           => $brcrum,
 6119:                      bread_crumbs_component => $bread_crumbs_component};
 6120:             $r->print(&header(undef,$args));
 6121:             my $setting = $env{'form.roletype'};
 6122:             my $choice = $env{'form.bulkaction'};
 6123:             if ($permission->{'cusr'}) {
 6124:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 6125:             } else {
 6126:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 6127:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 6128:             }
 6129:         } else {
 6130:             push(@{$brcrum},
 6131:                     {href => '/adm/createuser?action=listusers',
 6132:                      text => "List Users",
 6133:                      help => $helpitem});
 6134:             $bread_crumbs_component = 'List Users';
 6135:             $args = {bread_crumbs           => $brcrum,
 6136:                      bread_crumbs_component => $bread_crumbs_component};
 6137:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 6138:             my $formname = 'studentform';
 6139:             my $hidecall = "hide_searching();";
 6140:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 6141:                 ($env{'form.roletype'} eq 'community'))) {
 6142:                 if ($env{'form.roletype'} eq 'course') {
 6143:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 6144:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 6145:                                                                 $formname);
 6146:                 } elsif ($env{'form.roletype'} eq 'community') {
 6147:                     $cb_jscript = 
 6148:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 6149:                     my %elements = (
 6150:                                       coursepick => 'radio',
 6151:                                       coursetotal => 'text',
 6152:                                       courselist => 'text',
 6153:                                    );
 6154:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 6155:                 }
 6156:                 $jscript .= &verify_user_display($context)."\n".
 6157:                             &Apache::loncommon::check_uncheck_jscript();
 6158:                 my $js = &add_script($jscript).$cb_jscript;
 6159:                 my $loadcode = 
 6160:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 6161:                 if ($loadcode ne '') {
 6162:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 6163:                 } else {
 6164:                     $args->{add_entries} = {onload => $hidecall};
 6165:                 }
 6166:                 $r->print(&header($js,$args));
 6167:             } else {
 6168:                 $args->{add_entries} = {onload => $hidecall};
 6169:                 $jscript = &verify_user_display($context).
 6170:                            &Apache::loncommon::check_uncheck_jscript(); 
 6171:                 $r->print(&header(&add_script($jscript),$args));
 6172:             }
 6173:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 6174:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 6175:                          $showcredits);
 6176:         }
 6177:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 6178:         my $brtext;
 6179:         if ($crstype eq 'Community') {
 6180:             $brtext = 'Drop Members';
 6181:         } else {
 6182:             $brtext = 'Drop Students';
 6183:         }
 6184:         push(@{$brcrum},
 6185:                 {href => '/adm/createuser?action=drop',
 6186:                  text => $brtext,
 6187:                  help => 'Course_Drop_Student'});
 6188:         if ($env{'form.state'} eq 'done') {
 6189:             push(@{$brcrum},
 6190:                      {href=>'/adm/createuser?action=drop',
 6191:                       text=>"Result"});
 6192:         }
 6193:         $bread_crumbs_component = $brtext;
 6194:         $args = {bread_crumbs           => $brcrum,
 6195:                  bread_crumbs_component => $bread_crumbs_component}; 
 6196:         $r->print(&header(undef,$args));
 6197:         if (!exists($env{'form.state'})) {
 6198:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 6199:         } elsif ($env{'form.state'} eq 'done') {
 6200:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 6201:                                                     $env{'form.action'});
 6202:         }
 6203:     } elsif ($env{'form.action'} eq 'dateselect') {
 6204:         if ($permission->{'cusr'}) {
 6205:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6206:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 6207:                                                                    $crstype,$showcredits));
 6208:         } else {
 6209:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6210:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 6211:         }
 6212:     } elsif ($env{'form.action'} eq 'selfenroll') {
 6213:         my %currsettings;
 6214:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 6215:             %currsettings = (
 6216:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 6217:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 6218:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 6219:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 6220:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 6221:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 6222:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 6223:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 6224:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 6225:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 6226:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 6227:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 6228:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 6229:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 6230:             );
 6231:         }
 6232:         if ($permission->{selfenrolladmin}) {
 6233:             push(@{$brcrum},
 6234:                     {href => '/adm/createuser?action=selfenroll',
 6235:                      text => "Configure Self-enrollment",
 6236:                      help => 'Course_Self_Enrollment'});
 6237:             if (!exists($env{'form.state'})) {
 6238:                 $args = { bread_crumbs           => $brcrum,
 6239:                           bread_crumbs_component => 'Configure Self-enrollment'};
 6240:                 $r->print(&header(undef,$args));
 6241:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6242:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 6243:             } elsif ($env{'form.state'} eq 'done') {
 6244:                 push (@{$brcrum},
 6245:                           {href=>'/adm/createuser?action=selfenroll',
 6246:                            text=>"Result"});
 6247:                 $args = { bread_crumbs           => $brcrum,
 6248:                           bread_crumbs_component => 'Self-enrollment result'};
 6249:                 $r->print(&header(undef,$args));
 6250:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6251:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 6252:             }
 6253:         } elsif ($permission->{selfenrollview}) {
 6254:             push(@{$brcrum},
 6255:                     {href => '/adm/createuser?action=selfenroll',
 6256:                      text => "View Self-enrollment configuration",
 6257:                      help => 'Course_Self_Enrollment'});
 6258:             $args = { bread_crumbs           => $brcrum,
 6259:                       bread_crumbs_component => 'Self-enrollment Settings'};
 6260:             $r->print(&header(undef,$args));
 6261:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6262:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 6263:         } else {
 6264:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6265:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 6266:         }
 6267:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 6268:         if ($permission->{selfenrolladmin}) {
 6269:             push(@{$brcrum},
 6270:                      {href => '/adm/createuser?action=selfenrollqueue',
 6271:                       text => 'Enrollment requests',
 6272:                       help => 'Course_Approve_Selfenroll'});
 6273:             $bread_crumbs_component = 'Enrollment requests';
 6274:             if ($env{'form.state'} eq 'done') {
 6275:                 push(@{$brcrum},
 6276:                          {href => '/adm/createuser?action=selfenrollqueue',
 6277:                           text => 'Result',
 6278:                           help => 'Course_Approve_Selfenroll'});
 6279:                 $bread_crumbs_component = 'Enrollment result';
 6280:             }
 6281:             $args = { bread_crumbs           => $brcrum,
 6282:                       bread_crumbs_component => $bread_crumbs_component};
 6283:             $r->print(&header(undef,$args));
 6284:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6285:             if (!exists($env{'form.state'})) {
 6286:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 6287:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 6288:                                                                                 $cdom,$cnum));
 6289:             } elsif ($env{'form.state'} eq 'done') {
 6290:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 6291:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 6292:                               $cdom,$cnum,$coursedesc));
 6293:             }
 6294:         } else {
 6295:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6296:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 6297:         }
 6298:     } elsif ($env{'form.action'} eq 'changelogs') {
 6299:         if ($permission->{cusr} || $permission->{view}) {
 6300:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 6301:         } else {
 6302:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6303:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 6304:         }
 6305:     } elsif ($env{'form.action'} eq 'helpdesk') {
 6306:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6307:             ($permission->{'cusr'} || $permission->{'view'})) {
 6308:             if ($env{'form.state'} eq 'process') {
 6309:                 if ($permission->{'owner'}) {
 6310:                     &update_helpdeskaccess($r,$permission,$brcrum);
 6311:                 } else {
 6312:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 6313:                 }
 6314:             } else {
 6315:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 6316:             }
 6317:         } else {
 6318:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6319:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 6320:         }
 6321:     } elsif ($env{'form.action'} eq 'rolerequests') {
 6322:         if ($permission->{cusr} || $permission->{view}) {
 6323:             &print_queued_roles($r,$context,$permission,$brcrum);
 6324:         }
 6325:     } elsif ($env{'form.action'} eq 'queuedroles') {
 6326:         if (($permission->{cusr}) && ($context eq 'domain')) {
 6327:             if (&show_role_requests($context,$env{'request.role.domain'})) {
 6328:                 if ($env{'form.state'} eq 'done') {
 6329:                     &process_pendingroles($r,$context,$permission,$brcrum);
 6330:                 } else {
 6331:                     &print_pendingroles($r,$context,$permission,$brcrum);
 6332:                 }
 6333:             } else {
 6334:                 $r->print(&header(undef,{'no_nav_bar' => 1}).
 6335:                           '<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>');
 6336:             }
 6337:         } else {
 6338:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6339:                      '<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>');
 6340:         }
 6341:     } elsif ($env{'form.action'} eq 'camanagers') {
 6342:         if (($permission->{cusr}) && ($context eq 'author')) {
 6343:             push(@{$brcrum},
 6344:                      {href => '/adm/createuser?action=camanagers',
 6345:                       text => 'Co-authors who manage',
 6346:                       help => 'Author_Manage_Coauthors'});
 6347:             if ($env{'form.state'} eq 'process') {
 6348:                 push(@{$brcrum},
 6349:                          {href => '/adm/createuser?action=camanagers',
 6350:                           text => 'Result',
 6351:                           help => 'Author_Manage_Coauthors'});
 6352:             }
 6353:             $args = { bread_crumbs           => $brcrum };
 6354:             $r->print(&header(undef,$args));
 6355:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6356:             if (!exists($env{'form.state'})) {
 6357:                 $r->print('<h3>'.&mt('Co-author Management').'</h3>'."\n".
 6358:                           &display_coauthor_managers($permission));
 6359:             } elsif ($env{'form.state'} eq 'process') {
 6360:                 $r->print('<h3>'.&mt('Co-author Management Update Result').'</h3>'."\n".
 6361:                           &update_coauthor_managers($permission));
 6362:             }
 6363:         }
 6364:     } elsif (($env{'form.action'} eq 'calist') && ($context eq 'author')) {
 6365:         if ($permission->{'cusr'}) {
 6366:             my ($role,$audom,$auname,$canview,$canedit) =
 6367:                 &Apache::lonviewcoauthors::get_allowable();
 6368:             if (($canedit) && ($env{'form.forceedit'})) {
 6369:                 &Apache::lonviewcoauthors::get_editor_crumbs($brcrum,'/adm/createuser');
 6370:                 my $args = { 'bread_crumbs' => $brcrum };
 6371:                 $r->print(&Apache::loncommon::start_page('Configure co-author listing',undef,
 6372:                                                          $args).
 6373:                           &Apache::lonviewcoauthors::edit_settings($audom,$auname,$role,
 6374:                                                                    '/adm/createuser'));
 6375:             } else {
 6376:                 push(@{$brcrum},
 6377:                        {href => '/adm/createuser?action=calist',
 6378:                         text => 'Coauthor-viewable list',
 6379:                         help => 'Author_List_Coauthors'});
 6380:                 my $args = { 'bread_crumbs' => $brcrum };
 6381:                 $r->print(&Apache::loncommon::start_page('Coauthor-viewable list',undef,
 6382:                                                          $args));
 6383:                 my %viewsettings =
 6384:                     &Apache::lonviewcoauthors::retrieve_view_settings($auname,$audom,$role);
 6385:                 if ($viewsettings{'show'} eq 'none') {
 6386:                     $r->print('<h3>'.&mt('Coauthor-viewable listing').'</h3>'.
 6387:                               '<p class="LC_info">'.
 6388:                               &mt('Listing of co-authors not enabled for this Authoring Space').
 6389:                               '</p>');
 6390:                 } else {
 6391:                     &Apache::lonviewcoauthors::print_coauthors($r,$auname,$audom,$role,
 6392:                                                                '/adm/createuser',\%viewsettings);
 6393:                 }
 6394:             }
 6395:         } else {
 6396:             $r->internal_redirect('/adm/viewcoauthors');
 6397:             return OK;
 6398:         }
 6399:     } else {
 6400:         $bread_crumbs_component = 'User Management';
 6401:         $args = { bread_crumbs           => $brcrum,
 6402:                   bread_crumbs_component => $bread_crumbs_component};
 6403:         $r->print(&header(undef,$args));
 6404:         $r->print(&print_main_menu($permission,$context,$crstype));
 6405:     }
 6406:     $r->print(&Apache::loncommon::end_page());
 6407:     return OK;
 6408: }
 6409: 
 6410: sub header {
 6411:     my ($jscript,$args) = @_;
 6412:     my $start_page;
 6413:     if (ref($args) eq 'HASH') {
 6414:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 6415:     } else {
 6416:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 6417:     }
 6418:     return $start_page;
 6419: }
 6420: 
 6421: sub add_script {
 6422:     my ($js) = @_;
 6423:     return '<script type="text/javascript">'."\n"
 6424:           .'// <![CDATA['."\n"
 6425:           .$js."\n"
 6426:           .'// ]]>'."\n"
 6427:           .'</script>'."\n";
 6428: }
 6429: 
 6430: sub usernamerequest_javascript {
 6431:     my $js = <<ENDJS;
 6432: 
 6433: function openusernamereqdisplay(dom,uname,queue) {
 6434:     var url = '/adm/createuser?action=displayuserreq';
 6435:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 6436:     var title = 'Account_Request_Browser';
 6437:     var options = 'scrollbars=1,resizable=1,menubar=0';
 6438:     options += ',width=700,height=600';
 6439:     var stdeditbrowser = open(url,title,options,'1');
 6440:     stdeditbrowser.focus();
 6441:     return;
 6442: }
 6443:  
 6444: ENDJS
 6445: }
 6446: 
 6447: sub close_popup_form {
 6448:     my $close= &mt('Close Window');
 6449:     return << "END";
 6450: <p><form name="displayreq" action="" method="post">
 6451: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 6452: </form></p>
 6453: END
 6454: }
 6455: 
 6456: sub verify_user_display {
 6457:     my ($context) = @_;
 6458:     my %lt = &Apache::lonlocal::texthash (
 6459:         course    => 'course(s): description, section(s), status',
 6460:         community => 'community(s): description, section(s), status',
 6461:         author    => 'author',
 6462:     );
 6463:     my $photos;
 6464:     if (($context eq 'course') && $env{'request.course.id'}) {
 6465:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 6466:     }
 6467:     my $output = <<"END";
 6468: 
 6469: function hide_searching() {
 6470:     if (document.getElementById('searching')) {
 6471:         document.getElementById('searching').style.display = 'none';
 6472:     }
 6473:     return;
 6474: }
 6475: 
 6476: function display_update() {
 6477:     document.studentform.action.value = 'listusers';
 6478:     document.studentform.phase.value = 'display';
 6479:     document.studentform.submit();
 6480: }
 6481: 
 6482: function updateCols(caller) {
 6483:     var context = '$context';
 6484:     var photos = '$photos';
 6485:     if (caller == 'Status') {
 6486:         if ((context == 'domain') && 
 6487:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6488:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 6489:             document.getElementById('showcolstatus').checked = false;
 6490:             document.getElementById('showcolstatus').disabled = 'disabled';
 6491:             document.getElementById('showcolstart').checked = false;
 6492:             document.getElementById('showcolend').checked = false;
 6493:         } else {
 6494:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6495:                 document.getElementById('showcolstatus').checked = true;
 6496:                 document.getElementById('showcolstatus').disabled = '';
 6497:                 document.getElementById('showcolstart').checked = true;
 6498:                 document.getElementById('showcolend').checked = true;
 6499:             } else {
 6500:                 document.getElementById('showcolstatus').checked = false;
 6501:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6502:                 document.getElementById('showcolstart').checked = false;
 6503:                 document.getElementById('showcolend').checked = false;
 6504:             }
 6505:         }
 6506:     }
 6507:     if (caller == 'output') {
 6508:         if (photos == 1) {
 6509:             if (document.getElementById('showcolphoto')) {
 6510:                 var photoitem = document.getElementById('showcolphoto');
 6511:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 6512:                     photoitem.checked = true;
 6513:                     photoitem.disabled = '';
 6514:                 } else {
 6515:                     photoitem.checked = false;
 6516:                     photoitem.disabled = 'disabled';
 6517:                 }
 6518:             }
 6519:         }
 6520:     }
 6521:     if (caller == 'showrole') {
 6522:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 6523:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 6524:             document.getElementById('showcolrole').checked = true;
 6525:             document.getElementById('showcolrole').disabled = '';
 6526:         } else {
 6527:             document.getElementById('showcolrole').checked = false;
 6528:             document.getElementById('showcolrole').disabled = 'disabled';
 6529:         }
 6530:         if (context == 'domain') {
 6531:             var quotausageshow = 0;
 6532:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6533:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 6534:                 document.getElementById('showcolstatus').checked = false;
 6535:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6536:                 document.getElementById('showcolstart').checked = false;
 6537:                 document.getElementById('showcolend').checked = false;
 6538:             } else {
 6539:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6540:                     document.getElementById('showcolstatus').checked = true;
 6541:                     document.getElementById('showcolstatus').disabled = '';
 6542:                     document.getElementById('showcolstart').checked = true;
 6543:                     document.getElementById('showcolend').checked = true;
 6544:                 }
 6545:             }
 6546:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 6547:                 document.getElementById('showcolextent').disabled = 'disabled';
 6548:                 document.getElementById('showcolextent').checked = 'false';
 6549:                 document.getElementById('showextent').style.display='none';
 6550:                 document.getElementById('showcoltextextent').innerHTML = '';
 6551:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 6552:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 6553:                     if (document.getElementById('showcolauthorusage')) {
 6554:                         document.getElementById('showcolauthorusage').disabled = '';
 6555:                     }
 6556:                     if (document.getElementById('showcolauthorquota')) {
 6557:                         document.getElementById('showcolauthorquota').disabled = '';
 6558:                     }
 6559:                     quotausageshow = 1;
 6560:                 }
 6561:             } else {
 6562:                 document.getElementById('showextent').style.display='block';
 6563:                 document.getElementById('showextent').style.textAlign='left';
 6564:                 document.getElementById('showextent').style.textFace='normal';
 6565:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 6566:                     document.getElementById('showcolextent').disabled = '';
 6567:                     document.getElementById('showcolextent').checked = 'true';
 6568:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 6569:                 } else {
 6570:                     document.getElementById('showcolextent').disabled = '';
 6571:                     document.getElementById('showcolextent').checked = 'true';
 6572:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 6573:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 6574:                     } else {
 6575:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 6576:                     }
 6577:                 }
 6578:             }
 6579:             if (quotausageshow == 0)  {
 6580:                 if (document.getElementById('showcolauthorusage')) {
 6581:                     document.getElementById('showcolauthorusage').checked = false;
 6582:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 6583:                 }
 6584:                 if (document.getElementById('showcolauthorquota')) {
 6585:                     document.getElementById('showcolauthorquota').checked = false;
 6586:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 6587:                 }
 6588:             }
 6589:         }
 6590:     }
 6591:     return;
 6592: }
 6593: 
 6594: END
 6595:     return $output;
 6596: 
 6597: }
 6598: 
 6599: ###############################################################
 6600: ###############################################################
 6601: #  Menu Phase One
 6602: sub print_main_menu {
 6603:     my ($permission,$context,$crstype) = @_;
 6604:     my $linkcontext = $context;
 6605:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 6606:     if (($context eq 'course') && ($crstype eq 'Community')) {
 6607:         $linkcontext = lc($crstype);
 6608:         $stuterm = 'Members';
 6609:     }
 6610:     my %links = (
 6611:                 domain => {
 6612:                             upload     => 'Upload a File of Users',
 6613:                             singleuser => 'Add/Modify a User',
 6614:                             listusers  => 'Manage Users',
 6615:                             },
 6616:                 author => {
 6617:                             upload     => 'Upload a File of Co-authors',
 6618:                             singleuser => 'Add/Modify a Co-author',
 6619:                             listusers  => 'Manage Co-authors',
 6620:                             },
 6621:                 course => {
 6622:                             upload     => 'Upload a File of Course Users',
 6623:                             singleuser => 'Add/Modify a Course User',
 6624:                             listusers  => 'List and Modify Multiple Course Users',
 6625:                             },
 6626:                 community => {
 6627:                             upload     => 'Upload a File of Community Users',
 6628:                             singleuser => 'Add/Modify a Community User',
 6629:                             listusers  => 'List and Modify Multiple Community Users',
 6630:                            },
 6631:                 );
 6632:      my %linktitles = (
 6633:                 domain => {
 6634:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 6635:                             listusers  => 'Show and manage users in this domain.',
 6636:                             },
 6637:                 author => {
 6638:                             singleuser => 'Add a user with a co- or assistant author role.',
 6639:                             listusers  => 'Show and manage co- or assistant authors.',
 6640:                             },
 6641:                 course => {
 6642:                             singleuser => 'Add a user with a certain role to this course.',
 6643:                             listusers  => 'Show and manage users in this course.',
 6644:                             },
 6645:                 community => {
 6646:                             singleuser => 'Add a user with a certain role to this community.',
 6647:                             listusers  => 'Show and manage users in this community.',
 6648:                            },
 6649:                 );
 6650: 
 6651:   if ($linkcontext eq 'domain') {
 6652:       unless ($permission->{'cusr'}) {
 6653:           $links{'domain'}{'singleuser'} = 'View a User';
 6654:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 6655:       }
 6656:   } elsif ($linkcontext eq 'course') {
 6657:       unless ($permission->{'cusr'}) {
 6658:           $links{'course'}{'singleuser'} = 'View a Course User';
 6659:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 6660:           $links{'course'}{'listusers'} = 'List Course Users';
 6661:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 6662:       }
 6663:   } elsif ($linkcontext eq 'community') {
 6664:       unless ($permission->{'cusr'}) {
 6665:           $links{'community'}{'singleuser'} = 'View a Community User';
 6666:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 6667:           $links{'community'}{'listusers'} = 'List Community Users';
 6668:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 6669:       }
 6670:   }
 6671:   my @menu = ( {categorytitle => 'Single Users', 
 6672:          items =>
 6673:          [
 6674:             {
 6675:              linktext => $links{$linkcontext}{'singleuser'},
 6676:              icon => 'edit-redo.png',
 6677:              #help => 'Course_Change_Privileges',
 6678:              url => '/adm/createuser?action=singleuser',
 6679:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6680:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 6681:             },
 6682:          ]},
 6683: 
 6684:          {categorytitle => 'Multiple Users',
 6685:          items => 
 6686:          [
 6687:             {
 6688:              linktext => $links{$linkcontext}{'upload'},
 6689:              icon => 'uplusr.png',
 6690:              #help => 'Course_Create_Class_List',
 6691:              url => '/adm/createuser?action=upload',
 6692:              permission => $permission->{'cusr'},
 6693:              linktitle => 'Upload a CSV or a text file containing users.',
 6694:             },
 6695:             {
 6696:              linktext => $links{$linkcontext}{'listusers'},
 6697:              icon => 'mngcu.png',
 6698:              #help => 'Course_View_Class_List',
 6699:              url => '/adm/createuser?action=listusers',
 6700:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6701:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 6702:             },
 6703: 
 6704:          ]},
 6705: 
 6706:          {categorytitle => 'Administration',
 6707:          items => [ ]},
 6708:        );
 6709: 
 6710:     if ($context eq 'domain'){
 6711:         push(@{  $menu[0]->{items} }, # Single Users
 6712:             {
 6713:              linktext => 'User Access Log',
 6714:              icon => 'document-properties.png',
 6715:              #help => 'Domain_User_Access_Logs',
 6716:              url => '/adm/createuser?action=accesslogs',
 6717:              permission => $permission->{'activity'},
 6718:              linktitle => 'View user access log.',
 6719:             }
 6720:         );
 6721:         
 6722:         push(@{ $menu[2]->{items} }, #Category: Administration
 6723:             {
 6724:              linktext => 'Custom Roles',
 6725:              icon => 'emblem-photos.png',
 6726:              #help => 'Course_Editing_Custom_Roles',
 6727:              url => '/adm/createuser?action=custom',
 6728:              permission => $permission->{'custom'},
 6729:              linktitle => 'Configure a custom role.',
 6730:             },
 6731:             {
 6732:              linktext => 'Authoring Space Requests',
 6733:              icon => 'selfenrl-queue.png',
 6734:              #help => 'Domain_Role_Approvals',
 6735:              url => '/adm/createuser?action=processauthorreq',
 6736:              permission => $permission->{'cusr'},
 6737:              linktitle => 'Approve or reject author role requests',
 6738:             },
 6739:             {
 6740:              linktext => 'LON-CAPA Account Requests',
 6741:              icon => 'list-add.png',
 6742:              #help => 'Domain_Username_Approvals',
 6743:              url => '/adm/createuser?action=processusernamereq',
 6744:              permission => $permission->{'cusr'},
 6745:              linktitle => 'Approve or reject LON-CAPA account requests',
 6746:             },
 6747:             {
 6748:              linktext => 'Change Log',
 6749:              icon => 'document-properties.png',
 6750:              #help => 'Course_User_Logs',
 6751:              url => '/adm/createuser?action=changelogs',
 6752:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 6753:              linktitle => 'View change log.',
 6754:             },
 6755:         );
 6756:         
 6757:     }elsif ($context eq 'course'){
 6758:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 6759: 
 6760:         my %linktext = (
 6761:                          'Course'    => {
 6762:                                           single => 'Add/Modify a Student', 
 6763:                                           drop   => 'Drop Students',
 6764:                                           groups => 'Course Groups',
 6765:                                         },
 6766:                          'Community' => {
 6767:                                           single => 'Add/Modify a Member', 
 6768:                                           drop   => 'Drop Members',
 6769:                                           groups => 'Community Groups',
 6770:                                         },
 6771:                        );
 6772:         $linktext{'Placement'} = $linktext{'Course'};
 6773: 
 6774:         my %linktitle = (
 6775:             'Course' => {
 6776:                   single => 'Add a user with the role of student to this course',
 6777:                   drop   => 'Remove a student from this course.',
 6778:                   groups => 'Manage course groups',
 6779:                         },
 6780:             'Community' => {
 6781:                   single => 'Add a user with the role of member to this community',
 6782:                   drop   => 'Remove a member from this community.',
 6783:                   groups => 'Manage community groups',
 6784:                            },
 6785:         );
 6786: 
 6787:         $linktitle{'Placement'} = $linktitle{'Course'};
 6788: 
 6789:         push(@{ $menu[0]->{items} }, #Category: Single Users
 6790:             {   
 6791:              linktext => $linktext{$crstype}{'single'},
 6792:              #help => 'Course_Add_Student',
 6793:              icon => 'list-add.png',
 6794:              url => '/adm/createuser?action=singlestudent',
 6795:              permission => $permission->{'cusr'},
 6796:              linktitle => $linktitle{$crstype}{'single'},
 6797:             },
 6798:         );
 6799:         
 6800:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 6801:             {
 6802:              linktext => $linktext{$crstype}{'drop'},
 6803:              icon => 'edit-undo.png',
 6804:              #help => 'Course_Drop_Student',
 6805:              url => '/adm/createuser?action=drop',
 6806:              permission => $permission->{'cusr'},
 6807:              linktitle => $linktitle{$crstype}{'drop'},
 6808:             },
 6809:         );
 6810:         push(@{ $menu[2]->{items} }, #Category: Administration
 6811:             {
 6812:              linktext => 'Helpdesk Access',
 6813:              icon => 'helpdesk-access.png',
 6814:              #help => 'Course_Helpdesk_Access',
 6815:              url => '/adm/createuser?action=helpdesk',
 6816:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6817:                             ($permission->{'view'} || $permission->{'cusr'})),
 6818:              linktitle => 'Helpdesk access options',
 6819:             },
 6820:             {
 6821:              linktext => 'Custom Roles',
 6822:              icon => 'emblem-photos.png',
 6823:              #help => 'Course_Editing_Custom_Roles',
 6824:              url => '/adm/createuser?action=custom',
 6825:              permission => $permission->{'custom'},
 6826:              linktitle => 'Configure a custom role.',
 6827:             },
 6828:             {
 6829:              linktext => $linktext{$crstype}{'groups'},
 6830:              icon => 'grps.png',
 6831:              #help => 'Course_Manage_Group',
 6832:              url => '/adm/coursegroups?refpage=cusr',
 6833:              permission => $permission->{'grp_manage'},
 6834:              linktitle => $linktitle{$crstype}{'groups'},
 6835:             },
 6836:             {
 6837:              linktext => 'Change Log',
 6838:              icon => 'document-properties.png',
 6839:              #help => 'Course_User_Logs',
 6840:              url => '/adm/createuser?action=changelogs',
 6841:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6842:              linktitle => 'View change log.',
 6843:             },
 6844:         );
 6845:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 6846:             push(@{ $menu[2]->{items} },
 6847:                     {
 6848:                      linktext => 'Enrollment Requests',
 6849:                      icon => 'selfenrl-queue.png',
 6850:                      #help => 'Course_Approve_Selfenroll',
 6851:                      url => '/adm/createuser?action=selfenrollqueue',
 6852:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6853:                      linktitle =>'Approve or reject enrollment requests.',
 6854:                     },
 6855:             );
 6856:         }
 6857:         
 6858:         if (!exists($permission->{'cusr_section'})){
 6859:             if ($crstype ne 'Community') {
 6860:                 push(@{ $menu[2]->{items} },
 6861:                     {
 6862:                      linktext => 'Automated Enrollment',
 6863:                      icon => 'roles.png',
 6864:                      #help => 'Course_Automated_Enrollment',
 6865:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 6866:                                          && (($permission->{'cusr'}) ||
 6867:                                              ($permission->{'view'}))),
 6868:                      url  => '/adm/populate',
 6869:                      linktitle => 'Automated enrollment manager.',
 6870:                     }
 6871:                 );
 6872:             }
 6873:             push(@{ $menu[2]->{items} }, 
 6874:                 {
 6875:                  linktext => 'User Self-Enrollment',
 6876:                  icon => 'self_enroll.png',
 6877:                  #help => 'Course_Self_Enrollment',
 6878:                  url => '/adm/createuser?action=selfenroll',
 6879:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6880:                  linktitle => 'Configure user self-enrollment.',
 6881:                 },
 6882:             );
 6883:         }
 6884:     } elsif ($context eq 'author') {
 6885:         push(@{ $menu[2]->{items} }, #Category: Administration
 6886:             {
 6887:              linktext => 'Change Log',
 6888:              icon => 'document-properties.png',
 6889:              #help => 'Course_User_Logs',
 6890:              url => '/adm/createuser?action=changelogs',
 6891:              permission => $permission->{'cusr'},
 6892:              linktitle => 'View change log.',
 6893:             },
 6894:             {
 6895:              linktext => 'Co-authors who can add/revoke co-author roles',
 6896:              icon => 'helpdesk-access.png',
 6897:              #help => 'Coauthor_Management',
 6898:              url => '/adm/createuser?action=camanagers',
 6899:              permission => $permission->{'author'},
 6900:              linktitle => 'Assign/Revoke right to manage co-author roles',
 6901:             },
 6902:             {
 6903:              linktext => 'Configure coauthor-viewable listing',
 6904:              icon => 'helpdesk-access.png',
 6905:              #help => 'Coauthor_Settings',
 6906:              url => '/adm/createuser?action=calist&forceedit=1',
 6907:              permission => ($permission->{'cusr'}),
 6908:              linktitle => 'Set availability of coauthor-viewable user listing',
 6909:             },
 6910:         );
 6911:     }
 6912:     push(@{ $menu[2]->{items} },
 6913:         {
 6914:          linktext => 'Role Requests (other domains)',
 6915:          icon => 'edit-find.png',
 6916:          #help => 'Role_Requests',
 6917:          url => '/adm/createuser?action=rolerequests',
 6918:          permission => $permission->{'cusr'},
 6919:          linktitle => 'Role requests for users in other domains',
 6920:         },
 6921:     );
 6922:     if (&show_role_requests($context,$env{'request.role.domain'})) {
 6923:         push(@{ $menu[2]->{items} },
 6924:             {
 6925:              linktext => 'Queued Role Assignments (this domain)',
 6926:              icon => 'edit-find.png',
 6927:              #help => 'Role_Approvals',
 6928:              url => '/adm/createuser?action=queuedroles',
 6929:              permission => $permission->{'cusr'},
 6930:              linktitle => "Role requests for this domain's users",
 6931:             },
 6932:         );
 6933:     }
 6934:     return Apache::lonhtmlcommon::generate_menu(@menu);
 6935: #               { text => 'View Log-in History',
 6936: #                 help => 'Course_User_Logins',
 6937: #                 action => 'logins',
 6938: #                 permission => $permission->{'cusr'},
 6939: #               });
 6940: }
 6941: 
 6942: sub restore_prev_selections {
 6943:     my %saveable_parameters = ('srchby'   => 'scalar',
 6944: 			       'srchin'   => 'scalar',
 6945: 			       'srchtype' => 'scalar',
 6946: 			       );
 6947:     &Apache::loncommon::store_settings('user','user_picker',
 6948: 				       \%saveable_parameters);
 6949:     &Apache::loncommon::restore_settings('user','user_picker',
 6950: 					 \%saveable_parameters);
 6951: }
 6952: 
 6953: sub print_selfenroll_menu {
 6954:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 6955:     my $crstype = &Apache::loncommon::course_type();
 6956:     my $formname = 'selfenroll';
 6957:     my $nolink = 1;
 6958:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 6959:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 6960:     my $setsec_js = 
 6961:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 6962:     my %alerts = &Apache::lonlocal::texthash(
 6963:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 6964:         butn => 'but no user types have been checked.',
 6965:         wilf => "Please uncheck 'activate' or check at least one type.",
 6966:     );
 6967:     my $disabled;
 6968:     if ($readonly) {
 6969:        $disabled = ' disabled="disabled"';
 6970:     }
 6971:     &js_escape(\%alerts);
 6972:     my $selfenroll_js = <<"ENDSCRIPT";
 6973: function update_types(caller,num) {
 6974:     var delidx = getIndexByName('selfenroll_delete');
 6975:     var actidx = getIndexByName('selfenroll_activate');
 6976:     if (caller == 'selfenroll_all') {
 6977:         var selall;
 6978:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 6979:             if (document.$formname.selfenroll_all[i].checked) {
 6980:                 selall = document.$formname.selfenroll_all[i].value;
 6981:             }
 6982:         }
 6983:         if (selall == 1) {
 6984:             if (delidx != -1) {
 6985:                 if (document.$formname.selfenroll_delete.length) {
 6986:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 6987:                         document.$formname.selfenroll_delete[j].checked = true;
 6988:                     }
 6989:                 } else {
 6990:                     document.$formname.elements[delidx].checked = true;
 6991:                 }
 6992:             }
 6993:             if (actidx != -1) {
 6994:                 if (document.$formname.selfenroll_activate.length) {
 6995:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 6996:                         document.$formname.selfenroll_activate[j].checked = false;
 6997:                     }
 6998:                 } else {
 6999:                     document.$formname.elements[actidx].checked = false;
 7000:                 }
 7001:             }
 7002:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 7003:         }
 7004:     }
 7005:     if (caller == 'selfenroll_activate') {
 7006:         if (document.$formname.selfenroll_activate.length) {
 7007:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7008:                 if (document.$formname.selfenroll_activate[j].value == num) {
 7009:                     if (document.$formname.selfenroll_activate[j].checked) {
 7010:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7011:                             if (document.$formname.selfenroll_all[i].value == '1') {
 7012:                                 document.$formname.selfenroll_all[i].checked = false;
 7013:                             }
 7014:                             if (document.$formname.selfenroll_all[i].value == '0') {
 7015:                                 document.$formname.selfenroll_all[i].checked = true;
 7016:                             }
 7017:                         }
 7018:                     }
 7019:                 }
 7020:             }
 7021:         } else {
 7022:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7023:                 if (document.$formname.selfenroll_all[i].value == '1') {
 7024:                     document.$formname.selfenroll_all[i].checked = false;
 7025:                 }
 7026:                 if (document.$formname.selfenroll_all[i].value == '0') {
 7027:                     document.$formname.selfenroll_all[i].checked = true;
 7028:                 }
 7029:             }
 7030:         }
 7031:     }
 7032:     if (caller == 'selfenroll_delete') {
 7033:         if (document.$formname.selfenroll_delete.length) {
 7034:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7035:                 if (document.$formname.selfenroll_delete[j].value == num) {
 7036:                     if (document.$formname.selfenroll_delete[j].checked) {
 7037:                         var delindex = getIndexByName('selfenroll_types_'+num);
 7038:                         if (delindex != -1) { 
 7039:                             if (document.$formname.elements[delindex].length) {
 7040:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7041:                                     document.$formname.elements[delindex][k].checked = false;
 7042:                                 }
 7043:                             } else {
 7044:                                 document.$formname.elements[delindex].checked = false;
 7045:                             }
 7046:                         }
 7047:                     }
 7048:                 }
 7049:             }
 7050:         } else {
 7051:             if (document.$formname.selfenroll_delete.checked) {
 7052:                 var delindex = getIndexByName('selfenroll_types_'+num);
 7053:                 if (delindex != -1) {
 7054:                     if (document.$formname.elements[delindex].length) {
 7055:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7056:                             document.$formname.elements[delindex][k].checked = false;
 7057:                         }
 7058:                     } else {
 7059:                         document.$formname.elements[delindex].checked = false;
 7060:                     }
 7061:                 }
 7062:             }
 7063:         }
 7064:     }
 7065:     return;
 7066: }
 7067: 
 7068: function validate_types(form) {
 7069:     var needaction = new Array();
 7070:     var countfail = 0;
 7071:     var actidx = getIndexByName('selfenroll_activate');
 7072:     if (actidx != -1) {
 7073:         if (document.$formname.selfenroll_activate.length) {
 7074:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7075:                 var num = document.$formname.selfenroll_activate[j].value;
 7076:                 if (document.$formname.selfenroll_activate[j].checked) {
 7077:                     countfail = check_types(num,countfail,needaction)
 7078:                 }
 7079:             }
 7080:         } else {
 7081:             if (document.$formname.selfenroll_activate.checked) {
 7082:                 var num = document.$formname.selfenroll_activate.value;
 7083:                 countfail = check_types(num,countfail,needaction)
 7084:             }
 7085:         }
 7086:     }
 7087:     if (countfail > 0) {
 7088:         var msg = "$alerts{'acto'}\\n";
 7089:         var loopend = needaction.length -1;
 7090:         if (loopend > 0) {
 7091:             for (var m=0; m<loopend; m++) {
 7092:                 msg += needaction[m]+", ";
 7093:             }
 7094:         }
 7095:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 7096:         alert(msg);
 7097:         return; 
 7098:     }
 7099:     setSections(form);
 7100: }
 7101: 
 7102: function check_types(num,countfail,needaction) {
 7103:     var boxname = 'selfenroll_types_'+num;
 7104:     var typeidx = getIndexByName(boxname);
 7105:     var count = 0;
 7106:     if (typeidx != -1) {
 7107:         if (document.$formname.elements[boxname].length) {
 7108:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 7109:                 if (document.$formname.elements[boxname][k].checked) {
 7110:                     count ++;
 7111:                 }
 7112:             }
 7113:         } else {
 7114:             if (document.$formname.elements[typeidx].checked) {
 7115:                 count ++;
 7116:             }
 7117:         }
 7118:         if (count == 0) {
 7119:             var domidx = getIndexByName('selfenroll_dom_'+num);
 7120:             if (domidx != -1) {
 7121:                 var domname = document.$formname.elements[domidx].value;
 7122:                 needaction[countfail] = domname;
 7123:                 countfail ++;
 7124:             }
 7125:         }
 7126:     }
 7127:     return countfail;
 7128: }
 7129: 
 7130: function toggleNotify() {
 7131:     var selfenrollApproval = 0;
 7132:     if (document.$formname.selfenroll_approval.length) {
 7133:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 7134:             if (document.$formname.selfenroll_approval[i].checked) {
 7135:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 7136:                 break;        
 7137:             }
 7138:         }
 7139:     }
 7140:     if (document.getElementById('notified')) {
 7141:         if (selfenrollApproval == 0) {
 7142:             document.getElementById('notified').style.display='none';
 7143:         } else {
 7144:             document.getElementById('notified').style.display='block';
 7145:         }
 7146:     }
 7147:     return;
 7148: }
 7149: 
 7150: function getIndexByName(item) {
 7151:     for (var i=0;i<document.$formname.elements.length;i++) {
 7152:         if (document.$formname.elements[i].name == item) {
 7153:             return i;
 7154:         }
 7155:     }
 7156:     return -1;
 7157: }
 7158: ENDSCRIPT
 7159: 
 7160:     my $output = '<script type="text/javascript">'."\n".
 7161:                  '// <![CDATA['."\n".
 7162:                  $setsec_js."\n".$selfenroll_js."\n".
 7163:                  '// ]]>'."\n".
 7164:                  '</script>'."\n".
 7165:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 7166:     my $visactions = &cat_visibility($cdom);
 7167:     my ($cathash,%cattype);
 7168:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7169:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7170:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7171:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7172:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7173:         if ($cattype{'auth'} eq '') {
 7174:             $cattype{'auth'} = 'std';
 7175:         }
 7176:         if ($cattype{'unauth'} eq '') {
 7177:             $cattype{'unauth'} = 'std';
 7178:         }
 7179:     } else {
 7180:         $cathash = {};
 7181:         $cattype{'auth'} = 'std';
 7182:         $cattype{'unauth'} = 'std';
 7183:     }
 7184:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7185:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7186:                   '<br />'.
 7187:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7188:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7189:                   '</ul>');
 7190:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7191:         if ($currsettings->{'uniquecode'}) {
 7192:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7193:         } else {
 7194:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7195:                   '<br />'.
 7196:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7197:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7198:                   '</ul><br />');
 7199:         }
 7200:     } else {
 7201:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7202:         if (ref($visactions) eq 'HASH') {
 7203:             if ($visible) {
 7204:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 7205:            } else {
 7206:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 7207:                           .$visactions->{'yous'}.
 7208:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 7209:                 if (ref($vismsgs) eq 'ARRAY') {
 7210:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 7211:                     foreach my $item (@{$vismsgs}) {
 7212:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 7213:                     }
 7214:                     $output .= '</ul>';
 7215:                 }
 7216:                 $output .= '</p>';
 7217:             }
 7218:         }
 7219:     }
 7220:     my $actionhref = '/adm/createuser';
 7221:     if ($context eq 'domain') {
 7222:         $actionhref = '/adm/modifycourse';
 7223:     }
 7224: 
 7225:     my %noedit;
 7226:     unless ($context eq 'domain') {
 7227:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7228:     }
 7229:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 7230:                &Apache::lonhtmlcommon::start_pick_box();
 7231:     if (ref($row) eq 'ARRAY') {
 7232:         foreach my $item (@{$row}) {
 7233:             my $title = $item; 
 7234:             if (ref($lt) eq 'HASH') {
 7235:                 $title = $lt->{$item};
 7236:             }
 7237:             $output .= &Apache::lonhtmlcommon::row_title($title);
 7238:             if ($item eq 'types') {
 7239:                 my $curr_types;
 7240:                 if (ref($currsettings) eq 'HASH') {
 7241:                     $curr_types = $currsettings->{'selfenroll_types'};
 7242:                 }
 7243:                 if ($noedit{$item}) {
 7244:                     if ($curr_types eq '*') {
 7245:                         $output .= &mt('Any user in any domain');   
 7246:                     } else {
 7247:                         my @entries = split(/;/,$curr_types);
 7248:                         if (@entries > 0) {
 7249:                             $output .= '<ul>'; 
 7250:                             foreach my $entry (@entries) {
 7251:                                 my ($currdom,$typestr) = split(/:/,$entry);
 7252:                                 next if ($typestr eq '');
 7253:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 7254:                                 my @currinsttypes = split(',',$typestr);
 7255:                                 my ($othertitle,$usertypes,$types) = 
 7256:                                     &Apache::loncommon::sorted_inst_types($currdom);
 7257:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7258:                                     $usertypes->{'any'} = &mt('any user'); 
 7259:                                     if (keys(%{$usertypes}) > 0) {
 7260:                                         $usertypes->{'other'} = &mt('other users');
 7261:                                     }
 7262:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 7263:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 7264:                                  }
 7265:                             }
 7266:                             $output .= '</ul>';
 7267:                         } else {
 7268:                             $output .= &mt('None');
 7269:                         }
 7270:                     }
 7271:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7272:                     next;
 7273:                 }
 7274:                 my $showdomdesc = 1;
 7275:                 my $includeempty = 1;
 7276:                 my $num = 0;
 7277:                 $output .= &Apache::loncommon::start_data_table().
 7278:                            &Apache::loncommon::start_data_table_row()
 7279:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 7280:                            .&mt('Any user in any domain:')
 7281:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 7282:                 if ($curr_types eq '*') {
 7283:                     $output .= ' checked="checked" '; 
 7284:                 }
 7285:                 $output .= 'onchange="javascript:update_types('.
 7286:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 7287:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 7288:                 if ($curr_types ne '*') {
 7289:                     $output .= ' checked="checked" ';
 7290:                 }
 7291:                 $output .= ' onchange="javascript:update_types('.
 7292:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 7293:                            &Apache::loncommon::end_data_table_row().
 7294:                            &Apache::loncommon::end_data_table().
 7295:                            &mt('Or').'<br />'.
 7296:                            &Apache::loncommon::start_data_table();
 7297:                 my %currdoms;
 7298:                 if ($curr_types eq '') {
 7299:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 7300:                 } elsif ($curr_types ne '*') {
 7301:                     my @entries = split(/;/,$curr_types);
 7302:                     if (@entries > 0) {
 7303:                         foreach my $entry (@entries) {
 7304:                             my ($currdom,$typestr) = split(/:/,$entry);
 7305:                             $currdoms{$currdom} = 1;
 7306:                             my $domdesc = &Apache::lonnet::domain($currdom);
 7307:                             my @currinsttypes = split(',',$typestr);
 7308:                             $output .= &Apache::loncommon::start_data_table_row()
 7309:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 7310:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 7311:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 7312:                                        .'" value="'.$currdom.'" /></span><br />'
 7313:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 7314:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 7315:                                        .&mt('Delete').'</label></span></td>';
 7316:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 7317:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 7318:                                        .&Apache::loncommon::end_data_table_row();
 7319:                             $num ++;
 7320:                         }
 7321:                     }
 7322:                 }
 7323:                 my $add_domtitle = &mt('Users in additional domain:');
 7324:                 if ($curr_types eq '*') { 
 7325:                     $add_domtitle = &mt('Users in specific domain:');
 7326:                 } elsif ($curr_types eq '') {
 7327:                     $add_domtitle = &mt('Users in other domain:');
 7328:                 }
 7329:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 7330:                 $output .= &Apache::loncommon::start_data_table_row()
 7331:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 7332:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 7333:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 7334:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 7335:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 7336:                            .&Apache::loncommon::end_data_table();
 7337:             } elsif ($item eq 'registered') {
 7338:                 my ($regon,$regoff);
 7339:                 my $registered;
 7340:                 if (ref($currsettings) eq 'HASH') {
 7341:                     $registered = $currsettings->{'selfenroll_registered'};
 7342:                 }
 7343:                 if ($noedit{$item}) {
 7344:                     if ($registered) {
 7345:                         $output .= &mt('Must be registered in course');
 7346:                     } else {
 7347:                         $output .= &mt('No requirement');
 7348:                     }
 7349:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7350:                     next;
 7351:                 }
 7352:                 if ($registered) {
 7353:                     $regon = ' checked="checked" ';
 7354:                     $regoff = '';
 7355:                 } else {
 7356:                     $regon = '';
 7357:                     $regoff = ' checked="checked" ';
 7358:                 }
 7359:                 $output .= '<label>'.
 7360:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 7361:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 7362:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 7363:                            &mt('No').'</label>';
 7364:             } elsif ($item eq 'enroll_dates') {
 7365:                 my ($starttime,$endtime);
 7366:                 if (ref($currsettings) eq 'HASH') {
 7367:                     $starttime = $currsettings->{'selfenroll_start_date'};
 7368:                     $endtime = $currsettings->{'selfenroll_end_date'};
 7369:                     if ($starttime eq '') {
 7370:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7371:                     }
 7372:                     if ($endtime eq '') {
 7373:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7374:                     }
 7375:                 }
 7376:                 if ($noedit{$item}) {
 7377:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7378:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7379:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7380:                     next;
 7381:                 }
 7382:                 my $startform =
 7383:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 7384:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7385:                 my $endform =
 7386:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 7387:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7388:                 $output .= &selfenroll_date_forms($startform,$endform);
 7389:             } elsif ($item eq 'access_dates') {
 7390:                 my ($starttime,$endtime);
 7391:                 if (ref($currsettings) eq 'HASH') {
 7392:                     $starttime = $currsettings->{'selfenroll_start_access'};
 7393:                     $endtime = $currsettings->{'selfenroll_end_access'};
 7394:                     if ($starttime eq '') {
 7395:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7396:                     }
 7397:                     if ($endtime eq '') {
 7398:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7399:                     }
 7400:                 }
 7401:                 if ($noedit{$item}) {
 7402:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7403:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7404:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7405:                     next;
 7406:                 }
 7407:                 my $startform =
 7408:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 7409:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7410:                 my $endform =
 7411:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 7412:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7413:                 $output .= &selfenroll_date_forms($startform,$endform);
 7414:             } elsif ($item eq 'section') {
 7415:                 my $currsec;
 7416:                 if (ref($currsettings) eq 'HASH') {
 7417:                     $currsec = $currsettings->{'selfenroll_section'};
 7418:                 }
 7419:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 7420:                 my $newsecval;
 7421:                 if ($currsec ne 'none' && $currsec ne '') {
 7422:                     if (!defined($sections_count{$currsec})) {
 7423:                         $newsecval = $currsec;
 7424:                     }
 7425:                 }
 7426:                 if ($noedit{$item}) {
 7427:                     if ($currsec ne '') {
 7428:                         $output .= $currsec;
 7429:                     } else {
 7430:                         $output .= &mt('No specific section');
 7431:                     }
 7432:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7433:                     next;
 7434:                 }
 7435:                 my $sections_select = 
 7436:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 7437:                 $output .= '<table class="LC_createuser">'."\n".
 7438:                            '<tr class="LC_section_row">'."\n".
 7439:                            '<td align="center">'.&mt('Existing sections')."\n".
 7440:                            '<br />'.$sections_select.'</td><td align="center">'.
 7441:                            &mt('New section').'<br />'."\n".
 7442:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 7443:                            '<input type="hidden" name="sections" value="" />'."\n".
 7444:                            '</td></tr></table>'."\n";
 7445:             } elsif ($item eq 'approval') {
 7446:                 my ($currnotified,$currapproval,%appchecked);
 7447:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7448:                 if (ref($currsettings) eq 'HASH') {
 7449:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 7450:                     $currapproval = $currsettings->{'selfenroll_approval'};
 7451:                 }
 7452:                 if ($currapproval !~ /^[012]$/) {
 7453:                     $currapproval = 0;
 7454:                 }
 7455:                 if ($noedit{$item}) {
 7456:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 7457:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 7458:                     next;
 7459:                 }
 7460:                 $appchecked{$currapproval} = ' checked="checked"';
 7461:                 for my $i (0..2) {
 7462:                     $output .= '<label>'.
 7463:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 7464:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 7465:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 7466:                 }
 7467:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 7468:                 my (@ccs,%notified);
 7469:                 my $ccrole = 'cc';
 7470:                 if ($crstype eq 'Community') {
 7471:                     $ccrole = 'co';
 7472:                 }
 7473:                 if ($advhash{$ccrole}) {
 7474:                     @ccs = split(/,/,$advhash{$ccrole});
 7475:                 }
 7476:                 if ($currnotified) {
 7477:                     foreach my $current (split(/,/,$currnotified)) {
 7478:                         $notified{$current} = 1;
 7479:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 7480:                             push(@ccs,$current);
 7481:                         }
 7482:                     }
 7483:                 }
 7484:                 if (@ccs) {
 7485:                     my $style;
 7486:                     unless ($currapproval) {
 7487:                         $style = ' style="display: none;"'; 
 7488:                     }
 7489:                     $output .= '<br /><div id="notified"'.$style.'>'.
 7490:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 7491:                                &Apache::loncommon::start_data_table().
 7492:                                &Apache::loncommon::start_data_table_row();
 7493:                     my $count = 0;
 7494:                     my $numcols = 4;
 7495:                     foreach my $cc (sort(@ccs)) {
 7496:                         my $notifyon;
 7497:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 7498:                         if ($notified{$cc}) {
 7499:                             $notifyon = ' checked="checked" ';
 7500:                         }
 7501:                         if ($count && !$count%$numcols) {
 7502:                             $output .= &Apache::loncommon::end_data_table_row().
 7503:                                        &Apache::loncommon::start_data_table_row()
 7504:                         }
 7505:                         $output .= '<td><span class="LC_nobreak"><label>'.
 7506:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 7507:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 7508:                                    '</label></span></td>';
 7509:                         $count ++;
 7510:                     }
 7511:                     my $rem = $count%$numcols;
 7512:                     if ($rem) {
 7513:                         my $emptycols = $numcols - $rem;
 7514:                         for (my $i=0; $i<$emptycols; $i++) { 
 7515:                             $output .= '<td>&nbsp;</td>';
 7516:                         }
 7517:                     }
 7518:                     $output .= &Apache::loncommon::end_data_table_row().
 7519:                                &Apache::loncommon::end_data_table().
 7520:                                '</div>';
 7521:                 }
 7522:             } elsif ($item eq 'limit') {
 7523:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 7524:                 if (ref($currsettings) eq 'HASH') {
 7525:                     $currlim = $currsettings->{'selfenroll_limit'};
 7526:                     $currcap = $currsettings->{'selfenroll_cap'};
 7527:                 }
 7528:                 if ($noedit{$item}) {
 7529:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 7530:                         if ($currlim eq 'allstudents') {
 7531:                             $output .= &mt('Limit by total students');
 7532:                         } elsif ($currlim eq 'selfenrolled') {
 7533:                             $output .= &mt('Limit by total self-enrolled students');
 7534:                         }
 7535:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 7536:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 7537:                     } else {
 7538:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 7539:                     }
 7540:                     next;
 7541:                 }
 7542:                 if ($currlim eq 'allstudents') {
 7543:                     $crslimit = ' checked="checked" ';
 7544:                     $selflimit = ' ';
 7545:                     $nolimit = ' ';
 7546:                 } elsif ($currlim eq 'selfenrolled') {
 7547:                     $crslimit = ' ';
 7548:                     $selflimit = ' checked="checked" ';
 7549:                     $nolimit = ' '; 
 7550:                 } else {
 7551:                     $crslimit = ' ';
 7552:                     $selflimit = ' ';
 7553:                     $nolimit = ' checked="checked" ';
 7554:                 }
 7555:                 $output .= '<table><tr><td><label>'.
 7556:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 7557:                            &mt('No limit').'</label></td><td><label>'.
 7558:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 7559:                            &mt('Limit by total students').'</label></td><td><label>'.
 7560:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 7561:                            &mt('Limit by total self-enrolled students').
 7562:                            '</td></tr><tr>'.
 7563:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 7564:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 7565:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 7566:             }
 7567:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 7568:         }
 7569:     }
 7570:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 7571:     unless ($readonly) {
 7572:         $output .= '<input type="button" name="selfenrollconf" value="'
 7573:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 7574:     }
 7575:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 7576:               .'<input type="hidden" name="state" value="done" />'."\n"
 7577:               .$additional.'</form>';
 7578:     $r->print($output);
 7579:     return;
 7580: }
 7581: 
 7582: sub get_noedit_fields {
 7583:     my ($cdom,$cnum,$crstype,$row) = @_;
 7584:     my %noedit;
 7585:     if (ref($row) eq 'ARRAY') {
 7586:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 7587:                                                            'internal.selfenrollmgrdc',
 7588:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 7589:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 7590:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 7591:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 7592:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 7593:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 7594:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 7595: 
 7596:         foreach my $item (@{$row}) {
 7597:             next if ($specific_managebycc{$item});
 7598:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 7599:                 $noedit{$item} = 1;
 7600:             }
 7601:         }
 7602:     }
 7603:     return %noedit;
 7604: }
 7605: 
 7606: sub visible_in_stdcat {
 7607:     my ($cdom,$cnum,$domconf) = @_;
 7608:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 7609:     unless (ref($domconf) eq 'HASH') {
 7610:         return ($visible,$cansetvis,\@vismsgs);
 7611:     }
 7612:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7613:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 7614:             $settable{'togglecats'} = 1;
 7615:         }
 7616:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 7617:             $settable{'categorize'} = 1;
 7618:         }
 7619:         $cathash = $domconf->{'coursecategories'}{'cats'};
 7620:     }
 7621:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 7622:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 7623:     } elsif ($settable{'togglecats'}) {
 7624:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 7625:     } elsif ($settable{'categorize'}) {
 7626:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 7627:     } else {
 7628:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 7629:     }
 7630:      
 7631:     my %currsettings =
 7632:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 7633:                              $cdom,$cnum);
 7634:     $visible = 0;
 7635:     if ($currsettings{'internal.coursecode'} ne '') {
 7636:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7637:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7638:             if (ref($cathash) eq 'HASH') {
 7639:                 if ($cathash->{'instcode::0'} eq '') {
 7640:                     push(@vismsgs,'dc_addinst'); 
 7641:                 } else {
 7642:                     $visible = 1;
 7643:                 }
 7644:             } else {
 7645:                 $visible = 1;
 7646:             }
 7647:         } else {
 7648:             $visible = 1;
 7649:         }
 7650:     } else {
 7651:         if (ref($cathash) eq 'HASH') {
 7652:             if ($cathash->{'instcode::0'} ne '') {
 7653:                 push(@vismsgs,'dc_instcode');
 7654:             }
 7655:         } else {
 7656:             push(@vismsgs,'dc_instcode');
 7657:         }
 7658:     }
 7659:     if ($currsettings{'categories'} ne '') {
 7660:         my $cathash;
 7661:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7662:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7663:             if (ref($cathash) eq 'HASH') {
 7664:                 if (keys(%{$cathash}) == 0) {
 7665:                     push(@vismsgs,'dc_catalog');
 7666:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 7667:                     push(@vismsgs,'dc_categories');
 7668:                 } else {
 7669:                     my @currcategories = split('&',$currsettings{'categories'});
 7670:                     my $matched = 0;
 7671:                     foreach my $cat (@currcategories) {
 7672:                         if ($cathash->{$cat} ne '') {
 7673:                             $visible = 1;
 7674:                             $matched = 1;
 7675:                             last;
 7676:                         }
 7677:                     }
 7678:                     if (!$matched) {
 7679:                         if ($settable{'categorize'}) { 
 7680:                             push(@vismsgs,'chgcat');
 7681:                         } else {
 7682:                             push(@vismsgs,'dc_chgcat');
 7683:                         }
 7684:                     }
 7685:                 }
 7686:             }
 7687:         }
 7688:     } else {
 7689:         if (ref($cathash) eq 'HASH') {
 7690:             if ((keys(%{$cathash}) > 1) || 
 7691:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 7692:                 if ($settable{'categorize'}) {
 7693:                     push(@vismsgs,'addcat');
 7694:                 } else {
 7695:                     push(@vismsgs,'dc_addcat');
 7696:                 }
 7697:             }
 7698:         }
 7699:     }
 7700:     if ($currsettings{'hidefromcat'} eq 'yes') {
 7701:         $visible = 0;
 7702:         if ($settable{'togglecats'}) {
 7703:             unshift(@vismsgs,'unhide');
 7704:         } else {
 7705:             unshift(@vismsgs,'dc_unhide')
 7706:         }
 7707:     }
 7708:     return ($visible,$cansetvis,\@vismsgs);
 7709: }
 7710: 
 7711: sub cat_visibility {
 7712:     my ($cdom) = @_;
 7713:     my %visactions = &Apache::lonlocal::texthash(
 7714:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 7715:                    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.',
 7716:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 7717:                    none => 'Display of a course catalog is disabled for this domain.',
 7718:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 7719:                    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.',
 7720:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 7721:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 7722:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 7723:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 7724:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 7725:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 7726:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 7727:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 7728:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 7729:                    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',
 7730:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 7731:     );
 7732:     if ($env{'request.role'} eq "dc./$cdom/") {
 7733:         $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;');
 7734:         $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;');
 7735:         $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;');
 7736:         $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;');
 7737:         $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;');
 7738:         $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;');
 7739:         $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;');
 7740:         $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;');
 7741:         $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;');
 7742:     }
 7743:     $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>"');
 7744:     $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>"');
 7745:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 7746:     return \%visactions;
 7747: }
 7748: 
 7749: sub new_selfenroll_dom_row {
 7750:     my ($newdom,$num) = @_;
 7751:     my $domdesc = &Apache::lonnet::domain($newdom);
 7752:     my $output;
 7753:     if ($domdesc ne '') {
 7754:         $output .= &Apache::loncommon::start_data_table_row()
 7755:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 7756:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 7757:                    .'" value="'.$newdom.'" /></span><br />'
 7758:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 7759:                    .'name="selfenroll_activate" value="'.$num.'" '
 7760:                    .'onchange="javascript:update_types('
 7761:                    ."'selfenroll_activate','$num'".');" />'
 7762:                    .&mt('Activate').'</label></span></td>';
 7763:         my @currinsttypes;
 7764:         $output .= '<td>'.&mt('User types:').'<br />'
 7765:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 7766:                    .&Apache::loncommon::end_data_table_row();
 7767:     }
 7768:     return $output;
 7769: }
 7770: 
 7771: sub selfenroll_inst_types {
 7772:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 7773:     my $output;
 7774:     my $numinrow = 4;
 7775:     my $count = 0;
 7776:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 7777:     my $othervalue = 'any';
 7778:     my $disabled;
 7779:     if ($readonly) {
 7780:         $disabled = ' disabled="disabled"';
 7781:     }
 7782:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7783:         if (keys(%{$usertypes}) > 0) {
 7784:             $othervalue = 'other';
 7785:         }
 7786:         $output .= '<table><tr>';
 7787:         foreach my $type (@{$types}) {
 7788:             if (($count > 0) && ($count%$numinrow == 0)) {
 7789:                 $output .= '</tr><tr>';
 7790:             }
 7791:             if (defined($usertypes->{$type})) {
 7792:                 my $esc_type = &escape($type);
 7793:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 7794:                            $esc_type.'" ';
 7795:                 if (ref($currinsttypes) eq 'ARRAY') {
 7796:                     if (@{$currinsttypes} > 0) {
 7797:                         if (grep(/^any$/,@{$currinsttypes})) {
 7798:                             $output .= 'checked="checked"';
 7799:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 7800:                             $output .= 'checked="checked"';
 7801:                         }
 7802:                     } else {
 7803:                         $output .= 'checked="checked"';
 7804:                     }
 7805:                 }
 7806:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 7807:             }
 7808:             $count ++;
 7809:         }
 7810:         if (($count > 0) && ($count%$numinrow == 0)) {
 7811:             $output .= '</tr><tr>';
 7812:         }
 7813:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 7814:         if (ref($currinsttypes) eq 'ARRAY') {
 7815:             if (@{$currinsttypes} > 0) {
 7816:                 if (grep(/^any$/,@{$currinsttypes})) { 
 7817:                     $output .= ' checked="checked"';
 7818:                 } elsif ($othervalue eq 'other') {
 7819:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 7820:                         $output .= ' checked="checked"';
 7821:                     }
 7822:                 }
 7823:             } else {
 7824:                 $output .= ' checked="checked"';
 7825:             }
 7826:         } else {
 7827:             $output .= ' checked="checked"';
 7828:         }
 7829:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 7830:     }
 7831:     return $output;
 7832: }
 7833: 
 7834: sub selfenroll_date_forms {
 7835:     my ($startform,$endform) = @_;
 7836:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 7837:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 7838:                                                     'LC_oddrow_value')."\n".
 7839:                   $startform."\n".
 7840:                   &Apache::lonhtmlcommon::row_closure(1).
 7841:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 7842:                                                    'LC_oddrow_value')."\n".
 7843:                   $endform."\n".
 7844:                   &Apache::lonhtmlcommon::row_closure(1).
 7845:                   &Apache::lonhtmlcommon::end_pick_box();
 7846:     return $output;
 7847: }
 7848: 
 7849: sub print_userchangelogs_display {
 7850:     my ($r,$context,$permission,$brcrum) = @_;
 7851:     my $formname = 'rolelog';
 7852:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 7853:     if ($context eq 'domain') {
 7854:         $domain = $env{'request.role.domain'};
 7855:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 7856:     } else {
 7857:         if ($context eq 'course') { 
 7858:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7859:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 7860:             $crstype = &Apache::loncommon::course_type();
 7861:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 7862:             my %saveable_parameters = ('show' => 'scalar',);
 7863:             &Apache::loncommon::store_course_settings('roles_log',
 7864:                                                       \%saveable_parameters);
 7865:             &Apache::loncommon::restore_course_settings('roles_log',
 7866:                                                         \%saveable_parameters);
 7867:         } elsif ($context eq 'author') {
 7868:             $domain = $env{'user.domain'};
 7869:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 7870:                 $username = $env{'user.name'};
 7871:             } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 7872:                 ($domain,$username) = ($1,$2);
 7873:             } else {
 7874:                 undef($domain);
 7875:             }
 7876:         }
 7877:         if ($domain ne '' && $username ne '') { 
 7878:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 7879:         }
 7880:     }
 7881:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 7882: 
 7883:     my $helpitem;
 7884:     if ($context eq 'course') {
 7885:         $helpitem = 'Course_User_Logs';
 7886:     } elsif ($context eq 'domain') {
 7887:         $helpitem = 'Domain_Role_Logs';
 7888:     } elsif ($context eq 'author') {
 7889:         $helpitem = 'Author_User_Logs';
 7890:     }
 7891:     push (@{$brcrum},
 7892:              {href => '/adm/createuser?action=changelogs',
 7893:               text => 'User Management Logs',
 7894:               help => $helpitem});
 7895:     my $bread_crumbs_component = 'User Changes';
 7896:     my $args = { bread_crumbs           => $brcrum,
 7897:                  bread_crumbs_component => $bread_crumbs_component};
 7898: 
 7899:     # Create navigation javascript
 7900:     my $jsnav = &userlogdisplay_js($formname);
 7901: 
 7902:     my $jscript = (<<ENDSCRIPT);
 7903: <script type="text/javascript">
 7904: // <![CDATA[
 7905: $jsnav
 7906: // ]]>
 7907: </script>
 7908: ENDSCRIPT
 7909: 
 7910:     # print page header
 7911:     $r->print(&header($jscript,$args));
 7912: 
 7913:     # set defaults
 7914:     my $now = time();
 7915:     my $defstart = $now - (7*24*3600); #7 days ago 
 7916:     my %defaults = (
 7917:                      page               => '1',
 7918:                      show               => '10',
 7919:                      role               => 'any',
 7920:                      chgcontext         => 'any',
 7921:                      rolelog_start_date => $defstart,
 7922:                      rolelog_end_date   => $now,
 7923:                      approvals          => 'any',
 7924:                    );
 7925:     my $more_records = 0;
 7926: 
 7927:     # set current
 7928:     my %curr;
 7929:     foreach my $item ('show','page','role','chgcontext','approvals') {
 7930:         $curr{$item} = $env{'form.'.$item};
 7931:     }
 7932:     my ($startdate,$enddate) = 
 7933:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 7934:     $curr{'rolelog_start_date'} = $startdate;
 7935:     $curr{'rolelog_end_date'} = $enddate;
 7936:     foreach my $key (keys(%defaults)) {
 7937:         if ($curr{$key} eq '') {
 7938:             $curr{$key} = $defaults{$key};
 7939:         }
 7940:     }
 7941:     my (%whodunit,%changed,$version);
 7942:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 7943:     my ($minshown,$maxshown);
 7944:     $minshown = 1;
 7945:     my $count = 0;
 7946:     if ($curr{'show'} =~ /\D/) {
 7947:         $curr{'page'} = 1;
 7948:     } else {
 7949:         $maxshown = $curr{'page'} * $curr{'show'};
 7950:         if ($curr{'page'} > 1) {
 7951:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7952:         }
 7953:     }
 7954: 
 7955:     # Form Header
 7956:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7957:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 7958:                                    $version,$crstype));
 7959: 
 7960:     my $showntableheader = 0;
 7961: 
 7962:     # Table Header
 7963:     my $tableheader = 
 7964:         &Apache::loncommon::start_data_table_header_row()
 7965:        .'<th>&nbsp;</th>'
 7966:        .'<th>'.&mt('When').'</th>'
 7967:        .'<th>'.&mt('Who made the change').'</th>'
 7968:        .'<th>'.&mt('Changed User').'</th>'
 7969:        .'<th>'.&mt('Role').'</th>';
 7970: 
 7971:     if ($context eq 'course') {
 7972:         $tableheader .= '<th>'.&mt('Section').'</th>';
 7973:     }
 7974:     $tableheader .=
 7975:         '<th>'.&mt('Context').'</th>'
 7976:        .'<th>'.&mt('Start').'</th>'
 7977:        .'<th>'.&mt('End').'</th>'
 7978:        .&Apache::loncommon::end_data_table_header_row();
 7979: 
 7980:     # Display user change log data
 7981:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 7982:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 7983:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 7984:         if ($curr{'show'} !~ /\D/) {
 7985:             if ($count >= $curr{'page'} * $curr{'show'}) {
 7986:                 $more_records = 1;
 7987:                 last;
 7988:             }
 7989:         }
 7990:         if ($curr{'role'} ne 'any') {
 7991:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 7992:         }
 7993:         if ($curr{'chgcontext'} ne 'any') {
 7994:             if ($curr{'chgcontext'} eq 'selfenroll') {
 7995:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 7996:             } else {
 7997:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 7998:             }
 7999:         }
 8000:         if (($context eq 'course') && ($viewablesec ne '')) {
 8001:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 8002:         }
 8003:         if ($curr{'approvals'} eq 'none') {
 8004:             next if ($roleslog{$id}{'logentry'}{'approval'});
 8005:         } elsif ($curr{'approvals'} ne 'any') { 
 8006:             next if ($roleslog{$id}{'logentry'}{'approval'} ne $curr{'approvals'});
 8007:         }
 8008:         $count ++;
 8009:         next if ($count < $minshown);
 8010:         unless ($showntableheader) {
 8011:             $r->print(&Apache::loncommon::start_data_table()
 8012:                      .$tableheader);
 8013:             $r->rflush();
 8014:             $showntableheader = 1;
 8015:         }
 8016:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 8017:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 8018:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 8019:         }
 8020:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 8021:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 8022:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 8023:         }
 8024:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 8025:         if ($sec eq '') {
 8026:             $sec = &mt('None');
 8027:         }
 8028:         my ($rolestart,$roleend);
 8029:         if ($roleslog{$id}{'delflag'}) {
 8030:             $rolestart = &mt('deleted');
 8031:             $roleend = &mt('deleted');
 8032:         } else {
 8033:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 8034:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 8035:             if ($rolestart eq '' || $rolestart == 0) {
 8036:                 $rolestart = &mt('No start date'); 
 8037:             } else {
 8038:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 8039:             }
 8040:             if ($roleend eq '' || $roleend == 0) { 
 8041:                 $roleend = &mt('No end date');
 8042:             } else {
 8043:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 8044:             }
 8045:         }
 8046:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 8047:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 8048:             $chgcontext = 'selfenroll';
 8049:         }
 8050:         my %lt = &rolechg_contexts($context,$crstype);
 8051:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 8052:             $chgcontext = $lt{$chgcontext};
 8053:         }
 8054:         my ($showreqby,%reqby);
 8055:         if (($roleslog{$id}{'logentry'}{'approval'}) &&
 8056:             ($roleslog{$id}{'logentry'}{'requester'})) {
 8057:             if ($reqby{$roleslog{$id}{'logentry'}{'requester'}} eq '') {
 8058:                 my ($requname,$requdom) = split(/:/,$roleslog{$id}{'logentry'}{'requester'});
 8059:                 $reqby{$roleslog{$id}{'logentry'}{'requester'}} =
 8060:                     &Apache::loncommon::plainname($requname,$requdom);
 8061:             }
 8062:             $showreqby = &mt('Requester').': <span class="LC_nobreak">'.$reqby{$roleslog{$id}{'logentry'}{'requester'}}.'</span><br />';
 8063:             if ($roleslog{$id}{'logentry'}{'approval'} eq 'domain') {
 8064:                 $showreqby .= &mt('Adjudicator').': <span class="LC_nobreak">'.
 8065:                               $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.
 8066:                               '</span>';
 8067:             } else {
 8068:                 $showreqby .= '<span class="LC_nobreak">'.&mt('User approved').'</span>';
 8069:             }
 8070:         } else {
 8071:             $showreqby = $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}};
 8072:         }
 8073:         $r->print(
 8074:             &Apache::loncommon::start_data_table_row()
 8075:            .'<td>'.$count.'</td>'
 8076:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 8077:            .'<td>'.$showreqby.'</td>'
 8078:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 8079:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 8080:         if ($context eq 'course') { 
 8081:             $r->print('<td>'.$sec.'</td>');
 8082:         }
 8083:         $r->print(
 8084:             '<td>'.$chgcontext.'</td>'
 8085:            .'<td>'.$rolestart.'</td>'
 8086:            .'<td>'.$roleend.'</td>'
 8087:            .&Apache::loncommon::end_data_table_row()."\n");
 8088:     }
 8089: 
 8090:     if ($showntableheader) { # Table footer, if content displayed above
 8091:         $r->print(&Apache::loncommon::end_data_table().
 8092:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8093:     } else { # No content displayed above
 8094:         $r->print('<p class="LC_info">'
 8095:                  .&mt('There are no records to display.')
 8096:                  .'</p>'
 8097:         );
 8098:     }
 8099: 
 8100:     # Form Footer
 8101:     $r->print( 
 8102:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8103:        .'<input type="hidden" name="action" value="changelogs" />'
 8104:        .'</form>');
 8105:     return;
 8106: }
 8107: 
 8108: sub print_useraccesslogs_display {
 8109:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 8110:     my $formname = 'accesslog';
 8111:     my $form = 'document.accesslog';
 8112: 
 8113: # set breadcrumbs
 8114:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 8115:     my $prevphasestr;
 8116:     if ($env{'form.popup'}) {
 8117:         $brcrum = [];
 8118:     } else {
 8119:         push (@{$brcrum},
 8120:             {href => "javascript:backPage($form)",
 8121:              text => $breadcrumb_text{'search'}});
 8122:         my @prevphases;
 8123:         if ($env{'form.prevphases'}) {
 8124:             @prevphases = split(/,/,$env{'form.prevphases'});
 8125:             $prevphasestr = $env{'form.prevphases'};
 8126:         }
 8127:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 8128:             push(@{$brcrum},
 8129:                   {href => "javascript:backPage($form,'get_user_info','select')",
 8130:                    text => $breadcrumb_text{'userpicked'}});
 8131:             if ($env{'form.phase'} eq 'userpicked') {
 8132:                 $prevphasestr = 'userpicked';
 8133:             }
 8134:         }
 8135:     }
 8136:     push(@{$brcrum},
 8137:              {href => '/adm/createuser?action=accesslogs',
 8138:               text => 'User access logs',
 8139:               help => 'Domain_User_Access_Logs'});
 8140:     my $bread_crumbs_component = 'User Access Logs';
 8141:     my $args = { bread_crumbs           => $brcrum,
 8142:                  bread_crumbs_component => 'User Management'};
 8143:     if ($env{'form.popup'}) {
 8144:         $args->{'no_nav_bar'} = 1;
 8145:         $args->{'bread_crumbs_nomenu'} = 1;
 8146:     }
 8147: 
 8148: # set javascript
 8149:     my ($jsback,$elements) = &crumb_utilities();
 8150:     my $jsnav = &userlogdisplay_js($formname);
 8151: 
 8152:     my $jscript = (<<ENDSCRIPT);
 8153: <script type="text/javascript">
 8154: // <![CDATA[
 8155: 
 8156: $jsback
 8157: $jsnav
 8158: 
 8159: // ]]>
 8160: </script>
 8161: 
 8162: ENDSCRIPT
 8163: 
 8164: # print page header
 8165:     $r->print(&header($jscript,$args));
 8166: 
 8167: # early out unless log data can be displayed.
 8168:     unless ($permission->{'activity'}) {
 8169:         $r->print('<p class="LC_warning">'
 8170:                  .&mt('You do not have rights to display user access logs.')
 8171:                  .'</p>');
 8172:         if ($env{'form.popup'}) {
 8173:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8174:         } else {
 8175:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8176:         }
 8177:         return;
 8178:     }
 8179: 
 8180:     unless ($udom eq $env{'request.role.domain'}) {
 8181:         $r->print('<p class="LC_warning">'
 8182:                  .&mt("User's domain must match role's domain")
 8183:                  .'</p>'
 8184:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8185:         return;
 8186:     }
 8187: 
 8188:     if (($uname eq '') || ($udom eq '')) {
 8189:         $r->print('<p class="LC_warning">'
 8190:                  .&mt('Invalid username or domain')
 8191:                  .'</p>'
 8192:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8193:         return;
 8194:     }
 8195: 
 8196:     if (&Apache::lonnet::privileged($uname,$udom,
 8197:                                     [$env{'request.role.domain'}],['dc','su'])) {
 8198:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 8199:                                             [$env{'request.role.domain'}],['dc','su'])) {
 8200:             $r->print('<p class="LC_warning">'
 8201:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 8202:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 8203:                                                          $uname,$udom))
 8204:                  .'</p>');
 8205:             if ($env{'form.popup'}) {
 8206:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8207:             } else {
 8208:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8209:             }
 8210:             return;
 8211:         }
 8212:     }
 8213: 
 8214: # set defaults
 8215:     my $now = time();
 8216:     my $defstart = $now - (7*24*3600);
 8217:     my %defaults = (
 8218:                      page                 => '1',
 8219:                      show                 => '10',
 8220:                      activity             => 'any',
 8221:                      accesslog_start_date => $defstart,
 8222:                      accesslog_end_date   => $now,
 8223:                    );
 8224:     my $more_records = 0;
 8225: 
 8226: # set current
 8227:     my %curr;
 8228:     foreach my $item ('show','page','activity') {
 8229:         $curr{$item} = $env{'form.'.$item};
 8230:     }
 8231:     my ($startdate,$enddate) =
 8232:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 8233:     $curr{'accesslog_start_date'} = $startdate;
 8234:     $curr{'accesslog_end_date'} = $enddate;
 8235:     foreach my $key (keys(%defaults)) {
 8236:         if ($curr{$key} eq '') {
 8237:             $curr{$key} = $defaults{$key};
 8238:         }
 8239:     }
 8240:     my ($minshown,$maxshown);
 8241:     $minshown = 1;
 8242:     my $count = 0;
 8243:     if ($curr{'show'} =~ /\D/) {
 8244:         $curr{'page'} = 1;
 8245:     } else {
 8246:         $maxshown = $curr{'page'} * $curr{'show'};
 8247:         if ($curr{'page'} > 1) {
 8248:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8249:         }
 8250:     }
 8251: 
 8252: # form header
 8253:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8254:               &activity_display_filter($formname,\%curr));
 8255: 
 8256:     my $showntableheader = 0;
 8257:     my ($nav_script,$nav_links);
 8258: 
 8259: # table header
 8260:     my $heading = '<h3>'.
 8261:         &mt('User access logs for: [_1]',
 8262:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 8263:     my $tableheader = $heading
 8264:        .&Apache::loncommon::start_data_table_header_row()
 8265:        .'<th>&nbsp;</th>'
 8266:        .'<th>'.&mt('When').'</th>'
 8267:        .'<th>'.&mt('HostID').'</th>'
 8268:        .'<th>'.&mt('Event').'</th>'
 8269:        .'<th>'.&mt('Other data').'</th>'
 8270:        .&Apache::loncommon::end_data_table_header_row();
 8271: 
 8272:     my %filters=(
 8273:         start  => $curr{'accesslog_start_date'},
 8274:         end    => $curr{'accesslog_end_date'},
 8275:         action => $curr{'activity'},
 8276:     );
 8277: 
 8278:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 8279:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8280:         my (%courses,%missing);
 8281:         my @results = split(/\&/,$reply);
 8282:         foreach my $item (reverse(@results)) {
 8283:             my ($timestamp,$host,$event) = split(/:/,$item);
 8284:             next unless ($event =~ /^(Log|Role)/);
 8285:             if ($curr{'show'} !~ /\D/) {
 8286:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 8287:                     $more_records = 1;
 8288:                     last;
 8289:                 }
 8290:             }
 8291:             $count ++;
 8292:             next if ($count < $minshown);
 8293:             unless ($showntableheader) {
 8294:                 $r->print($nav_script
 8295:                          .&Apache::loncommon::start_data_table()
 8296:                          .$tableheader);
 8297:                 $r->rflush();
 8298:                 $showntableheader = 1;
 8299:             }
 8300:             my ($shown,$extra);
 8301:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 8302:             if ($event eq 'Role') {
 8303:                 my ($rolecode,$extent) = split(/\./,$data,2);
 8304:                 next if ($extent eq '');
 8305:                 my ($crstype,$desc,$info);
 8306:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 8307:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 8308:                     my $cid = $cdom.'_'.$cnum;
 8309:                     if (exists($courses{$cid})) {
 8310:                         $crstype = $courses{$cid}{'type'};
 8311:                         $desc = $courses{$cid}{'description'};
 8312:                     } elsif ($missing{$cid}) {
 8313:                         $crstype = 'Course';
 8314:                         $desc = 'Course/Community';
 8315:                     } else {
 8316:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8317:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 8318:                             $courses{$cid} = $crsinfo{$cid};
 8319:                             $crstype = $crsinfo{$cid}{'type'};
 8320:                             $desc = $crsinfo{$cid}{'description'};
 8321:                         } else {
 8322:                             $missing{$cid} = 1;
 8323:                         }
 8324:                     }
 8325:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 8326:                     if ($sec ne '') {
 8327:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 8328:                     }
 8329:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 8330:                     my ($dom,$name) = ($1,$2);
 8331:                     if ($rolecode eq 'au') {
 8332:                         $extra = '';
 8333:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 8334:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 8335:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 8336:                         $extra = &mt('Domain: [_1]',$dom);
 8337:                     }
 8338:                 }
 8339:                 my $rolename;
 8340:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 8341:                     my $role = $3;
 8342:                     my $owner = "($2:$1)";
 8343:                     if ($2 eq $1.'-domainconfig') {
 8344:                         $owner = '(ad hoc)';
 8345:                     }
 8346:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 8347:                 } else {
 8348:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 8349:                 }
 8350:                 $shown = &mt('Role selection: [_1]',$rolename);
 8351:             } else {
 8352:                 $shown = &mt($event);
 8353:                 if ($data =~ /^webdav/) {
 8354:                     my ($path,$clientip) = split(/\s+/,$data,2);
 8355:                     $path =~ s/^webdav//;
 8356:                     if ($clientip ne '') {
 8357:                         $extra = &mt('Client IP address: [_1]',$clientip);
 8358:                     }
 8359:                     if ($path ne '') {
 8360:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 8361:                     }
 8362:                 } elsif ($data ne '') {
 8363:                     $extra = &mt('Client IP address: [_1]',$data);
 8364:                 }
 8365:             }
 8366:             $r->print(
 8367:             &Apache::loncommon::start_data_table_row()
 8368:            .'<td>'.$count.'</td>'
 8369:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 8370:            .'<td>'.$host.'</td>'
 8371:            .'<td>'.$shown.'</td>'
 8372:            .'<td>'.$extra.'</td>'
 8373:            .&Apache::loncommon::end_data_table_row()."\n");
 8374:         }
 8375:     }
 8376: 
 8377:     if ($showntableheader) { # Table footer, if content displayed above
 8378:         $r->print(&Apache::loncommon::end_data_table().
 8379:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8380:     } else { # No content displayed above
 8381:         $r->print($heading.'<p class="LC_info">'
 8382:                  .&mt('There are no records to display.')
 8383:                  .'</p>');
 8384:     }
 8385: 
 8386:     if ($env{'form.popup'} == 1) {
 8387:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 8388:     }
 8389: 
 8390:     # Form Footer
 8391:     $r->print(
 8392:         '<input type="hidden" name="currstate" value="" />'
 8393:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 8394:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 8395:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8396:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 8397:        .'<input type="hidden" name="phase" value="activity" />'
 8398:        .'<input type="hidden" name="action" value="accesslogs" />'
 8399:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 8400:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 8401:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 8402:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 8403:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 8404:        .'</form>');
 8405:     return;
 8406: }
 8407: 
 8408: sub earlyout_accesslog_form {
 8409:     my ($formname,$prevphasestr,$udom) = @_;
 8410:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 8411:    return <<"END";
 8412: <form action="/adm/createuser" method="post" name="$formname">
 8413: <input type="hidden" name="currstate" value="" />
 8414: <input type="hidden" name="prevphases" value="$prevphasestr" />
 8415: <input type="hidden" name="phase" value="activity" />
 8416: <input type="hidden" name="action" value="accesslogs" />
 8417: <input type="hidden" name="srchdomain" value="$udom" />
 8418: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 8419: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 8420: <input type="hidden" name="srchterm" value="$srchterm" />
 8421: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 8422: </form>
 8423: END
 8424: }
 8425: 
 8426: sub activity_display_filter {
 8427:     my ($formname,$curr) = @_;
 8428:     my $nolink = 1;
 8429:     my $output = '<table><tr><td valign="top">'.
 8430:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 8431:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8432:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8433:                  '</td><td>&nbsp;&nbsp;</td>';
 8434:     my $startform =
 8435:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 8436:                                             $curr->{'accesslog_start_date'},undef,
 8437:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8438:     my $endform =
 8439:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 8440:                                             $curr->{'accesslog_end_date'},undef,
 8441:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8442:     my %lt = &Apache::lonlocal::texthash (
 8443:                                           activity => 'Activity',
 8444:                                           Role     => 'Role selection',
 8445:                                           log      => 'Log-in or Logout',
 8446:     );
 8447:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 8448:                '<table><tr><td>'.&mt('After:').
 8449:                '</td><td>'.$startform.'</td></tr>'.
 8450:                '<tr><td>'.&mt('Before:').'</td>'.
 8451:                '<td>'.$endform.'</td></tr></table>'.
 8452:                '</td>'.
 8453:                '<td>&nbsp;&nbsp;</td>'.
 8454:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 8455:                '<select name="activity"><option value="any"';
 8456:     if ($curr->{'activity'} eq 'any') {
 8457:         $output .= ' selected="selected"';
 8458:     }
 8459:     $output .= '>'.&mt('Any').'</option>'."\n";
 8460:     foreach my $activity ('Role','log') {
 8461:         my $selstr = '';
 8462:         if ($activity eq $curr->{'activity'}) {
 8463:             $selstr = ' selected="selected"';
 8464:         }
 8465:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 8466:     }
 8467:     $output .= '</select></td>'.
 8468:                '</tr></table>';
 8469:     # Update Display button
 8470:     $output .= '<p>'
 8471:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8472:               .'</p><hr />';
 8473:     return $output;
 8474: }
 8475: 
 8476: sub userlogdisplay_js {
 8477:     my ($formname) = @_;
 8478:     return <<"ENDSCRIPT";
 8479: 
 8480: function chgPage(caller) {
 8481:     if (caller == 'previous') {
 8482:         document.$formname.page.value --;
 8483:     }
 8484:     if (caller == 'next') {
 8485:         document.$formname.page.value ++;
 8486:     }
 8487:     document.$formname.submit();
 8488:     return;
 8489: }
 8490: ENDSCRIPT
 8491: }
 8492: 
 8493: sub userlogdisplay_navlinks {
 8494:     my ($curr,$more_records) = @_;
 8495:     return unless(ref($curr) eq 'HASH');
 8496:     # Navigation Buttons
 8497:     my $nav_links = '<p>';
 8498:     if (($curr->{'page'} > 1) || ($more_records)) {
 8499:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 8500:             $nav_links .= '<input type="button"'
 8501:                          .' onclick="javascript:chgPage('."'previous'".');"'
 8502:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 8503:                          .'" /> ';
 8504:         }
 8505:         if ($more_records) {
 8506:             $nav_links .= '<input type="button"'
 8507:                          .' onclick="javascript:chgPage('."'next'".');"'
 8508:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 8509:                          .'" />';
 8510:         }
 8511:     }
 8512:     $nav_links .= '</p>';
 8513:     return $nav_links;
 8514: }
 8515: 
 8516: sub role_display_filter {
 8517:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 8518:     my $nolink = 1;
 8519:     my $output = '<table><tr><td valign="top">'.
 8520:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 8521:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8522:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8523:                  '</td><td>&nbsp;&nbsp;</td>';
 8524:     my $startform =
 8525:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 8526:                                             $curr->{'rolelog_start_date'},undef,
 8527:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8528:     my $endform =
 8529:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 8530:                                             $curr->{'rolelog_end_date'},undef,
 8531:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8532:     my %lt = &rolechg_contexts($context,$crstype);
 8533:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 8534:                '<table><tr><td>'.&mt('After:').
 8535:                '</td><td>'.$startform.'</td></tr>'.
 8536:                '<tr><td>'.&mt('Before:').'</td>'.
 8537:                '<td>'.$endform.'</td></tr></table>'.
 8538:                '</td>'.
 8539:                '<td>&nbsp;&nbsp;</td>'.
 8540:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 8541:                '<select name="role"><option value="any"';
 8542:     if ($curr->{'role'} eq 'any') {
 8543:         $output .= ' selected="selected"';
 8544:     }
 8545:     $output .= '>'.&mt('Any').'</option>'."\n";
 8546:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 8547:     foreach my $role (@roles) {
 8548:         my $plrole;
 8549:         if ($role eq 'cr') {
 8550:             $plrole = &mt('Custom Role');
 8551:         } else {
 8552:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8553:         }
 8554:         my $selstr = '';
 8555:         if ($role eq $curr->{'role'}) {
 8556:             $selstr = ' selected="selected"';
 8557:         }
 8558:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 8559:     }
 8560:     $output .= '</select></td>'.
 8561:                '<td>&nbsp;&nbsp;</td>'.
 8562:                '<td valign="top"><b>'.
 8563:                &mt('Context:').'</b><br /><select name="chgcontext">';
 8564:     my @posscontexts;
 8565:     if ($context eq 'course') {
 8566:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype','ltienroll');
 8567:     } elsif ($context eq 'domain') {
 8568:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 8569:     } else {
 8570:         @posscontexts = ('any','author','coauthor','domain');
 8571:     }
 8572:     foreach my $chgtype (@posscontexts) {
 8573:         my $selstr = '';
 8574:         if ($curr->{'chgcontext'} eq $chgtype) {
 8575:             $selstr = ' selected="selected"';
 8576:         }
 8577:         if ($context eq 'course') {
 8578:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 8579:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 8580:             }
 8581:         }
 8582:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 8583:     }
 8584:     my @possapprovals = ('any','none','domain','user');
 8585:     my %apptxt = &approval_types();
 8586:     $output .= '</select></td>'.
 8587:                '<td>&nbsp;&nbsp;</td>'.
 8588:                '<td valign="top"><b>'.
 8589:                &mt('Approvals:').'</b><br /><select name="approvals">';
 8590:     foreach my $approval (@possapprovals) {
 8591:         my $selstr = '';
 8592:         if ($curr->{'approvals'} eq $approval) {
 8593:             $selstr = ' selected="selected"';
 8594:         }    
 8595:         $output .= '<option value="'.$approval.'"'.$selstr.'>'.$apptxt{$approval}.'</option>';
 8596:     }
 8597:     $output .= '</select></td></tr></table>';
 8598: 
 8599:     # Update Display button
 8600:     $output .= '<p>'
 8601:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8602:               .'</p>';
 8603: 
 8604:     # Server version info
 8605:     my $needsrev = '2.11.0';
 8606:     if ($context eq 'course') {
 8607:         $needsrev = '2.7.0';
 8608:     }
 8609:     
 8610:     $output .= '<p class="LC_info">'
 8611:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 8612:                   ,$needsrev);
 8613:     if ($version) {
 8614:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 8615:     }
 8616:     $output .= '</p><hr />';
 8617:     return $output;
 8618: }
 8619: 
 8620: sub rolechg_contexts {
 8621:     my ($context,$crstype) = @_;
 8622:     my %lt;
 8623:     if ($context eq 'course') {
 8624:         %lt = &Apache::lonlocal::texthash (
 8625:                                              any          => 'Any',
 8626:                                              automated    => 'Automated Enrollment',
 8627:                                              chgtype      => 'Enrollment Type/Lock Change',
 8628:                                              updatenow    => 'Roster Update',
 8629:                                              createcourse => 'Course Creation',
 8630:                                              course       => 'User Management in course',
 8631:                                              domain       => 'User Management in domain',
 8632:                                              selfenroll   => 'Self-enrolled',
 8633:                                              requestcourses => 'Course Request',
 8634:                                              ltienroll    => 'Enrollment via LTI',
 8635:                                          );
 8636:         if ($crstype eq 'Community') {
 8637:             $lt{'createcourse'} = &mt('Community Creation');
 8638:             $lt{'course'} = &mt('User Management in community');
 8639:             $lt{'requestcourses'} = &mt('Community Request');
 8640:         }
 8641:     } elsif ($context eq 'domain') {
 8642:         %lt = &Apache::lonlocal::texthash (
 8643:                                              any           => 'Any',
 8644:                                              domain        => 'User Management in domain',
 8645:                                              requestauthor => 'Authoring Request',
 8646:                                              server        => 'Command line script (DC role)',
 8647:                                              domconfig     => 'Self-enrolled',
 8648:                                          );
 8649:     } else {
 8650:         %lt = &Apache::lonlocal::texthash (
 8651:                                              any    => 'Any',
 8652:                                              domain => 'User Management in domain',
 8653:                                              author => 'User Management by author',
 8654:                                              coauthor => 'User Management by coauthor',
 8655:                                          );
 8656:     } 
 8657:     return %lt;
 8658: }
 8659: 
 8660: sub approval_types {
 8661:     return &Apache::lonlocal::texthash (
 8662:                                           any => 'Any',
 8663:                                           none => 'No approval needed',
 8664:                                           user => 'Role recipient approval',
 8665:                                           domain => 'Domain coordinator approval',
 8666:                                        );
 8667: }
 8668: 
 8669: sub print_helpdeskaccess_display {
 8670:     my ($r,$permission,$brcrum) = @_;
 8671:     my $formname = 'helpdeskaccess';
 8672:     my $helpitem = 'Course_Helpdesk_Access';
 8673:     push (@{$brcrum},
 8674:              {href => '/adm/createuser?action=helpdesk',
 8675:               text => 'Helpdesk Access',
 8676:               help => $helpitem});
 8677:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8678:     my $args = { bread_crumbs           => $brcrum,
 8679:                  bread_crumbs_component => $bread_crumbs_component};
 8680: 
 8681:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8682:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8683:     my $confname = $cdom.'-domainconfig';
 8684:     my $crstype = &Apache::loncommon::course_type();
 8685: 
 8686:     my @accesstypes = ('all','dh','da','none');
 8687:     my ($numstatustypes,@jsarray);
 8688:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8689:     if (ref($types) eq 'ARRAY') {
 8690:         if (@{$types} > 0) {
 8691:             $numstatustypes = scalar(@{$types});
 8692:             push(@accesstypes,'status');
 8693:             @jsarray = ('bystatus');
 8694:         }
 8695:     }
 8696:     my %customroles = &get_domain_customroles($cdom,$confname);
 8697:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8698:     if (keys(%domhelpdesk)) {
 8699:        push(@accesstypes,('inc','exc'));
 8700:        push(@jsarray,('notinc','notexc'));
 8701:     }
 8702:     push(@jsarray,'privs');
 8703:     my $hiddenstr = join("','",@jsarray);
 8704:     my $rolestr = join("','",sort(keys(%customroles)));
 8705: 
 8706:     my $jscript;
 8707:     my (%settings,%overridden);
 8708:     if (keys(%customroles)) {
 8709:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8710:                                 $types,\%customroles,\%settings,\%overridden);
 8711:         my %jsfull=();
 8712:         my %jslevels= (
 8713:                      course => {},
 8714:                      domain => {},
 8715:                      system => {},
 8716:                     );
 8717:         my %jslevelscurrent=(
 8718:                            course => {},
 8719:                            domain => {},
 8720:                            system => {},
 8721:                           );
 8722:         my (%privs,%jsprivs);
 8723:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 8724:         foreach my $priv (keys(%jsfull)) {
 8725:             if ($jslevels{'course'}{$priv}) {
 8726:                 $jsprivs{$priv} = 1;
 8727:             }
 8728:         }
 8729:         my (%elements,%stored);
 8730:         foreach my $role (keys(%customroles)) {
 8731:             $elements{$role.'_access'} = 'radio';
 8732:             $elements{$role.'_incrs'} = 'radio';
 8733:             if ($numstatustypes) {
 8734:                 $elements{$role.'_status'} = 'checkbox';
 8735:             }
 8736:             if (keys(%domhelpdesk) > 0) {
 8737:                 $elements{$role.'_staff_inc'} = 'checkbox';
 8738:                 $elements{$role.'_staff_exc'} = 'checkbox';
 8739:             }
 8740:             $elements{$role.'_override'} = 'checkbox';
 8741:             if (ref($settings{$role}) eq 'HASH') {
 8742:                 if ($settings{$role}{'access'} ne '') {
 8743:                     my $curraccess = $settings{$role}{'access'};
 8744:                     $stored{$role.'_access'} = $curraccess;
 8745:                     $stored{$role.'_incrs'} = 1;
 8746:                     if ($curraccess eq 'status') {
 8747:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 8748:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 8749:                         }
 8750:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8751:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 8752:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 8753:                         }
 8754:                     }
 8755:                 } else {
 8756:                     $stored{$role.'_incrs'} = 0;
 8757:                 }
 8758:                 $stored{$role.'_override'} = [];
 8759:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 8760:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 8761:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 8762:                             push(@{$stored{$role.'_override'}},$priv);
 8763:                         }
 8764:                     }
 8765:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 8766:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 8767:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 8768:                                 push(@{$stored{$role.'_override'}},$priv);
 8769:                             }
 8770:                         }
 8771:                     }
 8772:                 }
 8773:             } else {
 8774:                 $stored{$role.'_incrs'} = 0;
 8775:             }
 8776:         }
 8777:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 8778:     }
 8779: 
 8780:     my $js = <<"ENDJS";
 8781: <script type="text/javascript">
 8782: // <![CDATA[
 8783: $jscript;
 8784: 
 8785: function switchRoleTab(caller,role) {
 8786:     if (document.getElementById(role+'_maindiv')) {
 8787:         if (caller.id != 'LC_current_minitab') {
 8788:             if (document.getElementById('LC_current_minitab')) {
 8789:                 document.getElementById('LC_current_minitab').id=null;
 8790:             }
 8791:             var roledivs = Array('$rolestr');
 8792:             if (roledivs.length > 0) {
 8793:                 for (var i=0; i<roledivs.length; i++) {
 8794:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 8795:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 8796:                     }
 8797:                 }
 8798:             }
 8799:             caller.id = 'LC_current_minitab';
 8800:             document.getElementById(role+'_maindiv').style.display='block';
 8801:         }
 8802:     }
 8803:     return false;
 8804: }
 8805: 
 8806: function helpdeskAccess(role) {
 8807:     var curraccess = null;
 8808:     if (document.$formname.elements[role+'_access'].length) {
 8809:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 8810:             if (document.$formname.elements[role+'_access'][i].checked) {
 8811:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 8812:             }
 8813:         }
 8814:     }
 8815:     var shown = Array();
 8816:     var hidden = Array();
 8817:     if (curraccess == 'none') {
 8818:         hidden = Array ('$hiddenstr');
 8819:     } else {
 8820:         if (curraccess == 'status') {
 8821:             shown = Array ('bystatus','privs');
 8822:             hidden = Array ('notinc','notexc');
 8823:         } else {
 8824:             if (curraccess == 'exc') {
 8825:                 shown = Array ('notexc','privs');
 8826:                 hidden = Array ('notinc','bystatus');
 8827:             }
 8828:             if (curraccess == 'inc') {
 8829:                 shown = Array ('notinc','privs');
 8830:                 hidden = Array ('notexc','bystatus');
 8831:             }
 8832:             if (curraccess == 'all') {
 8833:                 shown = Array ('privs');
 8834:                 hidden = Array ('notinc','notexc','bystatus');
 8835:             }
 8836:         }
 8837:     }
 8838:     if (hidden.length > 0) {
 8839:         for (var i=0; i<hidden.length; i++) {
 8840:             if (document.getElementById(role+'_'+hidden[i])) {
 8841:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 8842:             }
 8843:         }
 8844:     }
 8845:     if (shown.length > 0) {
 8846:         for (var i=0; i<shown.length; i++) {
 8847:             if (document.getElementById(role+'_'+shown[i])) {
 8848:                 if (shown[i] == 'privs') {
 8849:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 8850:                 } else {
 8851:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 8852:                 }
 8853:             }
 8854:         }
 8855:     }
 8856:     return;
 8857: }
 8858: 
 8859: function toggleAccess(role) {
 8860:     if ((document.getElementById(role+'_setincrs')) &&
 8861:         (document.getElementById(role+'_setindom'))) {
 8862:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 8863:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 8864:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 8865:                     document.getElementById(role+'_setindom').style.display = 'none';
 8866:                     document.getElementById(role+'_setincrs').style.display = 'block';
 8867:                 } else {
 8868:                     document.getElementById(role+'_setincrs').style.display = 'none';
 8869:                     document.getElementById(role+'_setindom').style.display = 'block';
 8870:                 }
 8871:                 break;
 8872:             }
 8873:         }
 8874:     }
 8875:     return;
 8876: }
 8877: 
 8878: // ]]>
 8879: </script>
 8880: ENDJS
 8881: 
 8882:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 8883: 
 8884:     # print page header
 8885:     $r->print(&header($js,$args));
 8886:     # print form header
 8887:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 8888: 
 8889:     if (keys(%customroles)) {
 8890:         my %lt = &Apache::lonlocal::texthash(
 8891:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 8892:                     'rou'    => 'Role usage',
 8893:                     'whi'    => 'Which helpdesk personnel may use this role?',
 8894:                     'udd'    => 'Use domain default',
 8895:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 8896:                     'dh'     => 'All with domain helpdesk role',
 8897:                     'da'     => 'All with domain helpdesk assistant role',
 8898:                     'none'   => 'None',
 8899:                     'status' => 'Determined based on institutional status',
 8900:                     'inc'    => 'Include all, but exclude specific personnel',
 8901:                     'exc'    => 'Exclude all, but include specific personnel',
 8902:                     'hel'    => 'Helpdesk',
 8903:                     'rpr'    => 'Role privileges',
 8904:                  );
 8905:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 8906:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8907:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 8908:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8909:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8910:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8911:             }
 8912:         }
 8913:         my $count = 0;
 8914:         foreach my $role (sort(keys(%customroles))) {
 8915:             my ($order,$desc,$access_in_dom);
 8916:             if (ref($domcurrent{$role}) eq 'HASH') {
 8917:                 $order = $domcurrent{$role}{'order'};
 8918:                 $desc = $domcurrent{$role}{'desc'};
 8919:                 $access_in_dom = $domcurrent{$role}{'access'};
 8920:             }
 8921:             if ($order eq '') {
 8922:                 $order = $count;
 8923:             }
 8924:             $ordered{$order} = $role;
 8925:             if ($desc ne '') {
 8926:                 $description{$role} = $desc;
 8927:             } else {
 8928:                 $description{$role}= $role;
 8929:             }
 8930:             $count++;
 8931:         }
 8932:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8933:         my @roles_by_num = ();
 8934:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8935:             push(@roles_by_num,$ordered{$item});
 8936:         }
 8937:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 8938:         if ($permission->{'owner'}) {
 8939:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 8940:             $r->print('<input type="hidden" name="state" value="process" />'.
 8941:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 8942:         } else {
 8943:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 8944:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 8945:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 8946:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 8947:             }
 8948:             $disabled = ' disabled="disabled"';
 8949:         }
 8950:         $r->print('</p>');
 8951: 
 8952:         $r->print('<div id="LC_minitab_header"><ul>');
 8953:         my $count = 0;
 8954:         my %visibility;
 8955:         foreach my $role (@roles_by_num) {
 8956:             my $id;
 8957:             if ($count == 0) {
 8958:                 $id=' id="LC_current_minitab"';
 8959:                 $visibility{$role} = ' style="display:block"';
 8960:             } else {
 8961:                 $visibility{$role} = ' style="display:none"';
 8962:             }
 8963:             $count ++;
 8964:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 8965:         }
 8966:         $r->print('</ul></div>');
 8967: 
 8968:         foreach my $role (@roles_by_num) {
 8969:             my %usecheck = (
 8970:                              all => ' checked="checked"',
 8971:                            );
 8972:             my %displaydiv = (
 8973:                                 status => 'none',
 8974:                                 inc    => 'none',
 8975:                                 exc    => 'none',
 8976:                                 priv   => 'block',
 8977:                              );
 8978:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 8979:             if (ref($settings{$role}) eq 'HASH') {
 8980:                 if ($settings{$role}{'access'} ne '') {
 8981:                     $indomvis = ' style="display:none"';
 8982:                     $incrsvis = ' style="display:block"';
 8983:                     $incrscheck = ' checked="checked"';
 8984:                     if ($settings{$role}{'access'} ne 'all') {
 8985:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 8986:                         delete($usecheck{'all'});
 8987:                         if ($settings{$role}{'access'} eq 'status') {
 8988:                             my $access = 'status';
 8989:                             $displaydiv{$access} = 'inline';
 8990:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 8991:                                 $selected{$access} = $settings{$role}{$access};
 8992:                             }
 8993:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 8994:                             my $access = $1;
 8995:                             $displaydiv{$access} = 'inline';
 8996:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 8997:                                 $selected{$access} = $settings{$role}{$access};
 8998:                             }
 8999:                         } elsif ($settings{$role}{'access'} eq 'none') {
 9000:                             $displaydiv{'priv'} = 'none';
 9001:                         }
 9002:                     }
 9003:                 } else {
 9004:                     $indomcheck = ' checked="checked"';
 9005:                     $indomvis = ' style="display:block"';
 9006:                     $incrsvis = ' style="display:none"';
 9007:                 }
 9008:             } else {
 9009:                 $indomcheck = ' checked="checked"';
 9010:                 $indomvis = ' style="display:block"';
 9011:                 $incrsvis = ' style="display:none"';
 9012:             }
 9013:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 9014:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 9015:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 9016:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9017:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 9018:                       '<span>'.('&nbsp;'x2).
 9019:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9020:                       $lt{'udd'}.'</label><span></p>'.
 9021:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 9022:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 9023:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 9024:             foreach my $access (@accesstypes) {
 9025:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 9026:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 9027:                 if ($access eq 'status') {
 9028:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 9029:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 9030:                                                                         $othertitle,$usertypes,$types,$disabled).
 9031:                               '</div>');
 9032:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 9033:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 9034:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9035:                                                                  \%domhelpdesk,$disabled).
 9036:                               '</div>');
 9037:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 9038:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 9039:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9040:                                                                  \%domhelpdesk,$disabled).
 9041:                               '</div>');
 9042:                 }
 9043:                 $r->print('</p>');
 9044:             }
 9045:             $r->print('</div></fieldset>');
 9046:             my %full=();
 9047:             my %levels= (
 9048:                          course => {},
 9049:                          domain => {},
 9050:                          system => {},
 9051:                         );
 9052:             my %levelscurrent=(
 9053:                                course => {},
 9054:                                domain => {},
 9055:                                system => {},
 9056:                               );
 9057:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9058:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 9059:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 9060:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 9061:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 9062:         }
 9063:         if ($permission->{'owner'}) {
 9064:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 9065:         }
 9066:     } else {
 9067:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 9068:     }
 9069:     # Form Footer
 9070:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 9071:              .'</form>');
 9072:     return;
 9073: }
 9074: 
 9075: sub print_queued_roles {
 9076:     my ($r,$context,$permission,$brcrum) = @_;
 9077:     push (@{$brcrum},
 9078:              {href => '/adm/createuser?action=rolerequests',
 9079:               text => 'Role Requests (other domains)',
 9080:               help => ''});
 9081:     my $bread_crumbs_component = 'Role Requests';
 9082:     my $args = { bread_crumbs           => $brcrum,
 9083:                  bread_crumbs_component => $bread_crumbs_component};
 9084:     # print page header
 9085:     $r->print(&header('',$args));
 9086:     my ($dom,$cnum);
 9087:     $dom = $env{'request.role.domain'};
 9088:     if ($context eq 'course') {
 9089:         if ($env{'request.course.id'}) {
 9090:             if (&Apache::loncommon::course_type() eq 'Community') {
 9091:                 $context = 'community';
 9092:             }
 9093:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9094:         }
 9095:     } elsif ($context eq 'author') {
 9096:         $cnum = $env{'user.name'};
 9097:     }
 9098:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomqueue',$dom,$cnum,$context));
 9099:     return;
 9100: }
 9101: 
 9102: sub print_pendingroles {
 9103:     my ($r,$context,$permission,$brcrum) = @_;
 9104:     push (@{$brcrum},
 9105:              {href => '/adm/createuser?action=queuedroles',
 9106:               text => 'Queued Role Assignments (users in this domain)',
 9107:               help => ''});
 9108:     my $bread_crumbs_component = 'Queued Role Assignments';
 9109:     my $args = { bread_crumbs           => $brcrum,
 9110:                  bread_crumbs_component => $bread_crumbs_component};
 9111:     # print page header
 9112:     $r->print(&header('',$args));
 9113:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomaction',$env{'request.role.domain'},'','domain'));
 9114:     return;
 9115: }
 9116: 
 9117: sub process_pendingroles {
 9118:     my ($r,$context,$permission,$brcrum) = @_;
 9119:     push (@{$brcrum},
 9120:              {href => '/adm/createuser?action=queuedroles',
 9121:               text => 'Queued Role Assignments (users in this domain)',
 9122:               help => ''},
 9123:              {href => '/adm/createuser?action=processrolereq',
 9124:               text => 'Process Queue',
 9125:               help => ''});
 9126:     my $bread_crumbs_component = 'Queued Role Assignments';
 9127:     my $args = { bread_crumbs           => $brcrum,
 9128:                  bread_crumbs_component => $bread_crumbs_component};
 9129:     # print page header
 9130:     $r->print(&header('',$args));
 9131:     $r->print(&Apache::loncoursequeueadmin::update_request_queue('othdombydc',
 9132:                                                                  $env{'request.role.domain'}));
 9133:     return;
 9134: }
 9135: 
 9136: sub domain_adhoc_access {
 9137:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 9138:     my %domusage;
 9139:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 9140:     foreach my $role (keys(%{$roles})) {
 9141:         if (ref($domcurrent->{$role}) eq 'HASH') {
 9142:             my $access = $domcurrent->{$role}{'access'};
 9143:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 9144:                 $access = 'all';
 9145:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 9146:                                                                                           &Apache::lonnet::plaintext('da'));
 9147:             } elsif ($access eq 'status') {
 9148:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 9149:                     my @shown;
 9150:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 9151:                         unless ($type eq 'default') {
 9152:                             if ($usertypes->{$type}) {
 9153:                                 push(@shown,$usertypes->{$type});
 9154:                             }
 9155:                         }
 9156:                     }
 9157:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 9158:                         push(@shown,$othertitle);
 9159:                     }
 9160:                     if (@shown) {
 9161:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 9162:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 9163:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 9164:                     } else {
 9165:                         $domusage{$role} = &mt('No one in the domain');
 9166:                     }
 9167:                 }
 9168:             } elsif ($access eq 'inc') {
 9169:                 my @dominc = ();
 9170:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 9171:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 9172:                         my ($uname,$udom) = split(/:/,$user);
 9173:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9174:                     }
 9175:                     my $showninc = join(', ',@dominc);
 9176:                     if ($showninc ne '') {
 9177:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 9178:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 9179:                     } else {
 9180:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9181:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9182:                     }
 9183:                 }
 9184:             } elsif ($access eq 'exc') {
 9185:                 my @domexc = ();
 9186:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 9187:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 9188:                         my ($uname,$udom) = split(/:/,$user);
 9189:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9190:                     }
 9191:                 }
 9192:                 my $shownexc = join(', ',@domexc);
 9193:                 if ($shownexc ne '') {
 9194:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 9195:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 9196:                 } else {
 9197:                     $domusage{$role} = &mt('No one in the domain');
 9198:                 }
 9199:             } elsif ($access eq 'none') {
 9200:                 $domusage{$role} = &mt('No one in the domain');
 9201:             } elsif ($access eq 'dh') {
 9202:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 9203:             } elsif ($access eq 'da') {
 9204:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 9205:             } elsif ($access eq 'all') {
 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:         } else {
 9210:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9211:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9212:         }
 9213:     }
 9214:     return %domusage;
 9215: }
 9216: 
 9217: sub get_domain_customroles {
 9218:     my ($cdom,$confname) = @_;
 9219:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 9220:     my %customroles;
 9221:     foreach my $key (keys(%existing)) {
 9222:         if ($key=~/^rolesdef\_(\w+)$/) {
 9223:             my $rolename = $1;
 9224:             my %privs;
 9225:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 9226:             $customroles{$rolename} = \%privs;
 9227:         }
 9228:     }
 9229:     return %customroles;
 9230: }
 9231: 
 9232: sub role_priv_table {
 9233:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 9234:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 9235:                    (ref($levelscurrent) eq 'HASH'));
 9236:     my %lt=&Apache::lonlocal::texthash (
 9237:                     'crl'  => 'Course Level Privilege',
 9238:                     'def'  => 'Domain Defaults',
 9239:                     'ove'  => 'Override in Course',
 9240:                     'ine'  => 'In effect',
 9241:                     'dis'  => 'Disabled',
 9242:                     'ena'  => 'Enabled',
 9243:                    );
 9244:     if ($crstype eq 'Community') {
 9245:         $lt{'ove'} = 'Override in Community',
 9246:     }
 9247:     my @status = ('Disabled','Enabled');
 9248:     my (%on,%off);
 9249:     if (ref($overridden) eq 'HASH') {
 9250:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 9251:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 9252:         }
 9253:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 9254:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 9255:         }
 9256:     }
 9257:     my $output=&Apache::loncommon::start_data_table().
 9258:                &Apache::loncommon::start_data_table_header_row().
 9259:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 9260:                '</th><th>'.$lt{'ine'}.'</th>'.
 9261:                &Apache::loncommon::end_data_table_header_row();
 9262:     foreach my $priv (sort(keys(%{$full}))) {
 9263:         next unless ($levels->{'course'}{$priv});
 9264:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 9265:         my ($default,$ineffect);
 9266:         if ($levelscurrent->{'course'}{$priv}) {
 9267:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9268:             $ineffect = $default;
 9269:         }
 9270:         my ($customstatus,$checked);
 9271:         $output .= &Apache::loncommon::start_data_table_row().
 9272:                    '<td>'.$privtext.'</td>'.
 9273:                    '<td>'.$default.'</td><td>';
 9274:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 9275:             if ($permission->{'owner'}) {
 9276:                 $checked = ' checked="checked"';
 9277:             }
 9278:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 9279:             $ineffect = $customstatus;
 9280:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 9281:             if ($permission->{'owner'}) {
 9282:                 $checked = ' checked="checked"';
 9283:             }
 9284:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9285:             $ineffect = $customstatus;
 9286:         }
 9287:         if ($permission->{'owner'}) {
 9288:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 9289:         } else {
 9290:             $output .= $customstatus;
 9291:         }
 9292:         $output .= '</td><td>'.$ineffect.'</td>'.
 9293:                    &Apache::loncommon::end_data_table_row();
 9294:     }
 9295:     $output .= &Apache::loncommon::end_data_table();
 9296:     return $output;
 9297: }
 9298: 
 9299: sub get_adhocrole_settings {
 9300:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 9301:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 9302:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 9303:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 9304:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 9305:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 9306:             $settings->{$role}{'access'} = $curraccess;
 9307:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 9308:                 my @status = split(/,/,$rest);
 9309:                 my @currstatus;
 9310:                 foreach my $type (@status) {
 9311:                     if ($type eq 'default') {
 9312:                         push(@currstatus,$type);
 9313:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9314:                         push(@currstatus,$type);
 9315:                     }
 9316:                 }
 9317:                 if (@currstatus) {
 9318:                     $settings->{$role}{$curraccess} = \@currstatus;
 9319:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 9320:                     my @personnel = split(/,/,$rest);
 9321:                     $settings->{$role}{$curraccess} = \@personnel;
 9322:                 }
 9323:             }
 9324:         }
 9325:     }
 9326:     foreach my $role (keys(%{$customroles})) {
 9327:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 9328:             my %currentprivs;
 9329:             if (ref($customroles->{$role}) eq 'HASH') {
 9330:                 if (exists($customroles->{$role}{'course'})) {
 9331:                     my %full=();
 9332:                     my %levels= (
 9333:                                   course => {},
 9334:                                   domain => {},
 9335:                                   system => {},
 9336:                                 );
 9337:                     my %levelscurrent=(
 9338:                                         course => {},
 9339:                                         domain => {},
 9340:                                         system => {},
 9341:                                       );
 9342:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 9343:                     %currentprivs = %{$levelscurrent{'course'}};
 9344:                 }
 9345:             }
 9346:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 9347:                 next if ($item eq '');
 9348:                 my ($rule,$rest) = split(/=/,$item);
 9349:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 9350:                 foreach my $priv (split(/:/,$rest)) {
 9351:                     if ($priv ne '') {
 9352:                         if ($rule eq 'off') {
 9353:                             push(@{$overridden->{$role}{'off'}},$priv);
 9354:                             if ($currentprivs{$priv}) {
 9355:                                 push(@{$settings->{$role}{'off'}},$priv);
 9356:                             }
 9357:                         } else {
 9358:                             push(@{$overridden->{$role}{'on'}},$priv);
 9359:                             unless ($currentprivs{$priv}) {
 9360:                                 push(@{$settings->{$role}{'on'}},$priv);
 9361:                             }
 9362:                         }
 9363:                     }
 9364:                 }
 9365:             }
 9366:         }
 9367:     }
 9368:     return;
 9369: }
 9370: 
 9371: sub update_helpdeskaccess {
 9372:     my ($r,$permission,$brcrum) = @_;
 9373:     my $helpitem = 'Course_Helpdesk_Access';
 9374:     push (@{$brcrum},
 9375:              {href => '/adm/createuser?action=helpdesk',
 9376:               text => 'Helpdesk Access',
 9377:               help => $helpitem},
 9378:              {href => '/adm/createuser?action=helpdesk',
 9379:               text => 'Result',
 9380:               help => $helpitem}
 9381:          );
 9382:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 9383:     my $args = { bread_crumbs           => $brcrum,
 9384:                  bread_crumbs_component => $bread_crumbs_component};
 9385: 
 9386:     # print page header
 9387:     $r->print(&header('',$args));
 9388:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 9389:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 9390:         return;
 9391:     }
 9392:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 9393:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9394:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9395:     my $confname = $cdom.'-domainconfig';
 9396:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 9397:     my $crstype = &Apache::loncommon::course_type();
 9398:     my %customroles = &get_domain_customroles($cdom,$confname);
 9399:     my (%settings,%overridden);
 9400:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 9401:                             $types,\%customroles,\%settings,\%overridden);
 9402:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 9403:     my (%changed,%storehash,@todelete);
 9404: 
 9405:     if (keys(%customroles)) {
 9406:         my (%newsettings,@incrs);
 9407:         foreach my $role (keys(%customroles)) {
 9408:             $newsettings{$role} = {
 9409:                                     access => '',
 9410:                                     status => '',
 9411:                                     exc    => '',
 9412:                                     inc    => '',
 9413:                                     on     => '',
 9414:                                     off    => '',
 9415:                                   };
 9416:             my %current;
 9417:             if (ref($settings{$role}) eq 'HASH') {
 9418:                 %current = %{$settings{$role}};
 9419:             }
 9420:             if (ref($overridden{$role}) eq 'HASH') {
 9421:                 $current{'overridden'} = $overridden{$role};
 9422:             }
 9423:             if ($env{'form.'.$role.'_incrs'}) {
 9424:                 my $access = $env{'form.'.$role.'_access'};
 9425:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 9426:                     push(@incrs,$role);
 9427:                     unless ($current{'access'} eq $access) {
 9428:                         $changed{$role}{'access'} = 1;
 9429:                         $storehash{'internal.adhoc.'.$role} = $access;
 9430:                     }
 9431:                     if ($access eq 'status') {
 9432:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 9433:                         my @stored;
 9434:                         my @shownstatus;
 9435:                         if (ref($types) eq 'ARRAY') {
 9436:                             foreach my $type (sort(@statuses)) {
 9437:                                 if ($type eq 'default') {
 9438:                                     push(@stored,$type);
 9439:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9440:                                     push(@stored,$type);
 9441:                                     push(@shownstatus,$usertypes->{$type});
 9442:                                 }
 9443:                             }
 9444:                             if (grep(/^default$/,@statuses)) {
 9445:                                 push(@shownstatus,$othertitle);
 9446:                             }
 9447:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9448:                         }
 9449:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 9450:                         if (ref($current{'status'}) eq 'ARRAY') {
 9451:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 9452:                             if (@diffs) {
 9453:                                 $changed{$role}{'status'} = 1;
 9454:                             }
 9455:                         } elsif (@stored) {
 9456:                             $changed{$role}{'status'} = 1;
 9457:                         }
 9458:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 9459:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 9460:                         my @newspecstaff;
 9461:                         my @stored;
 9462:                         my @currstaff;
 9463:                         foreach my $person (sort(@personnel)) {
 9464:                             if ($domhelpdesk{$person}) {
 9465:                                 push(@stored,$person);
 9466:                             }
 9467:                         }
 9468:                         if (ref($current{$access}) eq 'ARRAY') {
 9469:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 9470:                             if (@diffs) {
 9471:                                 $changed{$role}{$access} = 1;
 9472:                             }
 9473:                         } elsif (@stored) {
 9474:                             $changed{$role}{$access} = 1;
 9475:                         }
 9476:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9477:                         foreach my $person (@stored) {
 9478:                             my ($uname,$udom) = split(/:/,$person);
 9479:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 9480:                         }
 9481:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 9482:                     }
 9483:                     $newsettings{$role}{'access'} = $access;
 9484:                 }
 9485:             } else {
 9486:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 9487:                     $changed{$role}{'access'} = 1;
 9488:                     $newsettings{$role} = {};
 9489:                     push(@todelete,'internal.adhoc.'.$role);
 9490:                 }
 9491:             }
 9492:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 9493:                 if (ref($current{'overridden'}) eq 'HASH') {
 9494:                     push(@todelete,'internal.adhocpriv.'.$role);
 9495:                 }
 9496:             } else {
 9497:                 my %full=();
 9498:                 my %levels= (
 9499:                              course => {},
 9500:                              domain => {},
 9501:                              system => {},
 9502:                             );
 9503:                 my %levelscurrent=(
 9504:                                    course => {},
 9505:                                    domain => {},
 9506:                                    system => {},
 9507:                                   );
 9508:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9509:                 my (@updatedon,@updatedoff,@override);
 9510:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 9511:                 if (@override) {
 9512:                     foreach my $priv (sort(keys(%full))) {
 9513:                         next unless ($levels{'course'}{$priv});
 9514:                         if (grep(/^\Q$priv\E$/,@override)) {
 9515:                             if ($levelscurrent{'course'}{$priv}) {
 9516:                                 push(@updatedoff,$priv);
 9517:                             } else {
 9518:                                 push(@updatedon,$priv);
 9519:                             }
 9520:                         }
 9521:                     }
 9522:                 }
 9523:                 if (@updatedon) {
 9524:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 9525:                 }
 9526:                 if (@updatedoff) {
 9527:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 9528:                 }
 9529:                 if (ref($current{'overridden'}) eq 'HASH') {
 9530:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 9531:                         if (@updatedon) {
 9532:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 9533:                             if (@diffs) {
 9534:                                 $changed{$role}{'on'} = 1;
 9535:                             }
 9536:                         } else {
 9537:                             $changed{$role}{'on'} = 1;
 9538:                         }
 9539:                     } elsif (@updatedon) {
 9540:                         $changed{$role}{'on'} = 1;
 9541:                     }
 9542:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 9543:                         if (@updatedoff) {
 9544:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 9545:                             if (@diffs) {
 9546:                                 $changed{$role}{'off'} = 1;
 9547:                             }
 9548:                         } else {
 9549:                             $changed{$role}{'off'} = 1;
 9550:                         }
 9551:                     } elsif (@updatedoff) {
 9552:                         $changed{$role}{'off'} = 1;
 9553:                     }
 9554:                 } else {
 9555:                     if (@updatedon) {
 9556:                         $changed{$role}{'on'} = 1;
 9557:                     }
 9558:                     if (@updatedoff) {
 9559:                         $changed{$role}{'off'} = 1;
 9560:                     }
 9561:                 }
 9562:                 if (ref($changed{$role}) eq 'HASH') {
 9563:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 9564:                         my $newpriv;
 9565:                         if (@updatedon) {
 9566:                             $newpriv = 'on='.join(':',@updatedon);
 9567:                         }
 9568:                         if (@updatedoff) {
 9569:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 9570:                         }
 9571:                         if ($newpriv eq '') {
 9572:                             push(@todelete,'internal.adhocpriv.'.$role);
 9573:                         } else {
 9574:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 9575:                         }
 9576:                     }
 9577:                 }
 9578:             }
 9579:         }
 9580:         if (@incrs) {
 9581:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 9582:         } elsif (@todelete) {
 9583:             push(@todelete,'internal.adhocaccess');
 9584:         }
 9585:         if (keys(%changed)) {
 9586:             my ($putres,$delres);
 9587:             if (keys(%storehash)) {
 9588:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 9589:                 my %newenvhash;
 9590:                 foreach my $key (keys(%storehash)) {
 9591:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 9592:                 }
 9593:                 &Apache::lonnet::appenv(\%newenvhash);
 9594:             }
 9595:             if (@todelete) {
 9596:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 9597:                 foreach my $key (@todelete) {
 9598:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 9599:                 }
 9600:             }
 9601:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 9602:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9603:                 my (%domcurrent,%ordered,%description,%domusage);
 9604:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9605:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9606:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9607:                     }
 9608:                 }
 9609:                 my $count = 0;
 9610:                 foreach my $role (sort(keys(%customroles))) {
 9611:                     my ($order,$desc);
 9612:                     if (ref($domcurrent{$role}) eq 'HASH') {
 9613:                         $order = $domcurrent{$role}{'order'};
 9614:                         $desc = $domcurrent{$role}{'desc'};
 9615:                     }
 9616:                     if ($order eq '') {
 9617:                         $order = $count;
 9618:                     }
 9619:                     $ordered{$order} = $role;
 9620:                     if ($desc ne '') {
 9621:                         $description{$role} = $desc;
 9622:                     } else {
 9623:                         $description{$role}= $role;
 9624:                     }
 9625:                     $count++;
 9626:                 }
 9627:                 my @roles_by_num = ();
 9628:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9629:                     push(@roles_by_num,$ordered{$item});
 9630:                 }
 9631:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9632:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 9633:                 $r->print('<ul>');
 9634:                 foreach my $role (@roles_by_num) {
 9635:                     next unless (ref($changed{$role}) eq 'HASH');
 9636:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 9637:                               '<ul>');
 9638:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 9639:                         $r->print('<li>');
 9640:                         if ($env{'form.'.$role.'_incrs'}) {
 9641:                             if ($newsettings{$role}{'access'} eq 'all') {
 9642:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 9643:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 9644:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9645:                                               &Apache::lonnet::plaintext('dh')));
 9646:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 9647:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9648:                                               &Apache::lonnet::plaintext('da')));
 9649:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 9650:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9651:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 9652:                                 if ($newsettings{$role}{'status'}) {
 9653:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 9654:                                     if (split(/,/,$rest) > 1) {
 9655:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 9656:                                                       $newsettings{$role}{'status'}));
 9657:                                     } else {
 9658:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 9659:                                                       $newsettings{$role}{'status'}));
 9660:                                     }
 9661:                                 } else {
 9662:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9663:                                 }
 9664:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 9665:                                 if ($newsettings{$role}{'exc'}) {
 9666:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 9667:                                 } else {
 9668:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9669:                                 }
 9670:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 9671:                                 if ($newsettings{$role}{'inc'}) {
 9672:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 9673:                                 } else {
 9674:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 9675:                                 }
 9676:                             }
 9677:                         } else {
 9678:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 9679:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 9680:                         }
 9681:                         $r->print('</li>');
 9682:                     }
 9683:                     unless ($newsettings{$role}{'access'} eq 'none') {
 9684:                         if ($changed{$role}{'off'}) {
 9685:                             if ($newsettings{$role}{'off'}) {
 9686:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 9687:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 9688:                             } else {
 9689:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 9690:                             }
 9691:                         }
 9692:                         if ($changed{$role}{'on'}) {
 9693:                             if ($newsettings{$role}{'on'}) {
 9694:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 9695:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 9696:                             } else {
 9697:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 9698:                             }
 9699:                         }
 9700:                     }
 9701:                     $r->print('</ul></li>');
 9702:                 }
 9703:                 $r->print('</ul>');
 9704:             }
 9705:         } else {
 9706:             $r->print(&mt('No changes made to helpdesk access settings.'));
 9707:         }
 9708:     }
 9709:     return;
 9710: }
 9711: 
 9712: #-------------------------------------------------- functions for &phase_two
 9713: sub user_search_result {
 9714:     my ($context,$srch) = @_;
 9715:     my %allhomes;
 9716:     my %inst_matches;
 9717:     my %srch_results;
 9718:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 9719:     $srch->{'srchterm'} =~ s/\s+/ /g;
 9720:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 9721:         $response = &mt('Invalid search.');
 9722:     }
 9723:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 9724:         $response = &mt('Invalid search.');
 9725:     }
 9726:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 9727:         $response = &mt('Invalid search.');
 9728:     }
 9729:     if ($srch->{'srchterm'} eq '') {
 9730:         $response = &mt('You must enter a search term.');
 9731:     }
 9732:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 9733:         $response = &mt('Your search term must contain more than just spaces.');
 9734:     }
 9735:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 9736:         if (($srch->{'srchdomain'} eq '') || 
 9737: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 9738:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 9739:         }
 9740:     }
 9741:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 9742:         ($srch->{'srchin'} eq 'alc')) {
 9743:         if ($srch->{'srchby'} eq 'uname') {
 9744:             my $unamecheck = $srch->{'srchterm'};
 9745:             if ($srch->{'srchtype'} eq 'contains') {
 9746:                 if ($unamecheck !~ /^\w/) {
 9747:                     $unamecheck = 'a'.$unamecheck; 
 9748:                 }
 9749:             }
 9750:             if ($unamecheck !~ /^$match_username$/) {
 9751:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 9752:             }
 9753:         }
 9754:     }
 9755:     if ($response ne '') {
 9756:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 9757:     }
 9758:     if ($srch->{'srchin'} eq 'instd') {
 9759:         my $instd_chk = &instdirectorysrch_check($srch);
 9760:         if ($instd_chk ne 'ok') {
 9761:             my $domd_chk = &domdirectorysrch_check($srch);
 9762:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 9763:             if ($domd_chk eq 'ok') {
 9764:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 9765:             }
 9766:             $response .= '<br />';
 9767:         }
 9768:     } else {
 9769:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 9770:             my $domd_chk = &domdirectorysrch_check($srch);
 9771:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 9772:                 my $instd_chk = &instdirectorysrch_check($srch);
 9773:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 9774:                 if ($instd_chk eq 'ok') {
 9775:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 9776:                 }
 9777:                 $response .= '<br />';
 9778:             }
 9779:         }
 9780:     }
 9781:     if ($response ne '') {
 9782:         return ($currstate,$response);
 9783:     }
 9784:     if ($srch->{'srchby'} eq 'uname') {
 9785:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 9786:             if ($env{'form.forcenew'}) {
 9787:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 9788:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9789:                     if ($uhome eq 'no_host') {
 9790:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 9791:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 9792:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 9793:                     } else {
 9794:                         $currstate = 'modify';
 9795:                     }
 9796:                 } else {
 9797:                     $currstate = 'modify';
 9798:                 }
 9799:             } else {
 9800:                 if ($srch->{'srchin'} eq 'dom') {
 9801:                     if ($srch->{'srchtype'} eq 'exact') {
 9802:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9803:                         if ($uhome eq 'no_host') {
 9804:                             ($currstate,$response,$forcenewuser) =
 9805:                                 &build_search_response($context,$srch,%srch_results);
 9806:                         } else {
 9807:                             $currstate = 'modify';
 9808:                             if ($env{'form.action'} eq 'accesslogs') {
 9809:                                 $currstate = 'activity';
 9810:                             }
 9811:                             my $uname = $srch->{'srchterm'};
 9812:                             my $udom = $srch->{'srchdomain'};
 9813:                             $srch_results{$uname.':'.$udom} =
 9814:                                 { &Apache::lonnet::get('environment',
 9815:                                                        ['firstname',
 9816:                                                         'lastname',
 9817:                                                         'permanentemail'],
 9818:                                                          $udom,$uname)
 9819:                                 };
 9820:                         }
 9821:                     } else {
 9822:                         %srch_results = &Apache::lonnet::usersearch($srch);
 9823:                         ($currstate,$response,$forcenewuser) =
 9824:                             &build_search_response($context,$srch,%srch_results);
 9825:                     }
 9826:                 } else {
 9827:                     my $courseusers = &get_courseusers();
 9828:                     if ($srch->{'srchtype'} eq 'exact') {
 9829:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 9830:                             $currstate = 'modify';
 9831:                         } else {
 9832:                             ($currstate,$response,$forcenewuser) =
 9833:                                 &build_search_response($context,$srch,%srch_results);
 9834:                         }
 9835:                     } else {
 9836:                         foreach my $user (keys(%$courseusers)) {
 9837:                             my ($cuname,$cudomain) = split(/:/,$user);
 9838:                             if ($cudomain eq $srch->{'srchdomain'}) {
 9839:                                 my $matched = 0;
 9840:                                 if ($srch->{'srchtype'} eq 'begins') {
 9841:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 9842:                                         $matched = 1;
 9843:                                     }
 9844:                                 } else {
 9845:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 9846:                                         $matched = 1;
 9847:                                     }
 9848:                                 }
 9849:                                 if ($matched) {
 9850:                                     $srch_results{$user} = 
 9851: 					{&Apache::lonnet::get('environment',
 9852: 							     ['firstname',
 9853: 							      'lastname',
 9854: 							      'permanentemail'],
 9855: 							      $cudomain,$cuname)};
 9856:                                 }
 9857:                             }
 9858:                         }
 9859:                         ($currstate,$response,$forcenewuser) =
 9860:                             &build_search_response($context,$srch,%srch_results);
 9861:                     }
 9862:                 }
 9863:             }
 9864:         } elsif ($srch->{'srchin'} eq 'alc') {
 9865:             $currstate = 'query';
 9866:         } elsif ($srch->{'srchin'} eq 'instd') {
 9867:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 9868:             if ($dirsrchres eq 'ok') {
 9869:                 ($currstate,$response,$forcenewuser) = 
 9870:                     &build_search_response($context,$srch,%srch_results);
 9871:             } else {
 9872:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9873:                 $response = '<span class="LC_warning">'.
 9874:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9875:                     '</span><br />'.
 9876:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 9877:                     '<br />'; 
 9878:             }
 9879:         }
 9880:     } else {
 9881:         if ($srch->{'srchin'} eq 'dom') {
 9882:             %srch_results = &Apache::lonnet::usersearch($srch);
 9883:             ($currstate,$response,$forcenewuser) = 
 9884:                 &build_search_response($context,$srch,%srch_results); 
 9885:         } elsif ($srch->{'srchin'} eq 'crs') {
 9886:             my $courseusers = &get_courseusers(); 
 9887:             foreach my $user (keys(%$courseusers)) {
 9888:                 my ($uname,$udom) = split(/:/,$user);
 9889:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 9890:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 9891:                 if ($srch->{'srchby'} eq 'lastname') {
 9892:                     if ((($srch->{'srchtype'} eq 'exact') && 
 9893:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 9894:                         (($srch->{'srchtype'} eq 'begins') &&
 9895:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 9896:                         (($srch->{'srchtype'} eq 'contains') &&
 9897:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 9898:                         $srch_results{$user} = {firstname => $names{'firstname'},
 9899:                                             lastname => $names{'lastname'},
 9900:                                             permanentemail => $emails{'permanentemail'},
 9901:                                            };
 9902:                     }
 9903:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 9904:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 9905:                     $srchlast =~ s/\s+$//;
 9906:                     $srchfirst =~ s/^\s+//;
 9907:                     if ($srch->{'srchtype'} eq 'exact') {
 9908:                         if (($names{'lastname'} eq $srchlast) &&
 9909:                             ($names{'firstname'} eq $srchfirst)) {
 9910:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9911:                                                 lastname => $names{'lastname'},
 9912:                                                 permanentemail => $emails{'permanentemail'},
 9913: 
 9914:                                            };
 9915:                         }
 9916:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 9917:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 9918:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 9919:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9920:                                                 lastname => $names{'lastname'},
 9921:                                                 permanentemail => $emails{'permanentemail'},
 9922:                                                };
 9923:                         }
 9924:                     } else {
 9925:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 9926:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 9927:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9928:                                                 lastname => $names{'lastname'},
 9929:                                                 permanentemail => $emails{'permanentemail'},
 9930:                                                };
 9931:                         }
 9932:                     }
 9933:                 }
 9934:             }
 9935:             ($currstate,$response,$forcenewuser) = 
 9936:                 &build_search_response($context,$srch,%srch_results); 
 9937:         } elsif ($srch->{'srchin'} eq 'alc') {
 9938:             $currstate = 'query';
 9939:         } elsif ($srch->{'srchin'} eq 'instd') {
 9940:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 9941:             if ($dirsrchres eq 'ok') {
 9942:                 ($currstate,$response,$forcenewuser) = 
 9943:                     &build_search_response($context,$srch,%srch_results);
 9944:             } else {
 9945:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9946:                 $response = '<span class="LC_warning">'.
 9947:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9948:                     '</span><br />'.
 9949:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 9950:                     '<br />';
 9951:             }
 9952:         }
 9953:     }
 9954:     return ($currstate,$response,$forcenewuser,\%srch_results);
 9955: }
 9956: 
 9957: sub domdirectorysrch_check {
 9958:     my ($srch) = @_;
 9959:     my $response;
 9960:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 9961:                                              ['directorysrch'],$srch->{'srchdomain'});
 9962:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 9963:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 9964:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 9965:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 9966:         }
 9967:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 9968:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 9969:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 9970:             }
 9971:         }
 9972:     }
 9973:     return 'ok';
 9974: }
 9975: 
 9976: sub instdirectorysrch_check {
 9977:     my ($srch) = @_;
 9978:     my $can_search = 0;
 9979:     my $response;
 9980:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 9981:                                              ['directorysrch'],$srch->{'srchdomain'});
 9982:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 9983:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 9984:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 9985:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 9986:         }
 9987:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 9988:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 9989:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 9990:             }
 9991:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 9992:             if (!@usertypes) {
 9993:                 push(@usertypes,'default');
 9994:             }
 9995:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 9996:                 foreach my $type (@usertypes) {
 9997:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 9998:                         $can_search = 1;
 9999:                         last;
10000:                     }
10001:                 }
10002:             }
10003:             if (!$can_search) {
10004:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
10005:                 my @longtypes; 
10006:                 foreach my $item (@usertypes) {
10007:                     if (defined($insttypes->{$item})) { 
10008:                         push (@longtypes,$insttypes->{$item});
10009:                     } elsif ($item eq 'default') {
10010:                         push (@longtypes,&mt('other')); 
10011:                     }
10012:                 }
10013:                 my $insttype_str = join(', ',@longtypes); 
10014:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
10015:             }
10016:         } else {
10017:             $can_search = 1;
10018:         }
10019:     } else {
10020:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
10021:     }
10022:     my %longtext = &Apache::lonlocal::texthash (
10023:                        uname     => 'username',
10024:                        lastfirst => 'last name, first name',
10025:                        lastname  => 'last name',
10026:                        contains  => 'contains',
10027:                        exact     => 'as exact match to',
10028:                        begins    => 'begins with',
10029:                    );
10030:     if ($can_search) {
10031:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
10032:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
10033:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
10034:             }
10035:         } else {
10036:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
10037:         }
10038:     }
10039:     if ($can_search) {
10040:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
10041:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
10042:                 return 'ok';
10043:             } else {
10044:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10045:             }
10046:         } else {
10047:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
10048:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
10049:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
10050:                 return 'ok';
10051:             } else {
10052:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10053:             }
10054:         }
10055:     }
10056: }
10057: 
10058: sub get_courseusers {
10059:     my %advhash;
10060:     my $classlist = &Apache::loncoursedata::get_classlist();
10061:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
10062:     foreach my $role (sort(keys(%coursepersonnel))) {
10063:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
10064: 	    if (!exists($classlist->{$user})) {
10065: 		$classlist->{$user} = [];
10066: 	    }
10067:         }
10068:     }
10069:     return $classlist;
10070: }
10071: 
10072: sub build_search_response {
10073:     my ($context,$srch,%srch_results) = @_;
10074:     my ($currstate,$response,$forcenewuser);
10075:     my %names = (
10076:           'uname'     => 'username',
10077:           'lastname'  => 'last name',
10078:           'lastfirst' => 'last name, first name',
10079:           'crs'       => 'this course',
10080:           'dom'       => 'LON-CAPA domain',
10081:           'instd'     => 'the institutional directory for domain',
10082:     );
10083: 
10084:     my %single = (
10085:                    begins   => 'A match',
10086:                    contains => 'A match',
10087:                    exact    => 'An exact match',
10088:                  );
10089:     my %nomatch = (
10090:                    begins   => 'No match',
10091:                    contains => 'No match',
10092:                    exact    => 'No exact match',
10093:                   );
10094:     if (keys(%srch_results) > 1) {
10095:         $currstate = 'select';
10096:     } else {
10097:         if (keys(%srch_results) == 1) {
10098:             if ($env{'form.action'} eq 'accesslogs') {
10099:                 $currstate = 'activity';
10100:             } else {
10101:                 $currstate = 'modify';
10102:             }
10103:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
10104:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10105:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
10106:             }
10107:         } else { # Search has nothing found. Prepare message to user.
10108:             $response = '<span class="LC_warning">';
10109:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10110:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
10111:                                  '<b>'.$srch->{'srchterm'}.'</b>',
10112:                                  &display_domain_info($srch->{'srchdomain'}));
10113:             } else {
10114:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
10115:                                  '<b>'.$srch->{'srchterm'}.'</b>');
10116:             }
10117:             $response .= '</span>';
10118: 
10119:             if ($srch->{'srchin'} ne 'alc') {
10120:                 $forcenewuser = 1;
10121:                 my $cansrchinst = 0; 
10122:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
10123:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
10124:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
10125:                         if ($domconfig{'directorysrch'}{'available'}) {
10126:                             $cansrchinst = 1;
10127:                         } 
10128:                     }
10129:                 }
10130:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
10131:                      ($srch->{'srchby'} eq 'lastname')) &&
10132:                     ($srch->{'srchin'} eq 'dom')) {
10133:                     if ($cansrchinst) {
10134:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
10135:                     }
10136:                 }
10137:                 if ($srch->{'srchin'} eq 'crs') {
10138:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
10139:                 }
10140:             }
10141:             my $createdom = $env{'request.role.domain'};
10142:             if ($context eq 'requestcrs') {
10143:                 if ($env{'form.coursedom'} ne '') {
10144:                     $createdom = $env{'form.coursedom'};
10145:                 }
10146:             }
10147:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
10148:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
10149:                 my $cancreate =
10150:                     &Apache::lonuserutils::can_create_user($createdom,$context);
10151:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
10152:                 if ($cancreate) {
10153:                     my $showdom = &display_domain_info($createdom); 
10154:                     $response .= '<br /><br />'
10155:                                 .'<b>'.&mt('To add a new user:').'</b>'
10156:                                 .'<br />';
10157:                     if ($context eq 'requestcrs') {
10158:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
10159:                     } else {
10160:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
10161:                     }
10162:                     $response .='<ul><li>'
10163:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
10164:                                 .'</li><li>'
10165:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
10166:                                 .'</li><li>'
10167:                                 .&mt('Provide the proposed username')
10168:                                 .'</li><li>'
10169:                                 .&mt("Click 'Search'")
10170:                                 .'</li></ul><br />';
10171:                 } else {
10172:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
10173:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
10174:                         $response .= '<br /><br />';
10175:                         if ($context eq 'requestcrs') {
10176:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
10177:                         } else {
10178:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
10179:                         }
10180:                         $response .= '<br />'
10181:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
10182:                                         ,' <a'.$helplink.'>'
10183:                                         ,'</a>')
10184:                                      .'<br />';
10185:                     }
10186:                 }
10187:             }
10188:         }
10189:     }
10190:     return ($currstate,$response,$forcenewuser);
10191: }
10192: 
10193: sub display_domain_info {
10194:     my ($dom) = @_;
10195:     my $output = $dom;
10196:     if ($dom ne '') { 
10197:         my $domdesc = &Apache::lonnet::domain($dom,'description');
10198:         if ($domdesc ne '') {
10199:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
10200:         }
10201:     }
10202:     return $output;
10203: }
10204: 
10205: sub crumb_utilities {
10206:     my %elements = (
10207:        crtuser => {
10208:            srchterm => 'text',
10209:            srchin => 'selectbox',
10210:            srchby => 'selectbox',
10211:            srchtype => 'selectbox',
10212:            srchdomain => 'selectbox',
10213:        },
10214:        crtusername => {
10215:            srchterm => 'text',
10216:            srchdomain => 'selectbox',
10217:        },
10218:        docustom => {
10219:            rolename => 'selectbox',
10220:            newrolename => 'textbox',
10221:        },
10222:        studentform => {
10223:            srchterm => 'text',
10224:            srchin => 'selectbox',
10225:            srchby => 'selectbox',
10226:            srchtype => 'selectbox',
10227:            srchdomain => 'selectbox',
10228:        },
10229:     );
10230: 
10231:     my $jsback .= qq|
10232: function backPage(formname,prevphase,prevstate) {
10233:     if (typeof prevphase == 'undefined') {
10234:         formname.phase.value = '';
10235:     }
10236:     else {  
10237:         formname.phase.value = prevphase;
10238:     }
10239:     if (typeof prevstate == 'undefined') {
10240:         formname.currstate.value = '';
10241:     }
10242:     else {
10243:         formname.currstate.value = prevstate;
10244:     }
10245:     formname.submit();
10246: }
10247: |;
10248:     return ($jsback,\%elements);
10249: }
10250: 
10251: sub course_level_table {
10252:     my ($inccourses,$showcredits,$defaultcredits) = @_;
10253:     return unless (ref($inccourses) eq 'HASH');
10254:     my $table = '';
10255: # Custom Roles?
10256: 
10257:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10258:     my %lt=&Apache::lonlocal::texthash(
10259:             'exs'  => "Existing sections",
10260:             'new'  => "Define new section",
10261:             'ssd'  => "Set Start Date",
10262:             'sed'  => "Set End Date",
10263:             'crl'  => "Course Level",
10264:             'act'  => "Activate",
10265:             'rol'  => "Role",
10266:             'ext'  => "Extent",
10267:             'grs'  => "Section",
10268:             'crd'  => "Credits",
10269:             'sta'  => "Start",
10270:             'end'  => "End"
10271:     );
10272: 
10273:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
10274: 	my $thiscourse=$protectedcourse;
10275: 	$thiscourse=~s:_:/:g;
10276: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
10277:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
10278: 	my $area=$coursedata{'description'};
10279:         my $crstype=$coursedata{'type'};
10280: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
10281: 	my ($domain,$cnum)=split(/\//,$thiscourse);
10282:         my %sections_count;
10283:         if (defined($env{'request.course.id'})) {
10284:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
10285:                 %sections_count = 
10286: 		    &Apache::loncommon::get_sections($domain,$cnum);
10287:             }
10288:         }
10289:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
10290: 	foreach my $role (@roles) {
10291:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
10292: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
10293:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
10294:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10295:                                             $plrole,\%sections_count,\%lt,
10296:                                             $showcredits,$defaultcredits,$crstype);
10297:             } elsif ($env{'request.course.sec'} ne '') {
10298:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
10299:                                              $env{'request.course.sec'})) {
10300:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10301:                                                 $plrole,\%sections_count,\%lt,
10302:                                                 $showcredits,$defaultcredits,$crstype);
10303:                 }
10304:             }
10305:         }
10306:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
10307:             foreach my $cust (sort(keys(%customroles))) {
10308:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
10309:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
10310:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10311:                                             $cust,\%sections_count,\%lt,
10312:                                             $showcredits,$defaultcredits,$crstype);
10313:             }
10314: 	}
10315:     }
10316:     return '' if ($table eq ''); # return nothing if there is nothing 
10317:                                  # in the table
10318:     my $result;
10319:     if (!$env{'request.course.id'}) {
10320:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
10321:     }
10322:     $result .= 
10323: &Apache::loncommon::start_data_table().
10324: &Apache::loncommon::start_data_table_header_row().
10325: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10326: '<th>'.$lt{'ext'}.'</th><th>'."\n";
10327:     if ($showcredits) {
10328:         $result .= $lt{'crd'}.'</th>';
10329:     }
10330:     $result .=
10331: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
10332: '<th>'.$lt{'end'}.'</th>'.
10333: &Apache::loncommon::end_data_table_header_row().
10334: $table.
10335: &Apache::loncommon::end_data_table();
10336:     return $result;
10337: }
10338: 
10339: sub course_level_row {
10340:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
10341:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
10342:     my $creditem;
10343:     my $row = &Apache::loncommon::start_data_table_row().
10344:               ' <td><input type="checkbox" name="act_'.
10345:               $protectedcourse.'_'.$role.'" /></td>'."\n".
10346:               ' <td>'.$plrole.'</td>'."\n".
10347:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
10348:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
10349:         $row .= 
10350:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
10351:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
10352:     } else {
10353:         $row .= '<td>&nbsp;</td>';
10354:     }
10355:     if (($role eq 'cc') || ($role eq 'co')) {
10356:         $row .= '<td>&nbsp;</td>';
10357:     } elsif ($env{'request.course.sec'} ne '') {
10358:         $row .= ' <td><input type="hidden" value="'.
10359:                 $env{'request.course.sec'}.'" '.
10360:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
10361:                 $env{'request.course.sec'}.'</td>';
10362:     } else {
10363:         if (ref($sections_count) eq 'HASH') {
10364:             my $currsec = 
10365:                 &Apache::lonuserutils::course_sections($sections_count,
10366:                                                        $protectedcourse.'_'.$role);
10367:             $row .= '<td><table class="LC_createuser">'."\n".
10368:                     '<tr class="LC_section_row">'."\n".
10369:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
10370:                        $currsec.'</td>'."\n".
10371:                      ' <td>&nbsp;&nbsp;</td>'."\n".
10372:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
10373:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
10374:                      '" value="" />'.
10375:                      '<input type="hidden" '.
10376:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
10377:                      '</tr></table></td>'."\n";
10378:         } else {
10379:             $row .= '<td><input type="text" size="10" '.
10380:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
10381:         }
10382:     }
10383:     $row .= <<ENDTIMEENTRY;
10384: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
10385: <a href=
10386: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
10387: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
10388: <a href=
10389: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
10390: ENDTIMEENTRY
10391:     $row .= &Apache::loncommon::end_data_table_row();
10392:     return $row;
10393: }
10394: 
10395: sub course_level_dc {
10396:     my ($dcdom,$showcredits) = @_;
10397:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10398:     my @roles = &Apache::lonuserutils::roles_by_context('course');
10399:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
10400:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
10401:                       '<input type="hidden" name="dccourse" value="" />';
10402:     my $courseform=&Apache::loncommon::selectcourse_link
10403:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
10404:     my $credit_elem;
10405:     if ($showcredits) {
10406:         $credit_elem = 'credits';
10407:     }
10408:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
10409:     my %lt=&Apache::lonlocal::texthash(
10410:                     'rol'  => "Role",
10411:                     'grs'  => "Section",
10412:                     'exs'  => "Existing sections",
10413:                     'new'  => "Define new section", 
10414:                     'sta'  => "Start",
10415:                     'end'  => "End",
10416:                     'ssd'  => "Set Start Date",
10417:                     'sed'  => "Set End Date",
10418:                     'scc'  => "Course/Community",
10419:                     'crd'  => "Credits",
10420:                   );
10421:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
10422:                  &Apache::loncommon::start_data_table().
10423:                  &Apache::loncommon::start_data_table_header_row().
10424:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10425:                  '<th>'.$lt{'grs'}.'</th>'."\n";
10426:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
10427:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
10428:                  &Apache::loncommon::end_data_table_header_row();
10429:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
10430:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
10431:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
10432:                      '<td valign="top"><br /><select name="role">'."\n";
10433:     foreach my $role (@roles) {
10434:         my $plrole=&Apache::lonnet::plaintext($role);
10435:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
10436:     }
10437:     if ( keys(%customroles) > 0) {
10438:         foreach my $cust (sort(keys(%customroles))) {
10439:             my $custrole='cr_cr_'.$env{'user.domain'}.
10440:                     '_'.$env{'user.name'}.'_'.$cust;
10441:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
10442:         }
10443:     }
10444:     $otheritems .= '</select></td><td>'.
10445:                      '<table border="0" cellspacing="0" cellpadding="0">'.
10446:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
10447:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
10448:                      '<td>&nbsp;&nbsp;</td>'.
10449:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
10450:                      '<input type="text" name="newsec" value="" />'.
10451:                      '<input type="hidden" name="section" value="" />'.
10452:                      '<input type="hidden" name="groups" value="" />'.
10453:                      '<input type="hidden" name="crstype" value="" /></td>'.
10454:                      '</tr></table></td>'."\n";
10455:     if ($showcredits) {
10456:         $otheritems .= '<td><br />'."\n".
10457:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
10458:     }
10459:     $otheritems .= <<ENDTIMEENTRY;
10460: <td><br /><input type="hidden" name="start" value='' />
10461: <a href=
10462: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
10463: <td><br /><input type="hidden" name="end" value='' />
10464: <a href=
10465: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
10466: ENDTIMEENTRY
10467:     $otheritems .= &Apache::loncommon::end_data_table_row().
10468:                    &Apache::loncommon::end_data_table()."\n";
10469:     return $cb_jscript.$hiddenitems.$header.$otheritems;
10470: }
10471: 
10472: sub update_selfenroll_config {
10473:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
10474:     return unless (ref($currsettings) eq 'HASH');
10475:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
10476:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10477:     my (%changes,%warning);
10478:     my $curr_types;
10479:     my %noedit;
10480:     unless ($context eq 'domain') {
10481:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
10482:     }
10483:     if (ref($row) eq 'ARRAY') {
10484:         foreach my $item (@{$row}) {
10485:             next if ($noedit{$item});
10486:             if ($item eq 'enroll_dates') {
10487:                 my (%currenrolldate,%newenrolldate);
10488:                 foreach my $type ('start','end') {
10489:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
10490:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
10491:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
10492:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
10493:                     }
10494:                 }
10495:             } elsif ($item eq 'access_dates') {
10496:                 my (%currdate,%newdate);
10497:                 foreach my $type ('start','end') {
10498:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
10499:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
10500:                     if ($newdate{$type} ne $currdate{$type}) {
10501:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
10502:                     }
10503:                 }
10504:             } elsif ($item eq 'types') {
10505:                 $curr_types = $currsettings->{'selfenroll_'.$item};
10506:                 if ($env{'form.selfenroll_all'}) {
10507:                     if ($curr_types ne '*') {
10508:                         $changes{'internal.selfenroll_types'} = '*';
10509:                     } else {
10510:                         next;
10511:                     }
10512:                 } else {
10513:                     my %currdoms;
10514:                     my @entries = split(/;/,$curr_types);
10515:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
10516:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
10517:                     my $newnum = 0;
10518:                     my @latesttypes;
10519:                     foreach my $num (@activations) {
10520:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
10521:                         if (@types > 0) {
10522:                             @types = sort(@types);
10523:                             my $typestr = join(',',@types);
10524:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
10525:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10526:                             $currdoms{$typedom} = 1;
10527:                             $newnum ++;
10528:                         }
10529:                     }
10530:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
10531:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
10532:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
10533:                             if (@types > 0) {
10534:                                 @types = sort(@types);
10535:                                 my $typestr = join(',',@types);
10536:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
10537:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
10538:                                 $currdoms{$typedom} = 1;
10539:                                 $newnum ++;
10540:                             }
10541:                         }
10542:                     }
10543:                     if ($env{'form.selfenroll_newdom'} ne '') {
10544:                         my $typedom = $env{'form.selfenroll_newdom'};
10545:                         if ((!defined($currdoms{$typedom})) && 
10546:                             (&Apache::lonnet::domain($typedom) ne '')) {
10547:                             my $typestr;
10548:                             my ($othertitle,$usertypes,$types) = 
10549:                                 &Apache::loncommon::sorted_inst_types($typedom);
10550:                             my $othervalue = 'any';
10551:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
10552:                                 if (@{$types} > 0) {
10553:                                     my @esc_types = map { &escape($_); } @{$types};
10554:                                     $othervalue = 'other';
10555:                                     $typestr = join(',',(@esc_types,$othervalue));
10556:                                 }
10557:                                 $typestr = $othervalue;
10558:                             } else {
10559:                                 $typestr = $othervalue;
10560:                             } 
10561:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10562:                             $newnum ++ ;
10563:                         }
10564:                     }
10565:                     my $selfenroll_types = join(';',@latesttypes);
10566:                     if ($selfenroll_types ne $curr_types) {
10567:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
10568:                     }
10569:                 }
10570:             } elsif ($item eq 'limit') {
10571:                 my $newlimit = $env{'form.selfenroll_limit'};
10572:                 my $newcap = $env{'form.selfenroll_cap'};
10573:                 $newcap =~s/\s+//g;
10574:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10575:                 $currlimit = 'none' if ($currlimit eq '');
10576:                 my $currcap = $currsettings->{'selfenroll_cap'};
10577:                 if ($newlimit ne $currlimit) {
10578:                     if ($newlimit ne 'none') {
10579:                         if ($newcap =~ /^\d+$/) {
10580:                             if ($newcap ne $currcap) {
10581:                                 $changes{'internal.selfenroll_cap'} = $newcap;
10582:                             }
10583:                             $changes{'internal.selfenroll_limit'} = $newlimit;
10584:                         } else {
10585:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10586:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
10587:                         }
10588:                     } elsif ($currcap ne '') {
10589:                         $changes{'internal.selfenroll_cap'} = '';
10590:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
10591:                     }
10592:                 } elsif ($currlimit ne 'none') {
10593:                     if ($newcap =~ /^\d+$/) {
10594:                         if ($newcap ne $currcap) {
10595:                             $changes{'internal.selfenroll_cap'} = $newcap;
10596:                         }
10597:                     } else {
10598:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10599:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
10600:                     }
10601:                 }
10602:             } elsif ($item eq 'approval') {
10603:                 my (@currnotified,@newnotified);
10604:                 my $currapproval = $currsettings->{'selfenroll_approval'};
10605:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
10606:                 if ($currnotifylist ne '') {
10607:                     @currnotified = split(/,/,$currnotifylist);
10608:                     @currnotified = sort(@currnotified);
10609:                 }
10610:                 my $newapproval = $env{'form.selfenroll_approval'};
10611:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
10612:                 @newnotified = sort(@newnotified);
10613:                 if ($newapproval ne $currapproval) {
10614:                     $changes{'internal.selfenroll_approval'} = $newapproval;
10615:                     if (!$newapproval) {
10616:                         if ($currnotifylist ne '') {
10617:                             $changes{'internal.selfenroll_notifylist'} = '';
10618:                         }
10619:                     } else {
10620:                         my @differences =  
10621:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10622:                         if (@differences > 0) {
10623:                             if (@newnotified > 0) {
10624:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10625:                             } else {
10626:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10627:                             }
10628:                         }
10629:                     }
10630:                 } else {
10631:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10632:                     if (@differences > 0) {
10633:                         if (@newnotified > 0) {
10634:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10635:                         } else {
10636:                             $changes{'internal.selfenroll_notifylist'} = '';
10637:                         }
10638:                     }
10639:                 }
10640:             } else {
10641:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
10642:                 my $newval = $env{'form.selfenroll_'.$item};
10643:                 if ($item eq 'section') {
10644:                     $newval = $env{'form.sections'};
10645:                     if (defined($curr_groups{$newval})) {
10646:                         $newval = $curr_val;
10647:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
10648:                                           &mt('Group names and section names must be distinct');
10649:                     } elsif ($newval eq 'all') {
10650:                         $newval = $curr_val;
10651:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
10652:                     }
10653:                     if ($newval eq '') {
10654:                         $newval = 'none';
10655:                     }
10656:                 }
10657:                 if ($newval ne $curr_val) {
10658:                     $changes{'internal.selfenroll_'.$item} = $newval;
10659:                 }
10660:             }
10661:         }
10662:         if (keys(%warning) > 0) {
10663:             foreach my $item (@{$row}) {
10664:                 if (exists($warning{$item})) {
10665:                     $r->print($warning{$item}.'<br />');
10666:                 }
10667:             } 
10668:         }
10669:         if (keys(%changes) > 0) {
10670:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
10671:             if ($putresult eq 'ok') {
10672:                 if ((exists($changes{'internal.selfenroll_types'})) ||
10673:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
10674:                     (exists($changes{'internal.selfenroll_end_date'}))) {
10675:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
10676:                                                                 $cnum,undef,undef,'Course');
10677:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
10678:                     if (ref($crsinfo{$cid}) eq 'HASH') {
10679:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
10680:                             if (exists($changes{'internal.'.$item})) {
10681:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
10682:                             }
10683:                         }
10684:                         my $crsputresult =
10685:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
10686:                                                          $chome,'notime');
10687:                     }
10688:                 }
10689:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
10690:                 foreach my $item (@{$row}) {
10691:                     my $title = $item;
10692:                     if (ref($lt) eq 'HASH') {
10693:                         $title = $lt->{$item};
10694:                     }
10695:                     if ($item eq 'enroll_dates') {
10696:                         foreach my $type ('start','end') {
10697:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
10698:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
10699:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10700:                                           $title,$type,$newdate).'</li>');
10701:                             }
10702:                         }
10703:                     } elsif ($item eq 'access_dates') {
10704:                         foreach my $type ('start','end') {
10705:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
10706:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
10707:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10708:                                           $title,$type,$newdate).'</li>');
10709:                             }
10710:                         }
10711:                     } elsif ($item eq 'limit') {
10712:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
10713:                             (exists($changes{'internal.selfenroll_cap'}))) {
10714:                             my ($newval,$newcap);
10715:                             if ($changes{'internal.selfenroll_cap'} ne '') {
10716:                                 $newcap = $changes{'internal.selfenroll_cap'}
10717:                             } else {
10718:                                 $newcap = $currsettings->{'selfenroll_cap'};
10719:                             }
10720:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
10721:                                 $newval = &mt('No limit');
10722:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
10723:                                      'allstudents') {
10724:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10725:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10726:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10727:                             } else {
10728:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10729:                                 if ($currlimit eq 'allstudents') {
10730:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10731:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10732:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10733:                                 }
10734:                             }
10735:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10736:                         }
10737:                     } elsif ($item eq 'approval') {
10738:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
10739:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
10740:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
10741:                             my ($newval,$newnotify);
10742:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
10743:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
10744:                             } else {   
10745:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
10746:                             }
10747:                             if (exists($changes{'internal.selfenroll_approval'})) {
10748:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
10749:                                     $changes{'internal.selfenroll_approval'} = '0';
10750:                                 }
10751:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
10752:                             } else {
10753:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
10754:                                 if ($currapproval !~ /^[012]$/) {
10755:                                     $currapproval = 0;
10756:                                 }
10757:                                 $newval = $selfdescs{'approval'}{$currapproval};
10758:                             }
10759:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
10760:                             if ($newnotify) {
10761:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
10762:                             } else {
10763:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
10764:                             }
10765:                             $r->print('</li>'."\n");
10766:                         }
10767:                     } else {
10768:                         if (exists($changes{'internal.selfenroll_'.$item})) {
10769:                             my $newval = $changes{'internal.selfenroll_'.$item};
10770:                             if ($item eq 'types') {
10771:                                 if ($newval eq '') {
10772:                                     $newval = &mt('None');
10773:                                 } elsif ($newval eq '*') {
10774:                                     $newval = &mt('Any user in any domain');
10775:                                 }
10776:                             } elsif ($item eq 'registered') {
10777:                                 if ($newval eq '1') {
10778:                                     $newval = &mt('Yes');
10779:                                 } elsif ($newval eq '0') {
10780:                                     $newval = &mt('No');
10781:                                 }
10782:                             }
10783:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10784:                         }
10785:                     }
10786:                 }
10787:                 $r->print('</ul>');
10788:                 if ($env{'course.'.$cid.'.description'} ne '') {
10789:                     my %newenvhash;
10790:                     foreach my $key (keys(%changes)) {
10791:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
10792:                     }
10793:                     &Apache::lonnet::appenv(\%newenvhash);
10794:                 }
10795:             } else {
10796:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
10797:                           &mt('The error was: [_1].',$putresult));
10798:             }
10799:         } else {
10800:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10801:         }
10802:     } else {
10803:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10804:     }
10805:     my $visactions = &cat_visibility($cdom);
10806:     my ($cathash,%cattype);
10807:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
10808:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10809:         $cathash = $domconfig{'coursecategories'}{'cats'};
10810:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
10811:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
10812:     } else {
10813:         $cathash = {};
10814:         $cattype{'auth'} = 'std';
10815:         $cattype{'unauth'} = 'std';
10816:     }
10817:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
10818:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10819:                   '<br />'.
10820:                   '<br />'.$visactions->{'take'}.'<ul>'.
10821:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
10822:                   '</ul>');
10823:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
10824:         if ($currsettings->{'uniquecode'}) {
10825:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
10826:         } else {
10827:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10828:                   '<br />'.
10829:                   '<br />'.$visactions->{'take'}.'<ul>'.
10830:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
10831:                   '</ul><br />');
10832:         }
10833:     } else {
10834:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
10835:         if (ref($visactions) eq 'HASH') {
10836:             if (!$visible) {
10837:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10838:                           '<br />');
10839:                 if (ref($vismsgs) eq 'ARRAY') {
10840:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
10841:                     foreach my $item (@{$vismsgs}) {
10842:                         $r->print('<li>'.$visactions->{$item}.'</li>');
10843:                     }
10844:                     $r->print('</ul>');
10845:                 }
10846:                 $r->print($cansetvis);
10847:             }
10848:         }
10849:     } 
10850:     return;
10851: }
10852: 
10853: #---------------------------------------------- end functions for &phase_two
10854: 
10855: #--------------------------------- functions for &phase_two and &phase_three
10856: 
10857: #--------------------------end of functions for &phase_two and &phase_three
10858: 
10859: 1;
10860: __END__
10861: 
10862: 

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