File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.476: download - view: text, annotated - select for diffs
Thu Feb 29 16:28:35 2024 UTC (4 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- When user-specific value is in use or being set via " Add/Modify a User"
  set css display attribute to block for items which use a fieldset and to
  inline for items which use a span.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.476 2024/02/29 16:28:35 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use Apache::lonviewcoauthors;
   74: use LONCAPA qw(:DEFAULT :match);
   75: use HTML::Entities;
   76: 
   77: my $loginscript; # piece of javascript used in two separate instances
   78: my $authformnop;
   79: my $authformkrb;
   80: my $authformint;
   81: my $authformfsys;
   82: my $authformloc;
   83: my $authformlti;
   84: 
   85: sub initialize_authen_forms {
   86:     my ($dom,$formname,$curr_authtype,$mode,$readonly) = @_;
   87:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   88:     my %param = ( formname => $formname,
   89:                   kerb_def_dom => $krbdefdom,
   90:                   kerb_def_auth => $krbdef,
   91:                   domain => $dom,
   92:                 );
   93:     my %abv_auth = &auth_abbrev();
   94:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix|lti):(.*)$/) {
   95:         my $long_auth = $1;
   96:         my $curr_autharg = $2;
   97:         my %abv_auth = &auth_abbrev();
   98:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   99:         if ($long_auth =~ /^krb(4|5)$/) {
  100:             $param{'curr_kerb_ver'} = $1;
  101:             $param{'curr_autharg'} = $curr_autharg;
  102:         }
  103:         if ($mode eq 'modifyuser') {
  104:             $param{'mode'} = $mode;
  105:         }
  106:     }
  107:     if ($readonly) {
  108:         $param{'readonly'} = 1;
  109:     }
  110:     $loginscript  = &Apache::loncommon::authform_header(%param);
  111:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  112:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  113:     $authformint  = &Apache::loncommon::authform_internal(%param);
  114:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  115:     $authformloc  = &Apache::loncommon::authform_local(%param);
  116:     $authformlti  = &Apache::loncommon::authform_lti(%param);
  117: }
  118: 
  119: sub auth_abbrev {
  120:     my %abv_auth = (
  121:                      krb5      => 'krb',
  122:                      krb4      => 'krb',
  123:                      internal  => 'int',
  124:                      localauth => 'loc',
  125:                      unix      => 'fsys',
  126:                      lti       => 'lti',
  127:                    );
  128:     return %abv_auth;
  129: }
  130: 
  131: # ====================================================
  132: 
  133: sub user_quotas {
  134:     my ($ccuname,$ccdomain,$name) = @_;
  135:     my %lt = &Apache::lonlocal::texthash(
  136:                    'cust'      => "Custom quota",
  137:                    'chqu'      => "Change quota",
  138:     );
  139:     my ($output,$longinsttype);
  140:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  141:     my %titles = &Apache::lonlocal::texthash (
  142:                     portfolio => "Disk space allocated to user's portfolio files",
  143:                     author    => "Disk space allocated to user's Authoring Space",
  144:                  );
  145:     my ($currquota,$quotatype,$inststatus,$defquota) =
  146:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  147:     if ($longinsttype eq '') {
  148:         if ($inststatus ne '') {
  149:             if ($usertypes->{$inststatus} ne '') {
  150:                 $longinsttype = $usertypes->{$inststatus};
  151:             }
  152:         }
  153:     }
  154:     my ($showquota,$custom_on,$custom_off,$defaultinfo,$colspan);
  155:     $custom_on = ' ';
  156:     $custom_off = ' checked="checked" ';
  157:     $colspan = ' colspan="2"';
  158:     if ($quotatype eq 'custom') {
  159:         $custom_on = $custom_off;
  160:         $custom_off = ' ';
  161:         $showquota = $currquota;
  162:         if ($longinsttype eq '') {
  163:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
  164:                               .' MB.',$defquota);
  165:         } else {
  166:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
  167:                                " MB,[_2]as determined by the user's institutional".
  168:                                " affiliation ([_3]).",$defquota,'<br />',$longinsttype);
  169:         }
  170:     } else {
  171:         if ($longinsttype eq '') {
  172:             $defaultinfo = &mt('For this user, the default quota is [_1]'
  173:                               .' MB.',$defquota);
  174:         } else {
  175:             $defaultinfo = &mt("For this user, the default quota of [_1]".
  176:                                " MB,[_2]is determined by the user's institutional".
  177:                                " affiliation ([_3]).",$defquota,'<br />'.$longinsttype);
  178:         }
  179:     }
  180: 
  181:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  182:         $output .= '<tr class="LC_info_row">'."\n".
  183:                    '    <td'.$colspan.'>'.$titles{$name}.'</td>'."\n".
  184:                    '  </tr>'."\n".
  185:                    &Apache::loncommon::start_data_table_row()."\n".
  186:                    '  <td'.$colspan.'><span class="LC_nobreak">'.
  187:                    &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  188:                    $defaultinfo.'</td>'."\n".
  189:                    &Apache::loncommon::end_data_table_row()."\n".
  190:                    &Apache::loncommon::start_data_table_row()."\n".
  191:                    '<td'.$colspan.'><span class="LC_nobreak">'.$lt{'chqu'}.
  192:                    ': <label>'.
  193:                    '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  194:                    'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  195:                    ' /><span class="LC_nobreak">'.
  196:                    &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  197:                    '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  198:                    'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  199:                    ' />'.$lt{'cust'}.':</label>&nbsp;'.
  200:                    '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  201:                    'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  202:                    ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  203:                    &Apache::loncommon::end_data_table_row()."\n";
  204:     }
  205:     return $output;
  206: }
  207: 
  208: sub user_quota_js {
  209:     return  <<"END_SCRIPT";
  210: <script type="text/javascript">
  211: // <![CDATA[
  212: function quota_changes(caller,context) {
  213:     var customoff = document.getElementById('custom_'+context+'quota_off');
  214:     var customon = document.getElementById('custom_'+context+'quota_on');
  215:     var number = document.getElementById(context+'quota');
  216:     if (caller == "custom") {
  217:         if (customoff) {
  218:             if (customoff.checked) {
  219:                 number.value = "";
  220:             }
  221:         }
  222:     }
  223:     if (caller == "quota") {
  224:         if (customon) {
  225:             customon.checked = true;
  226:         }
  227:     }
  228:     return;
  229: }
  230: // ]]>
  231: </script>
  232: END_SCRIPT
  233: 
  234: }
  235: 
  236: sub set_custom_js {
  237:     return  <<"END_SCRIPT";
  238: 
  239: <script type="text/javascript">
  240: // <![CDATA[
  241: function toggleCustom(form,item,name) {
  242:     if (document.getElementById(item)) {
  243:         var divid = document.getElementById(item);
  244:         var radioname = form.elements[name];
  245:         if (radioname) {
  246:             if (radioname.length > 0) {
  247:                 var setvis;
  248:                 var RegExp = /^customtext_(aboutme|blog|portfolio|portaccess|timezone|webdav)\$/;
  249:                 for (var i=0; i<radioname.length; i++) {
  250:                     if (radioname[i].checked == true) {
  251:                         if (radioname[i].value == 1) {
  252:                             if (RegExp.test(item)) {
  253:                                 divid.style.display = 'inline';
  254:                             } else {
  255:                                 divid.style.display = 'block';
  256:                             }
  257:                             setvis = 1;
  258:                         }
  259:                         break;
  260:                     }
  261:                 }
  262:                 if (!setvis) {
  263:                     divid.style.display = 'none';
  264:                 }
  265:             }
  266:         }
  267:     }
  268:     return;
  269: }
  270: // ]]>
  271: </script>
  272: 
  273: END_SCRIPT
  274: 
  275: }
  276: 
  277: sub build_tools_display {
  278:     my ($ccuname,$ccdomain,$context) = @_;
  279:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  280:         $colspan,$isadv,%domconfig,@defaulteditors,@customeditors,@custommanagers,
  281:         @possmanagers);
  282:     my %lt = &Apache::lonlocal::texthash (
  283:                    'blog'       => "Personal User Blog",
  284:                    'aboutme'    => "Personal Information Page",
  285:                    'webdav'     => "WebDAV access to Authoring Spaces (https)",
  286:                    'editors'    => "Available Editors",
  287:                    'managers'   => "Co-authors who can add/revoke roles",
  288:                    'portfolio'  => "Personal User Portfolio",
  289:                    'portaccess' => "Portfolio Shareable",
  290:                    'timezone'   => "Can set Time Zone",
  291:                    'avai'       => "Available",
  292:                    'cusa'       => "availability",
  293:                    'chse'       => "Change setting",
  294:                    'usde'       => "Use default",
  295:                    'uscu'       => "Use custom",
  296:                    'official'   => 'Can request creation of official courses',
  297:                    'unofficial' => 'Can request creation of unofficial courses',
  298:                    'community'  => 'Can request creation of communities',
  299:                    'textbook'   => 'Can request creation of textbook courses',
  300:                    'placement'  => 'Can request creation of placement tests',
  301:                    'lti'        => 'Can request creation of LTI courses',
  302:                    'requestauthor'  => 'Can request author space',
  303:                    'edit'       => 'Standard editor (Edit)',
  304:                    'xml'        => 'Text editor (EditXML)',
  305:                    'daxe'       => 'Daxe editor (Daxe)',
  306:     );
  307:     $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  308:     if ($context eq 'requestcourses') {
  309:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  310:                       'requestcourses.official','requestcourses.unofficial',
  311:                       'requestcourses.community','requestcourses.textbook',
  312:                       'requestcourses.placement','requestcourses.lti');
  313:         @usertools = ('official','unofficial','community','textbook','placement','lti');
  314:         @options =('norequest','approval','autolimit','validate');
  315:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  316:         %reqtitles = &courserequest_titles();
  317:         %reqdisplay = &courserequest_display();
  318:         %domconfig =
  319:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  320:     } elsif ($context eq 'requestauthor') {
  321:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'requestauthor');
  322:         @usertools = ('requestauthor');
  323:         @options =('norequest','approval','automatic');
  324:         %reqtitles = &requestauthor_titles();
  325:         %reqdisplay = &requestauthor_display();
  326:         %domconfig =
  327:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  328:     } elsif ($context eq 'authordefaults') {
  329:         %domconfig =
  330:             &Apache::lonnet::get_dom('configuration',['quotas','authordefaults'],$ccdomain);
  331:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'tools.webdav',
  332:                                                     'authoreditors','authormanagers',
  333:                                                     'domcoord.author');
  334:         @usertools = ('webdav','editors','managers');
  335:         $colspan = ' colspan="2"';
  336:     } else {
  337:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  338:                           'tools.aboutme','tools.portfolio','tools.blog',
  339:                           'tools.timezone','tools.portaccess');
  340:         @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
  341:         $colspan = ' colspan="2"';
  342:     }
  343:     foreach my $item (@usertools) {
  344:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  345:             $currdisp,$custdisp,$custradio,$onclick,$customsty,$editorsty);
  346:         $cust_off = 'checked="checked" ';
  347:         $tool_on = 'checked="checked" ';
  348:         unless (($context eq 'authordefaults') && ($item ne 'webdav')) {
  349:             $curr_access =
  350:                 &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  351:                                                   $context,\%userenv,'',
  352:                                                   {'is_adv' => $isadv});
  353:         }
  354:         if ($context eq 'requestauthor') {
  355:             if ($userenv{$context} ne '') {
  356:                 $cust_on = ' checked="checked" ';
  357:                 $cust_off = '';
  358:             }
  359:         } elsif ($context eq 'authordefaults') {
  360:             if ($item eq 'editors') {
  361:                 if ($userenv{'author'.$item} ne '') {
  362:                     $cust_on = ' checked="checked" ';
  363:                     $cust_off = '';
  364:                 }
  365:             } elsif ($item eq 'webdav') {
  366:                 if ($userenv{'tools.'.$item} ne '') {
  367:                     $cust_on = ' checked="checked" ';
  368:                     $cust_off = '';
  369:                 }
  370:             }
  371:         } elsif ($userenv{$context.'.'.$item} ne '') {
  372:             $cust_on = ' checked="checked" ';
  373:             $cust_off = '';
  374:         }
  375:         if ($context eq 'requestcourses') {
  376:             if ($userenv{$context.'.'.$item} 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 ($context eq 'requestauthor') {
  384:             if ($userenv{$context} eq '') {
  385:                 $custom_access = &mt('Currently from default setting.');
  386:                 $customsty = ' style="display:none;"';
  387:             } else {
  388:                 $custom_access = &mt('Currently from custom setting.');
  389:                 $customsty = ' style="display:block;"';
  390:             }
  391:         } elsif ($item eq 'editors') {
  392:             if ($userenv{'author'.$item} eq '') {
  393:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
  394:                     @defaulteditors = @{$domconfig{'authordefaults'}{'editors'}};
  395:                 } else {
  396:                     @defaulteditors = ('edit','xml');
  397:                 }
  398:                 $custom_access = &mt('Can use: [_1]',
  399:                                                join(', ', map { $lt{$_} } @defaulteditors));
  400:                 $editorsty = ' style="display:none;"';
  401:             } else {
  402:                 $custom_access = &mt('Currently from custom setting.');
  403:                 foreach my $editor (split(/,/,$userenv{'author'.$item})) {
  404:                     if ($editor =~ /^(edit|daxe|xml)$/) {
  405:                         push(@customeditors,$editor);
  406:                     }
  407:                 }
  408:                 if (@customeditors) {
  409:                     if (@customeditors > 1) {
  410:                         $custom_access .= '<br /><span>';
  411:                     } else {
  412:                         $custom_access .= ' <span class="LC_nobreak">';
  413:                     }
  414:                     $custom_access .= &mt('Can use: [_1]',
  415:                                           join(', ', map { $lt{$_} } @customeditors)).
  416:                                       '</span>';
  417:                 } else {
  418:                     $custom_access .= ' '.&mt('No available editors');
  419:                 }
  420:                 $editorsty = ' style="display:block;"';
  421:             }
  422:         } elsif ($item eq 'managers') {
  423:             my %ca_roles = &Apache::lonnet::get_my_roles($ccuname,$ccdomain,undef,
  424:                                                          ['active','future'],['ca']);
  425:             if (keys(%ca_roles)) {
  426:                 foreach my $entry (sort(keys(%ca_roles))) {
  427:                     if ($entry =~ /^($match_username\:$match_domain):ca$/) {
  428:                         my $user = $1;
  429:                         unless ($user eq "$ccuname:$ccdomain") {
  430:                             push(@possmanagers,$user);
  431:                         }
  432:                     }
  433:                 }
  434:             }
  435:             if ($userenv{'author'.$item} eq '') {
  436:                 $custom_access = &mt('Currently author manages co-author roles');
  437:             } else {
  438:                 if (keys(%ca_roles)) {
  439:                     foreach my $user (split(/,/,$userenv{'author'.$item})) {
  440:                         if ($user =~ /^($match_username):($match_domain)$/) {
  441:                             if (exists($ca_roles{$user.':ca'})) {
  442:                                 unless ($user eq "$ccuname:$ccdomain") {
  443:                                     push(@custommanagers,$user);
  444:                                 }
  445:                             }
  446:                         }
  447:                     }
  448:                 }
  449:                 if (@custommanagers) {
  450:                     $custom_access = &mt('Co-authors who manage co-author roles: [_1]',
  451:                                          join(', ',@custommanagers));
  452:                 } else {
  453:                     $custom_access = &mt('Currently author manages co-author roles');
  454:                 }
  455:             }
  456:         } else {
  457:             my $current = $userenv{$context.'.'.$item};
  458:             if ($item eq 'webdav') {
  459:                 $current = $userenv{'tools.webdav'};
  460:             }
  461:             if ($current eq '') {
  462:                 $custom_access =
  463:                     &mt('Availability determined currently from default setting.');
  464:                 if (!$curr_access) {
  465:                     $tool_off = 'checked="checked" ';
  466:                     $tool_on = '';
  467:                 }
  468:                 $customsty = ' style="display:none;"';
  469:             } else {
  470:                 $custom_access =
  471:                     &mt('Availability determined currently from custom setting.');
  472:                 if ($current == 0) {
  473:                     $tool_off = 'checked="checked" ';
  474:                     $tool_on = '';
  475:                 }
  476:                 $customsty = ' style="display:inline;"';
  477:             }
  478:         }
  479:         $output .= '  <tr class="LC_info_row">'."\n".
  480:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  481:                    '  </tr>'."\n".
  482:                    &Apache::loncommon::start_data_table_row()."\n";
  483:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  484:             my ($curroption,$currlimit);
  485:             my $envkey = $context.'.'.$item;
  486:             if ($context eq 'requestauthor') {
  487:                 $envkey = $context;
  488:             }
  489:             if ($userenv{$envkey} ne '') {
  490:                 $curroption = $userenv{$envkey};
  491:             } else {
  492:                 my (@inststatuses);
  493:                 if ($context eq 'requestcourses') {
  494:                     $curroption =
  495:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  496:                                                                       $isadv,$ccdomain,$item,
  497:                                                                       \@inststatuses,\%domconfig);
  498:                 } else {
  499:                      $curroption = 
  500:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  501:                                                                        $isadv,$ccdomain,undef,
  502:                                                                        \@inststatuses,\%domconfig);
  503:                 }
  504:             }
  505:             if (!$curroption) {
  506:                 $curroption = 'norequest';
  507:             }
  508:             my $name = 'crsreq_'.$item;
  509:             if ($context eq 'requestauthor') {
  510:                 $name = $item;
  511:             }
  512:             $onclick = ' onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');"';
  513:             if ($curroption =~ /^autolimit=(\d*)$/) {
  514:                 $currlimit = $1;
  515:                 if ($currlimit eq '') {
  516:                     $currdisp = &mt('Yes, automatic creation');
  517:                 } else {
  518:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  519:                 }
  520:             } else {
  521:                 $currdisp = $reqdisplay{$curroption};
  522:             }
  523:             $custdisp = '<fieldset id="customtext_'.$item.'"'.$customsty.'>';
  524:             foreach my $option (@options) {
  525:                 my $val = $option;
  526:                 if ($option eq 'norequest') {
  527:                     $val = 0;
  528:                 }
  529:                 if ($option eq 'validate') {
  530:                     my $canvalidate = 0;
  531:                     if (ref($validations{$item}) eq 'HASH') {
  532:                         if ($validations{$item}{'_custom_'}) {
  533:                             $canvalidate = 1;
  534:                         }
  535:                     }
  536:                     next if (!$canvalidate);
  537:                 }
  538:                 my $checked = '';
  539:                 if ($option eq $curroption) {
  540:                     $checked = ' checked="checked"';
  541:                 } elsif ($option eq 'autolimit') {
  542:                     if ($curroption =~ /^autolimit/) {
  543:                         $checked = ' checked="checked"';
  544:                     }
  545:                 }
  546:                 if ($option eq 'autolimit') {
  547:                     $custdisp .= '<br />';
  548:                 }
  549:                 $custdisp .= '<span class="LC_nobreak"><label>'.
  550:                              '<input type="radio" name="'.$name.'" '.
  551:                              'value="'.$val.'"'.$checked.' />'.
  552:                              $reqtitles{$option}.'</label>&nbsp;';
  553:                 if ($option eq 'autolimit') {
  554:                     $custdisp .= '<input type="text" name="'.$name.
  555:                                  '_limit" size="1" '.
  556:                                  'value="'.$currlimit.'" />&nbsp;'.
  557:                                  $reqtitles{'unlimited'}.'</span>';
  558:                 } else {
  559:                     $custdisp .= '</span>';
  560:                 }
  561:                 $custdisp .= ' ';
  562:             }
  563:             $custdisp .= '</fieldset>';
  564:             $custradio = '<br />'.$custdisp;
  565:         } elsif ($item eq 'editors') {
  566:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  567:                        &Apache::loncommon::end_data_table_row()."\n";
  568:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  569:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  570:                           '<td'.$colspan.'><span class="LC_nobreak">'.
  571:                           $lt{'chse'}.': <label>'.
  572:                           '<input type="radio" name="custom'.$item.'" value="0" '.
  573:                           $cust_off.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  574:                           $lt{'usde'}.'</label>'.('&nbsp;' x3).
  575:                           '<label><input type="radio" name="custom'.$item.'" value="1" '.
  576:                           $cust_on.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  577:                           $lt{'uscu'}.'</label></span><br />'.
  578:                           '<fieldset id="customtext_'.$item.'"'.$editorsty.'>';
  579:                 foreach my $editor ('edit','xml','daxe') {
  580:                     my $checked;
  581:                     if ($userenv{'author'.$item} eq '') {
  582:                         if (grep(/^\Q$editor\E$/,@defaulteditors)) {
  583:                             $checked = ' checked="checked"';
  584:                         }
  585:                     } elsif (grep(/^\Q$editor\E$/,@customeditors)) {
  586:                         $checked = ' checked="checked"';
  587:                     }
  588:                     $output .= '<span style="LC_nobreak"><label>'.
  589:                                '<input type="checkbox" name="custom_editor" '.
  590:                                'value="'.$editor.'"'.$checked.' />'.
  591:                                $lt{$editor}.'</label></span> ';
  592:                 }
  593:                 $output .= '</fieldset></td>'.
  594:                            &Apache::loncommon::end_data_table_row()."\n";
  595:             }
  596:         } elsif ($item eq 'managers') {
  597:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  598:                        &Apache::loncommon::end_data_table_row()."\n";
  599:             unless ((&Apache::lonnet::allowed('udp',$ccdomain)) ||
  600:                     (($userenv{'domcoord.author'} eq 'blocked') &&
  601:                      (($env{'user.name'} ne $ccuname) || ($env{'user.domain'} ne $ccdomain)))) {
  602:                 $output .=
  603:                     &Apache::loncommon::start_data_table_row()."\n".
  604:                     '<td'.$colspan.'>';
  605:                 if (@possmanagers) {
  606:                     $output .= &mt('Select manager(s)').': ';
  607:                     foreach my $user (@possmanagers) {
  608:                         my $checked;
  609:                         if (grep(/^\Q$user\E$/,@custommanagers)) {
  610:                             $checked = ' checked="checked"';
  611:                         }
  612:                         $output .= '<span style="LC_nobreak"><label>'.
  613:                                    '<input type="checkbox" name="custommanagers" '.
  614:                                    'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
  615:                                    $user.'</label></span> ';
  616:                     }
  617:                 } else {
  618:                     $output .= &mt('No co-author roles assignable as manager');
  619:                 }
  620:                 $output .= '</td>'.
  621:                            &Apache::loncommon::end_data_table_row()."\n";
  622:             }
  623:         } else {
  624:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  625:             my $name = $context.'_'.$item;
  626:             $onclick = 'onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');" ';
  627:             $custdisp = '<span class="LC_nobreak"><label>'.
  628:                         '<input type="radio" name="'.$name.'"'.
  629:                         ' value="1" '.$tool_on.$onclick.'/>'.&mt('On').'</label>&nbsp;<label>'.
  630:                         '<input type="radio" name="'.$name.'" value="0" '.
  631:                         $tool_off.$onclick.'/>'.&mt('Off').'</label></span>';
  632:             $custradio = '<span id="customtext_'.$item.'"'.$customsty.' class="LC_nobreak">'.
  633:                          '--'.$lt{'cusa'}.':&nbsp;'.$custdisp.'</span>';
  634:         }
  635:         unless (($item eq 'editors') || ($item eq 'managers')) {
  636:             $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  637:                        $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  638:                        &Apache::loncommon::end_data_table_row()."\n";
  639:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  640:                 $output .=
  641:                    &Apache::loncommon::start_data_table_row()."\n".
  642:                    '<td><span class="LC_nobreak">'.
  643:                    $lt{'chse'}.': <label>'.
  644:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  645:                    $cust_off.$onclick.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  646:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  647:                    $cust_on.$onclick.'/>'.$lt{'uscu'}.'</label></span>';
  648:                 if ($colspan) {
  649:                     $output .= '</td><td>';
  650:                 }
  651:                 $output .= $custradio.'</td>'.
  652:                            &Apache::loncommon::end_data_table_row()."\n";
  653:             }
  654:         }
  655:     }
  656:     return $output;
  657: }
  658: 
  659: sub coursereq_externaluser {
  660:     my ($ccuname,$ccdomain,$cdom) = @_;
  661:     my (@usertools,@options,%validations,%userenv,$output);
  662:     my %lt = &Apache::lonlocal::texthash (
  663:                    'official'   => 'Can request creation of official courses',
  664:                    'unofficial' => 'Can request creation of unofficial courses',
  665:                    'community'  => 'Can request creation of communities',
  666:                    'textbook'   => 'Can request creation of textbook courses',
  667:                    'placement'  => 'Can request creation of placement tests',
  668:     );
  669: 
  670:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  671:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  672:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  673:                       'reqcrsotherdom.placement');
  674:     @usertools = ('official','unofficial','community','textbook','placement');
  675:     @options = ('approval','validate','autolimit');
  676:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  677:     my $optregex = join('|',@options);
  678:     my %reqtitles = &courserequest_titles();
  679:     foreach my $item (@usertools) {
  680:         my ($curroption,$currlimit,$tooloff);
  681:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  682:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  683:             foreach my $req (@curr) {
  684:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  685:                     $curroption = $1;
  686:                     $currlimit = $2;
  687:                     last;
  688:                 }
  689:             }
  690:             if (!$curroption) {
  691:                 $curroption = 'norequest';
  692:                 $tooloff = ' checked="checked"';
  693:             }
  694:         } else {
  695:             $curroption = 'norequest';
  696:             $tooloff = ' checked="checked"';
  697:         }
  698:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  699:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  700:                   '<table><tr><td valign="top">'."\n".
  701:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  702:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  703:                   '</label></td>';
  704:         foreach my $option (@options) {
  705:             if ($option eq 'validate') {
  706:                 my $canvalidate = 0;
  707:                 if (ref($validations{$item}) eq 'HASH') {
  708:                     if ($validations{$item}{'_external_'}) {
  709:                         $canvalidate = 1;
  710:                     }
  711:                 }
  712:                 next if (!$canvalidate);
  713:             }
  714:             my $checked = '';
  715:             if ($option eq $curroption) {
  716:                 $checked = ' checked="checked"';
  717:             }
  718:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  719:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  720:                        '" value="'.$option.'"'.$checked.' />'.
  721:                        $reqtitles{$option}.'</label>';
  722:             if ($option eq 'autolimit') {
  723:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  724:                            $item.'_limit" size="1" '.
  725:                            'value="'.$currlimit.'" /></span>'.
  726:                            '<br />'.$reqtitles{'unlimited'};
  727:             } else {
  728:                 $output .= '</span>';
  729:             }
  730:             $output .= '</td>';
  731:         }
  732:         $output .= '</td></tr></table></td>'."\n".
  733:                    &Apache::loncommon::end_data_table_row()."\n";
  734:     }
  735:     return $output;
  736: }
  737: 
  738: sub domainrole_req {
  739:     my ($ccuname,$ccdomain) = @_;
  740:     return '<br /><h3>'.
  741:            &mt('Can Request Assignment of Domain Roles?').
  742:            '</h3>'."\n".
  743:            &Apache::loncommon::start_data_table().
  744:            &build_tools_display($ccuname,$ccdomain,
  745:                                 'requestauthor').
  746:            &Apache::loncommon::end_data_table();
  747: }
  748: 
  749: sub authoring_defaults {
  750:     my ($ccuname,$ccdomain) = @_;
  751:     return '<br /><h3>'.
  752:            &mt('Authoring Space defaults (if role assigned)').
  753:            '</h3>'."\n".
  754:            &Apache::loncommon::start_data_table().
  755:            &build_tools_display($ccuname,$ccdomain,
  756:                                 'authordefaults').
  757:            &user_quotas($ccuname,$ccdomain,'author').
  758:            &Apache::loncommon::end_data_table();
  759: }
  760: 
  761: sub courserequest_titles {
  762:     my %titles = &Apache::lonlocal::texthash (
  763:                                    official   => 'Official',
  764:                                    unofficial => 'Unofficial',
  765:                                    community  => 'Communities',
  766:                                    textbook   => 'Textbook',
  767:                                    placement  => 'Placement Tests',
  768:                                    lti        => 'LTI Provider',
  769:                                    norequest  => 'Not allowed',
  770:                                    approval   => 'Approval by Dom. Coord.',
  771:                                    validate   => 'With validation',
  772:                                    autolimit  => 'Numerical limit',
  773:                                    unlimited  => '(blank for unlimited)',
  774:                  );
  775:     return %titles;
  776: }
  777: 
  778: sub courserequest_display {
  779:     my %titles = &Apache::lonlocal::texthash (
  780:                                    approval   => 'Yes, need approval',
  781:                                    validate   => 'Yes, with validation',
  782:                                    norequest  => 'No',
  783:    );
  784:    return %titles;
  785: }
  786: 
  787: sub requestauthor_titles {
  788:     my %titles = &Apache::lonlocal::texthash (
  789:                                    norequest  => 'Not allowed',
  790:                                    approval   => 'Approval by Dom. Coord.',
  791:                                    automatic  => 'Automatic approval',
  792:                  );
  793:     return %titles;
  794: 
  795: }
  796: 
  797: sub requestauthor_display {
  798:     my %titles = &Apache::lonlocal::texthash (
  799:                                    approval   => 'Yes, need approval',
  800:                                    automatic  => 'Yes, automatic approval',
  801:                                    norequest  => 'No',
  802:    );
  803:    return %titles;
  804: }
  805: 
  806: sub requestchange_display {
  807:     my %titles = &Apache::lonlocal::texthash (
  808:                                    approval   => "availability set to 'on' (approval required)", 
  809:                                    automatic  => "availability set to 'on' (automatic approval)",
  810:                                    norequest  => "availability set to 'off'",
  811:    );
  812:    return %titles;
  813: }
  814: 
  815: sub curr_requestauthor {
  816:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  817:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  818:     if ($uname eq '' || $udom eq '') {
  819:         $uname = $env{'user.name'};
  820:         $udom = $env{'user.domain'};
  821:         $isadv = $env{'user.adv'};
  822:     }
  823:     my (%userenv,%settings,$val);
  824:     my @options = ('automatic','approval');
  825:     %userenv =
  826:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  827:     if ($userenv{'requestauthor'}) {
  828:         $val = $userenv{'requestauthor'};
  829:         @{$inststatuses} = ('_custom_');
  830:     } else {
  831:         my %alltasks;
  832:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  833:             %settings = %{$domconfig->{'requestauthor'}};
  834:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  835:                 $val = $settings{'_LC_adv'};
  836:                 @{$inststatuses} = ('_LC_adv_');
  837:             } else {
  838:                 if ($userenv{'inststatus'} ne '') {
  839:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  840:                 } else {
  841:                     @{$inststatuses} = ('default');
  842:                 }
  843:                 foreach my $status (@{$inststatuses}) {
  844:                     if (exists($settings{$status})) {
  845:                         my $value = $settings{$status};
  846:                         next unless ($value);
  847:                         unless (exists($alltasks{$value})) {
  848:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  849:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  850:                                     push(@{$alltasks{$value}},$status);
  851:                                 }
  852:                             } else {
  853:                                 @{$alltasks{$value}} = ($status);
  854:                             }
  855:                         }
  856:                     }
  857:                 }
  858:                 foreach my $option (@options) {
  859:                     if ($alltasks{$option}) {
  860:                         $val = $option;
  861:                         last;
  862:                     }
  863:                 }
  864:             }
  865:         }
  866:     }
  867:     return $val;
  868: }
  869: 
  870: # =================================================================== Phase one
  871: 
  872: sub print_username_entry_form {
  873:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  874:         $permission) = @_;
  875:     my $defdom=$env{'request.role.domain'};
  876:     my $formtoset = 'crtuser';
  877:     if (exists($env{'form.startrolename'})) {
  878:         $formtoset = 'docustom';
  879:         $env{'form.rolename'} = $env{'form.startrolename'};
  880:     } elsif ($env{'form.origform'} eq 'crtusername') {
  881:         $formtoset =  $env{'form.origform'};
  882:     }
  883: 
  884:     my ($jsback,$elements) = &crumb_utilities();
  885: 
  886:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  887:         '<script type="text/javascript">'."\n".
  888:         '// <![CDATA['."\n".
  889:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  890:         '// ]]>'."\n".
  891:         '</script>'."\n";
  892: 
  893:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  894:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  895:         && (&Apache::lonnet::allowed('mcr','/'))) {
  896:         $jscript .= &customrole_javascript();
  897:     }
  898:     my $helpitem = 'Course_Change_Privileges';
  899:     if ($env{'form.action'} eq 'custom') {
  900:         if ($context eq 'course') {
  901:             $helpitem = 'Course_Editing_Custom_Roles';
  902:         } elsif ($context eq 'domain') {
  903:             $helpitem = 'Domain_Editing_Custom_Roles';
  904:         }
  905:     } elsif ($env{'form.action'} eq 'singlestudent') {
  906:         $helpitem = 'Course_Add_Student';
  907:     } elsif ($env{'form.action'} eq 'accesslogs') {
  908:         $helpitem = 'Domain_User_Access_Logs';
  909:     } elsif ($context eq 'author') {
  910:         $helpitem = 'Author_Change_Privileges';
  911:     } elsif ($context eq 'domain') {
  912:         if ($permission->{'cusr'}) {
  913:             $helpitem = 'Domain_Change_Privileges';
  914:         } elsif ($permission->{'view'}) {
  915:             $helpitem = 'Domain_View_Privileges';
  916:         } else {
  917:             undef($helpitem);
  918:         }
  919:     }
  920:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  921:     if ($env{'form.action'} eq 'custom') {
  922:         push(@{$brcrum},
  923:                  {href=>"javascript:backPage(document.crtuser)",       
  924:                   text=>"Pick custom role",
  925:                   help => $helpitem,}
  926:                  );
  927:     } else {
  928:         push (@{$brcrum},
  929:                   {href => "javascript:backPage(document.crtuser)",
  930:                    text => $breadcrumb_text{'search'},
  931:                    help => $helpitem,
  932:                    faq  => 282,
  933:                    bug  => 'Instructor Interface',}
  934:                   );
  935:     }
  936:     my %loaditems = (
  937:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  938:                     );
  939:     my $args = {bread_crumbs           => $brcrum,
  940:                 bread_crumbs_component => 'User Management',
  941:                 add_entries            => \%loaditems,};
  942:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  943: 
  944:     my %lt=&Apache::lonlocal::texthash(
  945:                     'srst' => 'Search for a user and enroll as a student',
  946:                     'srme' => 'Search for a user and enroll as a member',
  947:                     'srad' => 'Search for a user and modify/add user information or roles',
  948:                     'srvu' => 'Search for a user and view user information and roles',
  949:                     'srva' => 'Search for a user and view access log information',
  950: 		    'usr'  => "Username",
  951:                     'dom'  => "Domain",
  952:                     'ecrp' => "Define or Edit Custom Role",
  953:                     'nr'   => "role name",
  954:                     'cre'  => "Next",
  955: 				       );
  956: 
  957:     if ($env{'form.action'} eq 'custom') {
  958:         if (&Apache::lonnet::allowed('mcr','/')) {
  959:             my $newroletext = &mt('Define new custom role:');
  960:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  961:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  962:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  963:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  964:                       &Apache::loncommon::start_data_table().
  965:                       &Apache::loncommon::start_data_table_row().
  966:                       '<td>');
  967:             if (keys(%existingroles) > 0) {
  968:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  969:             } else {
  970:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  971:             }
  972:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  973:                       &Apache::loncommon::end_data_table_row());
  974:             if (keys(%existingroles) > 0) {
  975:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  976:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  977:                           &mt('View/Modify existing role:').'</b></label></td>'.
  978:                           '<td align="center"><br />'.
  979:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  980:                           '<option value="" selected="selected">'.
  981:                           &mt('Select'));
  982:                 foreach my $role (sort(keys(%existingroles))) {
  983:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  984:                 }
  985:                 $r->print('</select>'.
  986:                           '</td>'.
  987:                           &Apache::loncommon::end_data_table_row());
  988:             }
  989:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  990:                       '<input name="customeditor" type="submit" value="'.
  991:                       $lt{'cre'}.'" /></p>'.
  992:                       '</form>');
  993:         }
  994:     } else {
  995:         my $actiontext = $lt{'srad'};
  996:         my $fixeddom;
  997:         if ($env{'form.action'} eq 'singlestudent') {
  998:             if ($crstype eq 'Community') {
  999:                 $actiontext = $lt{'srme'};
 1000:             } else {
 1001:                 $actiontext = $lt{'srst'};
 1002:             }
 1003:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1004:             $actiontext = $lt{'srva'};
 1005:             $fixeddom = 1;
 1006:         } elsif (($env{'form.action'} eq 'singleuser') &&
 1007:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
 1008:             $actiontext = $lt{'srvu'};
 1009:             $fixeddom = 1;
 1010:         }
 1011:         $r->print("<h3>$actiontext</h3>");
 1012:         if ($env{'form.origform'} ne 'crtusername') {
 1013:             if ($response) {
 1014:                $r->print("\n<div>$response</div>".
 1015:                          '<br clear="all" />');
 1016:             }
 1017:         }
 1018:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
 1019:     }
 1020: }
 1021: 
 1022: sub customrole_javascript {
 1023:     my $js = <<"END";
 1024: <script type="text/javascript">
 1025: // <![CDATA[
 1026: 
 1027: function setCustomFields() {
 1028:     if (document.docustom.customroleaction.length > 0) {
 1029:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1030:             if (document.docustom.customroleaction[i].checked) {
 1031:                 if (document.docustom.customroleaction[i].value == 'new') {
 1032:                     document.docustom.rolename.selectedIndex = 0;
 1033:                 } else {
 1034:                     document.docustom.newrolename.value = '';
 1035:                 }
 1036:             }
 1037:         }
 1038:     }
 1039:     return;
 1040: }
 1041: 
 1042: function setCustomAction(caller) {
 1043:     if (document.docustom.customroleaction.length > 0) {
 1044:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1045:             if (document.docustom.customroleaction[i].value == caller) {
 1046:                 document.docustom.customroleaction[i].checked = true;
 1047:             }
 1048:         }
 1049:     }
 1050:     setCustomFields();
 1051:     return;
 1052: }
 1053: 
 1054: // ]]>
 1055: </script>
 1056: END
 1057:     return $js;
 1058: }
 1059: 
 1060: sub entry_form {
 1061:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
 1062:     my ($usertype,$inexact);
 1063:     if (ref($srch) eq 'HASH') {
 1064:         if (($srch->{'srchin'} eq 'dom') &&
 1065:             ($srch->{'srchby'} eq 'uname') &&
 1066:             ($srch->{'srchtype'} eq 'exact') &&
 1067:             ($srch->{'srchdomain'} ne '') &&
 1068:             ($srch->{'srchterm'} ne '')) {
 1069:             my (%curr_rules,%got_rules);
 1070:             my ($rules,$ruleorder) =
 1071:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
 1072:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
 1073:         } else {
 1074:             $inexact = 1;
 1075:         }
 1076:     }
 1077:     my ($cancreate,$noinstd);
 1078:     if ($env{'form.action'} eq 'accesslogs') {
 1079:         $noinstd = 1;
 1080:     } else {
 1081:         $cancreate =
 1082:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
 1083:     }
 1084:     my ($userpicker,$cansearch) = 
 1085:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
 1086:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
 1087:     my $srchbutton = &mt('Search');
 1088:     if ($env{'form.action'} eq 'singlestudent') {
 1089:         $srchbutton = &mt('Search and Enroll');
 1090:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1091:         $srchbutton = &mt('Search');
 1092:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
 1093:         $srchbutton = &mt('Search or Add New User');
 1094:     }
 1095:     my $output;
 1096:     if ($cansearch) {
 1097:         $output = <<"ENDBLOCK";
 1098: <form action="/adm/createuser" method="post" name="crtuser">
 1099: <input type="hidden" name="action" value="$env{'form.action'}" />
 1100: <input type="hidden" name="phase" value="get_user_info" />
 1101: $userpicker
 1102: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 1103: </form>
 1104: ENDBLOCK
 1105:     } else {
 1106:         $output = '<p>'.$userpicker.'</p>';
 1107:     }
 1108:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
 1109:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1110:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
 1111:         my $defdom=$env{'request.role.domain'};
 1112:         my ($trusted,$untrusted);
 1113:         if ($context eq 'course') {
 1114:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
 1115:         } elsif ($context eq 'author') {
 1116:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
 1117:         } elsif ($context eq 'domain') {
 1118:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
 1119:         }
 1120:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
 1121:         my %lt=&Apache::lonlocal::texthash(
 1122:                   'enro' => 'Enroll one student',
 1123:                   'enrm' => 'Enroll one member',
 1124:                   'admo' => 'Add/modify a single user',
 1125:                   'crea' => 'create new user if required',
 1126:                   'uskn' => "username is known",
 1127:                   'crnu' => 'Create a new user',
 1128:                   'usr'  => 'Username',
 1129:                   'dom'  => 'in domain',
 1130:                   'enrl' => 'Enroll',
 1131:                   'cram'  => 'Create/Modify user',
 1132:         );
 1133:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
 1134:         my ($title,$buttontext,$showresponse);
 1135:         if ($env{'form.action'} eq 'singlestudent') {
 1136:             if ($crstype eq 'Community') {
 1137:                 $title = $lt{'enrm'};
 1138:             } else {
 1139:                 $title = $lt{'enro'};
 1140:             }
 1141:             $buttontext = $lt{'enrl'};
 1142:         } else {
 1143:             $title = $lt{'admo'};
 1144:             $buttontext = $lt{'cram'};
 1145:         }
 1146:         if ($cancreate) {
 1147:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
 1148:         } else {
 1149:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
 1150:         }
 1151:         if ($env{'form.origform'} eq 'crtusername') {
 1152:             $showresponse = $responsemsg;
 1153:         }
 1154:         $output .= <<"ENDDOCUMENT";
 1155: <br />
 1156: <form action="/adm/createuser" method="post" name="crtusername">
 1157: <input type="hidden" name="action" value="$env{'form.action'}" />
 1158: <input type="hidden" name="phase" value="createnewuser" />
 1159: <input type="hidden" name="srchtype" value="exact" />
 1160: <input type="hidden" name="srchby" value="uname" />
 1161: <input type="hidden" name="srchin" value="dom" />
 1162: <input type="hidden" name="forcenewuser" value="1" />
 1163: <input type="hidden" name="origform" value="crtusername" />
 1164: <h3>$title</h3>
 1165: $showresponse
 1166: <table>
 1167:  <tr>
 1168:   <td>$lt{'usr'}:</td>
 1169:   <td><input type="text" size="15" name="srchterm" /></td>
 1170:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
 1171:   <td>&nbsp;$sellink&nbsp;</td>
 1172:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
 1173:  </tr>
 1174: </table>
 1175: </form>
 1176: ENDDOCUMENT
 1177:     }
 1178:     return $output;
 1179: }
 1180: 
 1181: sub user_modification_js {
 1182:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1183:     
 1184:     return <<END;
 1185: <script type="text/javascript" language="Javascript">
 1186: // <![CDATA[
 1187: 
 1188:     $pjump_def
 1189:     $dc_setcourse_code
 1190: 
 1191:     function dateset() {
 1192:         eval("document.cu."+document.cu.pres_marker.value+
 1193:             ".value=document.cu.pres_value.value");
 1194:         modalWindow.close();
 1195:     }
 1196: 
 1197:     $nondc_setsection_code
 1198: // ]]>
 1199: </script>
 1200: END
 1201: }
 1202: 
 1203: # =================================================================== Phase two
 1204: sub print_user_selection_page {
 1205:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1206:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1207:     my $sortby = $env{'form.sortby'};
 1208: 
 1209:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1210:         $sortby = 'lastname';
 1211:     }
 1212: 
 1213:     my ($jsback,$elements) = &crumb_utilities();
 1214: 
 1215:     my $jscript = (<<ENDSCRIPT);
 1216: <script type="text/javascript">
 1217: // <![CDATA[
 1218: function pickuser(uname,udom) {
 1219:     document.usersrchform.seluname.value=uname;
 1220:     document.usersrchform.seludom.value=udom;
 1221:     document.usersrchform.phase.value="userpicked";
 1222:     document.usersrchform.submit();
 1223: }
 1224: 
 1225: $jsback
 1226: // ]]>
 1227: </script>
 1228: ENDSCRIPT
 1229: 
 1230:     my %lt=&Apache::lonlocal::texthash(
 1231:                                        'usrch'          => "User Search to add/modify roles",
 1232:                                        'stusrch'        => "User Search to enroll student",
 1233:                                        'memsrch'        => "User Search to enroll member",
 1234:                                        'srcva'          => "Search for a user and view access log information",
 1235:                                        'usrvu'          => "User Search to view user roles",
 1236:                                        'usel'           => "Select a user to add/modify roles",
 1237:                                        'suvr'           => "Select a user to view roles",
 1238:                                        'stusel'         => "Select a user to enroll as a student",
 1239:                                        'memsel'         => "Select a user to enroll as a member",
 1240:                                        'vacsel'         => "Select a user to view access log",
 1241:                                        'username'       => "username",
 1242:                                        'domain'         => "domain",
 1243:                                        'lastname'       => "last name",
 1244:                                        'firstname'      => "first name",
 1245:                                        'permanentemail' => "permanent e-mail",
 1246:                                       );
 1247:     if ($context eq 'requestcrs') {
 1248:         $r->print('<div>');
 1249:     } else {
 1250:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1251:         my $helpitem;
 1252:         if ($env{'form.action'} eq 'singleuser') {
 1253:             $helpitem = 'Course_Change_Privileges';
 1254:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1255:             $helpitem = 'Course_Add_Student';
 1256:         } elsif ($context eq 'author') {
 1257:             $helpitem = 'Author_Change_Privileges';
 1258:         } elsif ($context eq 'domain') {
 1259:             $helpitem = 'Domain_Change_Privileges';
 1260:         }
 1261:         push (@{$brcrum},
 1262:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1263:                    text => $breadcrumb_text{'search'},
 1264:                    faq  => 282,
 1265:                    bug  => 'Instructor Interface',},
 1266:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1267:                    text => $breadcrumb_text{'userpicked'},
 1268:                    faq  => 282,
 1269:                    bug  => 'Instructor Interface',
 1270:                    help => $helpitem}
 1271:                   );
 1272:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1273:         if ($env{'form.action'} eq 'singleuser') {
 1274:             my $readonly;
 1275:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1276:                 $readonly = 1;
 1277:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1278:             } else {
 1279:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1280:             }
 1281:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1282:             if ($readonly) {
 1283:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1284:             } else {
 1285:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1286:             }
 1287:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1288:             $r->print($jscript."<b>");
 1289:             if ($crstype eq 'Community') {
 1290:                 $r->print($lt{'memsrch'});
 1291:             } else {
 1292:                 $r->print($lt{'stusrch'});
 1293:             }
 1294:             $r->print("</b><br />");
 1295:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1296:             $r->print('</form><h3>');
 1297:             if ($crstype eq 'Community') {
 1298:                 $r->print($lt{'memsel'});
 1299:             } else {
 1300:                 $r->print($lt{'stusel'});
 1301:             }
 1302:             $r->print('</h3>');
 1303:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1304:             $r->print("<b>$lt{'srcva'}</b><br />");
 1305:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1306:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1307:         }
 1308:     }
 1309:     $r->print('<form name="usersrchform" method="post" action="">'.
 1310:               &Apache::loncommon::start_data_table()."\n".
 1311:               &Apache::loncommon::start_data_table_header_row()."\n".
 1312:               ' <th> </th>'."\n");
 1313:     foreach my $field (@fields) {
 1314:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1315:                   "'".$field."'".';document.usersrchform.submit();">'.
 1316:                   $lt{$field}.'</a></th>'."\n");
 1317:     }
 1318:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1319: 
 1320:     my @sorted_users = sort {
 1321:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1322:             ||
 1323:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1324:             ||
 1325:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1326: 	    ||
 1327: 	lc($a) cmp lc($b)
 1328:         } (keys(%$srch_results));
 1329: 
 1330:     foreach my $user (@sorted_users) {
 1331:         my ($uname,$udom) = split(/:/,$user);
 1332:         my $onclick;
 1333:         if ($context eq 'requestcrs') {
 1334:             $onclick =
 1335:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1336:                                                "'$srch_results->{$user}->{firstname}',".
 1337:                                                "'$srch_results->{$user}->{lastname}',".
 1338:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1339:         } else {
 1340:             $onclick =
 1341:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1342:         }
 1343:         $r->print(&Apache::loncommon::start_data_table_row().
 1344:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1345:                   $onclick.' /></td>'.
 1346:                   '<td><tt>'.$uname.'</tt></td>'.
 1347:                   '<td><tt>'.$udom.'</tt></td>');
 1348:         foreach my $field ('lastname','firstname','permanentemail') {
 1349:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1350:         }
 1351:         $r->print(&Apache::loncommon::end_data_table_row());
 1352:     }
 1353:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1354:     if (ref($srcharray) eq 'ARRAY') {
 1355:         foreach my $item (@{$srcharray}) {
 1356:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1357:         }
 1358:     }
 1359:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1360:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1361:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1362:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1363:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1364:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1365:     if ($context eq 'requestcrs') {
 1366:         $r->print($opener_elements.'</form></div>');
 1367:     } else {
 1368:         $r->print($response.'</form>');
 1369:     }
 1370: }
 1371: 
 1372: sub print_user_query_page {
 1373:     my ($r,$caller,$brcrum) = @_;
 1374: # FIXME - this is for a network-wide name search (similar to catalog search)
 1375: # To use frames with similar behavior to catalog/portfolio search.
 1376: # To be implemented. 
 1377:     return;
 1378: }
 1379: 
 1380: sub print_user_modification_page {
 1381:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1382:         $brcrum,$showcredits) = @_;
 1383:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1384:         my $usermsg = &mt('No username and/or domain provided.');
 1385:         $env{'form.phase'} = '';
 1386: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1387:                                    $permission);
 1388:         return;
 1389:     }
 1390:     my ($form,$formname);
 1391:     if ($env{'form.action'} eq 'singlestudent') {
 1392:         $form = 'document.enrollstudent';
 1393:         $formname = 'enrollstudent';
 1394:     } else {
 1395:         $form = 'document.cu';
 1396:         $formname = 'cu';
 1397:     }
 1398:     my %abv_auth = &auth_abbrev();
 1399:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1400:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1401:     if ($uhome eq 'no_host') {
 1402:         my $usertype;
 1403:         my ($rules,$ruleorder) =
 1404:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1405:             $usertype =
 1406:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1407:                                                       \%curr_rules,\%got_rules);
 1408:         my $cancreate =
 1409:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1410:                                                    $usertype);
 1411:         if (!$cancreate) {
 1412:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1413:             my %usertypetext = (
 1414:                 official   => 'institutional',
 1415:                 unofficial => 'non-institutional',
 1416:             );
 1417:             my $response;
 1418:             if ($env{'form.origform'} eq 'crtusername') {
 1419:                 $response = '<span class="LC_warning">'.
 1420:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1421:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1422:                             '</span><br />';
 1423:             }
 1424:             $response .= '<p class="LC_warning">'
 1425:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1426:                         .' ';
 1427:             if ($context eq 'domain') {
 1428:                 $response .= &mt('Please contact a [_1] for assistance.',
 1429:                                  &Apache::lonnet::plaintext('dc'));
 1430:             } else {
 1431:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1432:                                 ,'<a href="'.$helplink.'">','</a>');
 1433:             }
 1434:             $response .= '</p><br />';
 1435:             $env{'form.phase'} = '';
 1436:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1437:                                        $permission);
 1438:             return;
 1439:         }
 1440:         $newuser = 1;
 1441:         my $checkhash;
 1442:         my $checks = { 'username' => 1 };
 1443:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1444:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1445:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1446:         if (ref($alerts{'username'}) eq 'HASH') {
 1447:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1448:                 my $domdesc =
 1449:                     &Apache::lonnet::domain($ccdomain,'description');
 1450:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1451:                     my $userchkmsg;
 1452:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1453:                         $userchkmsg = 
 1454:                             &Apache::loncommon::instrule_disallow_msg('username',
 1455:                                                                  $domdesc,1).
 1456:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1457:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1458:                             'username');
 1459:                     }
 1460:                     $env{'form.phase'} = '';
 1461:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1462:                                                $permission);
 1463:                     return;
 1464:                 }
 1465:             }
 1466:         }
 1467:     } else {
 1468:         $newuser = 0;
 1469:     }
 1470:     if ($response) {
 1471:         $response = '<br />'.$response;
 1472:     }
 1473: 
 1474:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1475:     my $dc_setcourse_code = '';
 1476:     my $nondc_setsection_code = '';                                        
 1477:     my %loaditem;
 1478: 
 1479:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1480: 
 1481:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1482:                                     $crstype,$groupslist,$newuser,
 1483:                                     $formname,\%loaditem,$permission);
 1484:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1485:     my $helpitem = 'Course_Change_Privileges';
 1486:     if ($env{'form.action'} eq 'singlestudent') {
 1487:         $helpitem = 'Course_Add_Student';
 1488:     } elsif ($context eq 'author') {
 1489:         $helpitem = 'Author_Change_Privileges';
 1490:     } elsif ($context eq 'domain') {
 1491:         $helpitem = 'Domain_Change_Privileges';
 1492:         $js .= &set_custom_js();
 1493:     }
 1494:     push (@{$brcrum},
 1495:         {href => "javascript:backPage($form)",
 1496:          text => $breadcrumb_text{'search'},
 1497:          faq  => 282,
 1498:          bug  => 'Instructor Interface',});
 1499:     if ($env{'form.phase'} eq 'userpicked') {
 1500:        push(@{$brcrum},
 1501:               {href => "javascript:backPage($form,'get_user_info','select')",
 1502:                text => $breadcrumb_text{'userpicked'},
 1503:                faq  => 282,
 1504:                bug  => 'Instructor Interface',});
 1505:     }
 1506:     push(@{$brcrum},
 1507:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1508:              text => $breadcrumb_text{'modify'},
 1509:              faq  => 282,
 1510:              bug  => 'Instructor Interface',
 1511:              help => $helpitem});
 1512:     my $args = {'add_entries'           => \%loaditem,
 1513:                 'bread_crumbs'          => $brcrum,
 1514:                 'bread_crumbs_component' => 'User Management'};
 1515:     if ($env{'form.popup'}) {
 1516:         $args->{'no_nav_bar'} = 1;
 1517:     }
 1518:     if (($context eq 'domain') && ($env{'request.role.domain'} eq $ccdomain)) {
 1519:         my @toggles;
 1520:         if (&Apache::lonnet::allowed('cau',$ccdomain)) {
 1521:             my ($isadv,$isauthor) =
 1522:                 &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1523:             unless ($isauthor) {
 1524:                 push(@toggles,'requestauthor');
 1525:             }
 1526:             push(@toggles,('webdav','editors'));
 1527:         }
 1528:         if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1529:             push(@toggles,('aboutme','blog','portfolio','portaccess','timezone'));
 1530:         }
 1531:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1532:             push(@toggles,('official','unofficial','community','textbook','placement','lti'));
 1533:         }
 1534:         if (@toggles) {
 1535:             my $onload;
 1536:             foreach my $item (@toggles) {
 1537:                 $onload .= "toggleCustom(document.cu,'customtext_$item','custom$item');";
 1538:             }
 1539:             $args->{'add_entries'} = {
 1540:                                        'onload' => $onload,
 1541:                                      };
 1542:         }
 1543:     }
 1544:     my $start_page =
 1545:         &Apache::loncommon::start_page('User Management',$js,$args);
 1546: 
 1547:     my $forminfo =<<"ENDFORMINFO";
 1548: <form action="/adm/createuser" method="post" name="$formname">
 1549: <input type="hidden" name="phase" value="update_user_data" />
 1550: <input type="hidden" name="ccuname" value="$ccuname" />
 1551: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1552: <input type="hidden" name="pres_value"  value="" />
 1553: <input type="hidden" name="pres_type"   value="" />
 1554: <input type="hidden" name="pres_marker" value="" />
 1555: ENDFORMINFO
 1556:     my (%inccourses,$roledom,$defaultcredits);
 1557:     if ($context eq 'course') {
 1558:         $inccourses{$env{'request.course.id'}}=1;
 1559:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1560:         if ($showcredits) {
 1561:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1562:         }
 1563:     } elsif ($context eq 'author') {
 1564:         $roledom = $env{'request.role.domain'};
 1565:     } elsif ($context eq 'domain') {
 1566:         foreach my $key (keys(%env)) {
 1567:             $roledom = $env{'request.role.domain'};
 1568:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1569:                 $inccourses{$1.'_'.$2}=1;
 1570:             }
 1571:         }
 1572:     } else {
 1573:         foreach my $key (keys(%env)) {
 1574: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1575: 	        $inccourses{$1.'_'.$2}=1;
 1576:             }
 1577:         }
 1578:     }
 1579:     my $title = '';
 1580:     my $need_quota_js;
 1581:     if ($newuser) {
 1582:         my ($portfolioform,$domroleform);
 1583:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1584:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1585:             # Current user has quota or user tools modification privileges
 1586:             $portfolioform = '<br /><h3>'.
 1587:                              &mt('User Tools').
 1588:                              '</h3>'."\n".
 1589:                              &Apache::loncommon::start_data_table();
 1590:             if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1591:                 $portfolioform .= &build_tools_display($ccuname,$ccdomain,'tools');
 1592:             }
 1593:             if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1594:                 $portfolioform .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1595:                 $need_quota_js = 1;
 1596:             }
 1597:             $portfolioform .= &Apache::loncommon::end_data_table();
 1598:         }
 1599:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1600:             ($ccdomain eq $env{'request.role.domain'})) {
 1601:             $domroleform = &domainrole_req($ccuname,$ccdomain).
 1602:                            &authoring_defaults($ccuname,$ccdomain);
 1603:             $need_quota_js = 1;
 1604:         }
 1605:         my $readonly;
 1606:         unless ($permission->{'cusr'}) {
 1607:             $readonly = 1;
 1608:         }
 1609:         &initialize_authen_forms($ccdomain,$formname,'','',$readonly);
 1610:         my %lt=&Apache::lonlocal::texthash(
 1611:                 'lg'             => 'Login Data',
 1612:                 'hs'             => "Home Server",
 1613:         );
 1614: 	$r->print(<<ENDTITLE);
 1615: $start_page
 1616: $response
 1617: $forminfo
 1618: <script type="text/javascript" language="Javascript">
 1619: // <![CDATA[
 1620: $loginscript
 1621: // ]]>
 1622: </script>
 1623: <input type='hidden' name='makeuser' value='1' />
 1624: ENDTITLE
 1625:         if ($env{'form.action'} eq 'singlestudent') {
 1626:             if ($crstype eq 'Community') {
 1627:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1628:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1629:             } else {
 1630:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1631:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1632:             }
 1633:         } else {
 1634:                 $title = &mt('Create New User [_1] in domain [_2]',
 1635:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1636:         }
 1637:         $r->print('<h2>'.$title.'</h2>'."\n");
 1638:         $r->print('<div class="LC_left_float">');
 1639:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1640:                                          $inst_results{$ccuname.':'.$ccdomain},$readonly));
 1641:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1642:         my ($home_server_pick,$numlib) = 
 1643:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1644:                                                       'default','hide');
 1645:         if ($numlib > 1) {
 1646:             $r->print("
 1647: <br />
 1648: $lt{'hs'}: $home_server_pick
 1649: <br />");
 1650:         } else {
 1651:             $r->print($home_server_pick);
 1652:         }
 1653:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1654:             $r->print('<br /><h3>'.
 1655:                       &mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1656:                       &Apache::loncommon::start_data_table().
 1657:                       &build_tools_display($ccuname,$ccdomain,
 1658:                                            'requestcourses').
 1659:                       &Apache::loncommon::end_data_table());
 1660:         }
 1661:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1662:                   $lt{'lg'}.'</h3>');
 1663:         my ($fixedauth,$varauth,$authmsg); 
 1664:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1665:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1666:             my ($rules,$ruleorder) = 
 1667:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1668:             if (ref($rules) eq 'HASH') {
 1669:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1670:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1671:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1672:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1673:                     } else { 
 1674:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1675:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1676:                         if ($authtype =~ /^krb(4|5)$/) {
 1677:                             my $ver = $1;
 1678:                             if ($authparm ne '') {
 1679:                                 $fixedauth = <<"KERB"; 
 1680: <input type="hidden" name="login" value="krb" />
 1681: <input type="hidden" name="krbver" value="$ver" />
 1682: <input type="hidden" name="krbarg" value="$authparm" />
 1683: KERB
 1684:                             }
 1685:                         } else {
 1686:                             $fixedauth = 
 1687: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1688:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1689:                                 $fixedauth .=    
 1690: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1691:                             } else {
 1692:                                 if ($authtype eq 'int') {
 1693:                                     $varauth = '<br />'.
 1694: &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>';
 1695:                                 } elsif ($authtype eq 'loc') {
 1696:                                     $varauth = '<br />'.
 1697: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1698:                                 } else {
 1699:                                     $varauth =
 1700: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1701:                                 }
 1702:                             }
 1703:                         }
 1704:                     }
 1705:                 } else {
 1706:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1707:                 }
 1708:             }
 1709:             if ($authmsg) {
 1710:                 $r->print(<<ENDAUTH);
 1711: $fixedauth
 1712: $authmsg
 1713: $varauth
 1714: ENDAUTH
 1715:             }
 1716:         } else {
 1717:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1718:         }
 1719:         $r->print($portfolioform.$domroleform);
 1720:         if ($env{'form.action'} eq 'singlestudent') {
 1721:             $r->print(&date_sections_select($context,$newuser,$formname,
 1722:                                             $permission,$crstype,$ccuname,
 1723:                                             $ccdomain,$showcredits));
 1724:         }
 1725:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1726:     } else { # user already exists
 1727: 	$r->print($start_page.$forminfo);
 1728:         if ($env{'form.action'} eq 'singlestudent') {
 1729:             if ($crstype eq 'Community') {
 1730:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1731:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1732:             } else {
 1733:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1734:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1735:             }
 1736:         } else {
 1737:             if ($permission->{'cusr'}) {
 1738:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1739:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1740:             } else {
 1741:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1742:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1743:             }
 1744:         }
 1745:         $r->print('<h2>'.$title.'</h2>'."\n");
 1746:         $r->print('<div class="LC_left_float">');
 1747:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1748:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1749:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1750:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1751:             $r->print('<br /><h3>'.&mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1752:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1753:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1754:                 $r->print(&Apache::loncommon::start_data_table());
 1755:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1756:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1757:                 } else {
 1758:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1759:                                                       $env{'request.role.domain'}));
 1760:                 }
 1761:                 $r->print(&Apache::loncommon::end_data_table());
 1762:             } else {
 1763:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1764:                               &Apache::lonnet::domain($ccdomain,'description')));
 1765:             }
 1766:         }
 1767:         $r->print('</div>');
 1768:         my @order = ('auth','quota','tools','requestauthor','authordefaults');
 1769:         my %user_text;
 1770:         my ($isadv,$isauthor) = 
 1771:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1772:         if (((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1773:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1774:             ($env{'request.role.domain'} eq $ccdomain)) {
 1775:             if (!$isauthor) {
 1776:                 $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1777:             }
 1778:             $user_text{'authordefaults'} = &authoring_defaults($ccuname,$ccdomain);
 1779:             if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1780:                 $need_quota_js = 1;
 1781:             }
 1782:         }
 1783:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1784:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1785:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1786:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1787:             $user_text{'quota'} = '<br /><h3>'.&mt('User Tools').'</h3>'."\n".
 1788:                                   &Apache::loncommon::start_data_table();
 1789:             if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1790:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1791:                 $user_text{'quota'} .= &build_tools_display($ccuname,$ccdomain,'tools');
 1792:             }
 1793:             # Current user has quota modification privileges
 1794:             if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1795:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1796:                 $user_text{'quota'} .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1797:                 $need_quota_js = 1;
 1798:             }
 1799:             $user_text{'quota'} .= &Apache::loncommon::end_data_table();
 1800:         }
 1801:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1802:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1803:                 my %lt=&Apache::lonlocal::texthash(
 1804:                     'dska'  => "Disk quotas for user's portfolio",
 1805:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1806:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1807:                 );
 1808:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1809: <h3>$lt{'dska'}</h3>
 1810: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1811: ENDNOPORTPRIV
 1812:             }
 1813:         }
 1814:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1815:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1816:                 my %lt=&Apache::lonlocal::texthash(
 1817:                     'utav'  => "User Tools Availability",
 1818:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, Personal Information Page, or Time Zone settings for this user.",
 1819:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1820:                 );
 1821:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1822: <h3>$lt{'utav'}</h3>
 1823: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1824: ENDNOTOOLSPRIV
 1825:             }
 1826:         }
 1827:         my $gotdiv = 0; 
 1828:         foreach my $item (@order) {
 1829:             if ($user_text{$item} ne '') {
 1830:                 unless ($gotdiv) {
 1831:                     $r->print('<div class="LC_left_float">');
 1832:                     $gotdiv = 1;
 1833:                 }
 1834:                 $r->print('<br />'.$user_text{$item});
 1835:             }
 1836:         }
 1837:         if ($env{'form.action'} eq 'singlestudent') {
 1838:             unless ($gotdiv) {
 1839:                 $r->print('<div class="LC_left_float">');
 1840:             }
 1841:             my $credits;
 1842:             if ($showcredits) {
 1843:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1844:                 if ($credits eq '') {
 1845:                     $credits = $defaultcredits;
 1846:                 }
 1847:             }
 1848:             $r->print(&date_sections_select($context,$newuser,$formname,
 1849:                                             $permission,$crstype,$ccuname,
 1850:                                             $ccdomain,$showcredits));
 1851:         }
 1852:         if ($gotdiv) {
 1853:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1854:         }
 1855:         my $statuses;
 1856:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1857:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1858:             $statuses = ['active'];
 1859:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1860:                  ($env{'request.course.sec'} &&
 1861:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1862:             $statuses = ['active'];
 1863:         }
 1864:         if ($env{'form.action'} ne 'singlestudent') {
 1865:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1866:                                     $roledom,$crstype,$showcredits,$statuses);
 1867:         }
 1868:     } ## End of new user/old user logic
 1869:     if ($env{'form.action'} eq 'singlestudent') {
 1870:         my $btntxt;
 1871:         if ($crstype eq 'Community') {
 1872:             $btntxt = &mt('Enroll Member');
 1873:         } else {
 1874:             $btntxt = &mt('Enroll Student');
 1875:         }
 1876:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1877:     } elsif ($permission->{'cusr'}) {
 1878:         $r->print('<div class="LC_left_float">'.
 1879:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1880:         my $addrolesdisplay = 0;
 1881:         if ($context eq 'domain' || $context eq 'author') {
 1882:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1883:         }
 1884:         if ($context eq 'domain') {
 1885:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1886:             if (!$addrolesdisplay) {
 1887:                 $addrolesdisplay = $add_domainroles;
 1888:             }
 1889:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1890:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1891:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1892:         } elsif ($context eq 'author') {
 1893:             if ($addrolesdisplay) {
 1894:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1895:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1896:                 if ($newuser) {
 1897:                     $r->print(' onclick="auth_check()" \>'."\n");
 1898:                 } else {
 1899:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1900:                 }
 1901:             } else {
 1902:                 $r->print('</fieldset></div>'.
 1903:                           '<div class="LC_clear_float_footer"></div>'.
 1904:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1905:                           &mt('Back to previous page').'</a>');
 1906:             }
 1907:         } else {
 1908:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1909:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1910:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1911:         }
 1912:     }
 1913:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1914:     $r->print('<input type="hidden" name="currstate" value="" />');
 1915:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1916:     if ($need_quota_js) {
 1917:         $r->print(&user_quota_js());
 1918:     }
 1919:     return;
 1920: }
 1921: 
 1922: sub singleuser_breadcrumb {
 1923:     my ($crstype,$context,$domain) = @_;
 1924:     my %breadcrumb_text;
 1925:     if ($env{'form.action'} eq 'singlestudent') {
 1926:         if ($crstype eq 'Community') {
 1927:             $breadcrumb_text{'search'} = 'Enroll a member';
 1928:         } else {
 1929:             $breadcrumb_text{'search'} = 'Enroll a student';
 1930:         }
 1931:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1932:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1933:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1934:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1935:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1936:         $breadcrumb_text{'activity'} = 'Activity';
 1937:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1938:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1939:         $breadcrumb_text{'search'} = "View user's roles";
 1940:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1941:         $breadcrumb_text{'modify'} = 'User roles';
 1942:     } else {
 1943:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1944:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1945:         $breadcrumb_text{'modify'} = 'Set user role';
 1946:     }
 1947:     return %breadcrumb_text;
 1948: }
 1949: 
 1950: sub date_sections_select {
 1951:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1952:         $showcredits) = @_;
 1953:     my $credits;
 1954:     if ($showcredits) {
 1955:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1956:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1957:         if ($credits eq '') {
 1958:             $credits = $defaultcredits;
 1959:         }
 1960:     }
 1961:     my $cid = $env{'request.course.id'};
 1962:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1963:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1964:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1965:                                                   undef,$formname,$permission);
 1966:     my $rowtitle = 'Section';
 1967:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1968:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1969:                                               $permission,$context,'',$crstype,
 1970:                                               $showcredits,$credits);
 1971:     my $output = $date_table.$secbox;
 1972:     return $output;
 1973: }
 1974: 
 1975: sub validation_javascript {
 1976:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1977:         $loaditem,$permission) = @_;
 1978:     my $dc_setcourse_code = '';
 1979:     my $nondc_setsection_code = '';
 1980:     if ($context eq 'domain') {
 1981:         if ((ref($permission) eq 'HASH') && ($permission->{'cusr'})) {
 1982:             my $dcdom = $env{'request.role.domain'};
 1983:             $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1984:             $dc_setcourse_code =
 1985:                 &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1986:         }
 1987:     } else {
 1988:         my $checkauth; 
 1989:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1990:             $checkauth = 1;
 1991:         }
 1992:         if ($context eq 'course') {
 1993:             $nondc_setsection_code =
 1994:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1995:                                                               undef,$checkauth,
 1996:                                                               $crstype);
 1997:         }
 1998:         if ($checkauth) {
 1999:             $nondc_setsection_code .= 
 2000:                 &Apache::lonuserutils::verify_authen($formname,$context);
 2001:         }
 2002:     }
 2003:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 2004:                                    $nondc_setsection_code,$groupslist);
 2005:     my ($jsback,$elements) = &crumb_utilities();
 2006:     $js .= "\n".
 2007:            '<script type="text/javascript">'."\n".
 2008:            '// <![CDATA['."\n".
 2009:            $jsback."\n".
 2010:            '// ]]>'."\n".
 2011:            '</script>'."\n";
 2012:     return $js;
 2013: }
 2014: 
 2015: sub display_existing_roles {
 2016:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 2017:         $showcredits,$statuses) = @_;
 2018:     my $now=time;
 2019:     my $showall = 1;
 2020:     my ($showexpired,$showactive);
 2021:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 2022:         $showall = 0;
 2023:         if (grep(/^expired$/,@{$statuses})) {
 2024:             $showexpired = 1;
 2025:         }
 2026:         if (grep(/^active$/,@{$statuses})) {
 2027:             $showactive = 1;
 2028:         }
 2029:         if ($showexpired && $showactive) {
 2030:             $showall = 1;
 2031:         }
 2032:     }
 2033:     my %lt=&Apache::lonlocal::texthash(
 2034:                     'rer'  => "Existing Roles",
 2035:                     'rev'  => "Revoke",
 2036:                     'del'  => "Delete",
 2037:                     'ren'  => "Re-Enable",
 2038:                     'rol'  => "Role",
 2039:                     'ext'  => "Extent",
 2040:                     'crd'  => "Credits",
 2041:                     'sta'  => "Start",
 2042:                     'end'  => "End",
 2043:                                        );
 2044:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 2045:     if ($context eq 'course' || $context eq 'author') {
 2046:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 2047:         my %roleshash = 
 2048:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 2049:                               ['active','previous','future'],\@roles,$roledom,1);
 2050:         foreach my $key (keys(%roleshash)) {
 2051:             my ($start,$end) = split(':',$roleshash{$key});
 2052:             next if ($start eq '-1' || $end eq '-1');
 2053:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 2054:             if ($context eq 'course') {
 2055:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 2056:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 2057:             } elsif ($context eq 'author') {
 2058:                 if ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2059:                     my ($audom,$auname) = ($1,$2);
 2060:                     next unless (($rnum eq $auname) && ($rdom eq $audom));
 2061:                 } else {
 2062:                     next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 2063:                 }
 2064:             }
 2065:             my ($newkey,$newvalue,$newrole);
 2066:             $newkey = '/'.$rdom.'/'.$rnum;
 2067:             if ($sec ne '') {
 2068:                 $newkey .= '/'.$sec;
 2069:             }
 2070:             $newvalue = $role;
 2071:             if ($role =~ /^cr/) {
 2072:                 $newrole = 'cr';
 2073:             } else {
 2074:                 $newrole = $role;
 2075:             }
 2076:             $newkey .= '_'.$newrole;
 2077:             if ($start ne '' && $end ne '') {
 2078:                 $newvalue .= '_'.$end.'_'.$start;
 2079:             } elsif ($end ne '') {
 2080:                 $newvalue .= '_'.$end;
 2081:             }
 2082:             $rolesdump{$newkey} = $newvalue;
 2083:         }
 2084:     } else {
 2085:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 2086:     }
 2087:     # Build up table of user roles to allow revocation and re-enabling of roles.
 2088:     my ($tmp) = keys(%rolesdump);
 2089:     return if ($tmp =~ /^(con_lost|error)/i);
 2090:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 2091:                                 my $b1=join('_',(split('_',$b))[1,0]);
 2092:                                 return $a1 cmp $b1;
 2093:                             } keys(%rolesdump)) {
 2094:         next if ($area =~ /^rolesdef/);
 2095:         my $envkey=$area;
 2096:         my $role = $rolesdump{$area};
 2097:         my $thisrole=$area;
 2098:         $area =~ s/\_\w\w$//;
 2099:         my ($role_code,$role_end_time,$role_start_time) =
 2100:             split(/_/,$role);
 2101:         my $active=1;
 2102:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 2103:         if ($active) {
 2104:             next unless($showall || $showactive);
 2105:         } else {
 2106:             next unless($showall || $showexpired);
 2107:         }
 2108: # Is this a custom role? Get role owner and title.
 2109:         my ($croleudom,$croleuname,$croletitle)=
 2110:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 2111:         my $allowed=0;
 2112:         my $delallowed=0;
 2113:         my $sortkey=$role_code;
 2114:         my $class='Unknown';
 2115:         my $credits='';
 2116:         my $csec;
 2117:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 2118:             $class='Course';
 2119:             my ($coursedom,$coursedir) = ($1,$2);
 2120:             my $cid = $1.'_'.$2;
 2121:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 2122:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 2123:             my %coursedata=
 2124:                 &Apache::lonnet::coursedescription($cid);
 2125:             if ($coursedir =~ /^$match_community$/) {
 2126:                 $class='Community';
 2127:             }
 2128:             $sortkey.="\0$coursedom";
 2129:             my $carea;
 2130:             if (defined($coursedata{'description'})) {
 2131:                 $carea=$coursedata{'description'}.
 2132:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 2133:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 2134:                 $sortkey.="\0".$coursedata{'description'};
 2135:             } else {
 2136:                 if ($class eq 'Community') {
 2137:                     $carea=&mt('Unavailable community').': '.$area;
 2138:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 2139:                 } else {
 2140:                     $carea=&mt('Unavailable course').': '.$area;
 2141:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 2142:                 }
 2143:             }
 2144:             $sortkey.="\0$coursedir";
 2145:             $inccourses->{$cid}=1;
 2146:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 2147:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 2148:                 $credits =
 2149:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 2150:                                       $coursedom,$coursedir);
 2151:                 if ($credits eq '') {
 2152:                     $credits = $defaultcredits;
 2153:                 }
 2154:             }
 2155:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 2156:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2157:                 $allowed=1;
 2158:             }
 2159:             unless ($allowed) {
 2160:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 2161:                 if ($isowner) {
 2162:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 2163:                         $allowed = 1;
 2164:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 2165:                         $allowed = 1;
 2166:                     }
 2167:                 }
 2168:             } 
 2169:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 2170:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 2171:                 $delallowed=1;
 2172:             }
 2173: # - custom role. Needs more info, too
 2174:             if ($croletitle) {
 2175:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 2176:                     $allowed=1;
 2177:                     $thisrole.='.'.$role_code;
 2178:                 }
 2179:             }
 2180:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 2181:                 $csec = $2;
 2182:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 2183:                 $sortkey.="\0$csec";
 2184:                 if (!$allowed) {
 2185:                     if ($env{'request.course.sec'} eq $csec) {
 2186:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 2187:                             $allowed = 1;
 2188:                         }
 2189:                     }
 2190:                 }
 2191:             }
 2192:             $area=$carea;
 2193:         } else {
 2194:             $sortkey.="\0".$area;
 2195:             # Determine if current user is able to revoke privileges
 2196:             if ($area=~m{^/($match_domain)/}) {
 2197:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 2198:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2199:                    $allowed=1;
 2200:                 }
 2201:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 2202:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 2203:                     ($role_code ne 'dc')) {
 2204:                     $delallowed=1;
 2205:                 }
 2206:             } else {
 2207:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 2208:                     $allowed=1;
 2209:                 }
 2210:             }
 2211:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 2212:                 $class='Authoring Space';
 2213:             } elsif ($role_code eq 'su') {
 2214:                 $class='System';
 2215:             } else {
 2216:                 $class='Domain';
 2217:             }
 2218:         }
 2219:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 2220:             $area=~m{/($match_domain)/($match_username)};
 2221:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 2222:                 $allowed=1;
 2223:             } elsif (&Apache::lonuserutils::coauthorpriv($2,$1)) {
 2224:                 $allowed=1;
 2225:             } else {
 2226:                 $allowed=0;
 2227:             }
 2228:         }
 2229:         my $row = '';
 2230:         if ($showall) {
 2231:             $row.= '<td>';
 2232:             if (($active) && ($allowed)) {
 2233:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 2234:             } else {
 2235:                 if ($active) {
 2236:                     $row.='&nbsp;';
 2237:                 } else {
 2238:                     $row.=&mt('expired or revoked');
 2239:                 }
 2240:             }
 2241:             $row.='</td><td>';
 2242:             if ($allowed && !$active) {
 2243:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 2244:             } else {
 2245:                 $row.='&nbsp;';
 2246:             }
 2247:             $row.='</td><td>';
 2248:             if ($delallowed) {
 2249:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 2250:             } else {
 2251:                 $row.='&nbsp;';
 2252:             }
 2253:             $row.= '</td>';
 2254:         }
 2255:         my $plaintext='';
 2256:         if (!$croletitle) {
 2257:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2258:             if (($showcredits) && ($credits ne '')) {
 2259:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2260:                               '<span class="LC_fontsize_small">'.
 2261:                               &mt('Credits: [_1]',$credits).
 2262:                               '</span></span>';
 2263:             }
 2264:         } else {
 2265:             $plaintext=
 2266:                 &mt('Custom role [_1][_2]defined by [_3]',
 2267:                         '"'.$croletitle.'"',
 2268:                         '<br />',
 2269:                         $croleuname.':'.$croleudom);
 2270:         }
 2271:         $row.= '<td>'.$plaintext.'</td>'.
 2272:                '<td>'.$area.'</td>'.
 2273:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2274:                                             : '&nbsp;' ).'</td>'.
 2275:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2276:                                             : '&nbsp;' ).'</td>';
 2277:         $sortrole{$sortkey}=$envkey;
 2278:         $roletext{$envkey}=$row;
 2279:         $roleclass{$envkey}=$class;
 2280:         if ($allowed) {
 2281:             $rolepriv{$envkey}='edit';
 2282:         } else {
 2283:             if ($context eq 'domain') {
 2284:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2285:                     ($envkey=~m{^/$ccdomain/})) {
 2286:                     $rolepriv{$envkey}='view';
 2287:                 }
 2288:             } elsif ($context eq 'course') {
 2289:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2290:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2291:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2292:                     $rolepriv{$envkey}='view';
 2293:                 }
 2294:             }
 2295:         }
 2296:     } # end of foreach        (table building loop)
 2297: 
 2298:     my $rolesdisplay = 0;
 2299:     my %output = ();
 2300:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2301:         $output{$type} = '';
 2302:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2303:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2304:                  $output{$type}.=
 2305:                       &Apache::loncommon::start_data_table_row().
 2306:                       $roletext{$sortrole{$which}}.
 2307:                       &Apache::loncommon::end_data_table_row();
 2308:             }
 2309:         }
 2310:         unless($output{$type} eq '') {
 2311:             $output{$type} = '<tr class="LC_info_row">'.
 2312:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2313:                       $output{$type};
 2314:             $rolesdisplay = 1;
 2315:         }
 2316:     }
 2317:     if ($rolesdisplay == 1) {
 2318:         my $contextrole='';
 2319:         if ($env{'request.course.id'}) {
 2320:             if (&Apache::loncommon::course_type() eq 'Community') {
 2321:                 $contextrole = &mt('Existing Roles in this Community');
 2322:             } else {
 2323:                 $contextrole = &mt('Existing Roles in this Course');
 2324:             }
 2325:         } elsif ($env{'request.role'} =~ /^au\./) {
 2326:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2327:         } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)/$}) {
 2328:             $contextrole = &mt('Existing Co-Author Roles in [_1] Authoring Space',
 2329:                                '<i>'.$1.'_'.$2.'</i>');
 2330:         } else {
 2331:             if ($showall) {
 2332:                 $contextrole = &mt('Existing Roles in this Domain');
 2333:             } elsif ($showactive) {
 2334:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2335:             } elsif ($showexpired) {
 2336:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2337:             }
 2338:         }
 2339:         $r->print('<div class="LC_left_float">'.
 2340: '<fieldset><legend>'.$contextrole.'</legend>'.
 2341: &Apache::loncommon::start_data_table("LC_createuser").
 2342: &Apache::loncommon::start_data_table_header_row());
 2343:         if ($showall) {
 2344:             $r->print(
 2345: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2346:             );
 2347:         } elsif ($showexpired) {
 2348:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2349:         }
 2350:         $r->print(
 2351: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2352: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2353: &Apache::loncommon::end_data_table_header_row());
 2354:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2355:             if ($output{$type}) {
 2356:                 $r->print($output{$type}."\n");
 2357:             }
 2358:         }
 2359:         $r->print(&Apache::loncommon::end_data_table().
 2360:                   '</fieldset></div>');
 2361:     }
 2362:     return;
 2363: }
 2364: 
 2365: sub new_coauthor_roles {
 2366:     my ($r,$ccuname,$ccdomain) = @_;
 2367:     my $addrolesdisplay = 0;
 2368:     #
 2369:     # Co-Author
 2370:     #
 2371:     my ($cuname,$cudom);
 2372:     if (($env{'request.role'} eq "au./$env{'user.domain'}/") ||
 2373:         ($env{'request.role'} eq "dc./$env{'user.domain'}/")) {
 2374:         $cuname=$env{'user.name'};
 2375:         $cudom=$env{'request.role.domain'};
 2376:         # No sense in assigning co-author role to yourself
 2377:         if ((&Apache::lonuserutils::authorpriv($cuname,$cudom)) &&
 2378:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2379:             $addrolesdisplay = 1;
 2380:         }
 2381:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2382:         ($cudom,$cuname) = ($1,$2);
 2383:         if ((&Apache::lonuserutils::coauthorpriv($cuname,$cudom)) &&
 2384:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain) &&
 2385:             ($cudom ne $ccdomain || $cuname ne $ccuname)) {
 2386:             $addrolesdisplay = 1;
 2387:         }
 2388:     }
 2389:     if ($addrolesdisplay) {
 2390:         my %lt=&Apache::lonlocal::texthash(
 2391:                     'cs'   => "Authoring Space",
 2392:                     'act'  => "Activate",
 2393:                     'rol'  => "Role",
 2394:                     'ext'  => "Extent",
 2395:                     'sta'  => "Start",
 2396:                     'end'  => "End",
 2397:                     'cau'  => "Co-Author",
 2398:                     'caa'  => "Assistant Co-Author",
 2399:                     'ssd'  => "Set Start Date",
 2400:                     'sed'  => "Set End Date"
 2401:                                        );
 2402:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2403:                   &Apache::loncommon::start_data_table()."\n".
 2404:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2405:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2406:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2407:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2408:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2409:                   &Apache::loncommon::start_data_table_row().'
 2410:            <td>
 2411:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2412:            </td>
 2413:            <td>'.$lt{'cau'}.'</td>
 2414:            <td>'.$cudom.'_'.$cuname.'</td>
 2415:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2416:              <a href=
 2417: "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>
 2418: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2419: <a href=
 2420: "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".
 2421:               &Apache::loncommon::end_data_table_row()."\n".
 2422:               &Apache::loncommon::start_data_table_row()."\n".
 2423: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2424: <td>'.$lt{'caa'}.'</td>
 2425: <td>'.$cudom.'_'.$cuname.'</td>
 2426: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2427: <a href=
 2428: "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>
 2429: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2430: <a href=
 2431: "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".
 2432:              &Apache::loncommon::end_data_table_row()."\n".
 2433:              &Apache::loncommon::end_data_table());
 2434:     } elsif ($env{'request.role'} =~ /^au\./) {
 2435:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2436:                                                 $env{'request.role.domain'}))) {
 2437:             $r->print('<span class="LC_error">'.
 2438:                       &mt('You do not have privileges to assign co-author roles.').
 2439:                       '</span>');
 2440:         } elsif (($env{'user.name'} eq $ccuname) &&
 2441:              ($env{'user.domain'} eq $ccdomain)) {
 2442:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2443:         }
 2444:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2445:         if (!(&Apache::lonuserutils::coauthorpriv($2,$1))) {
 2446:             $r->print('<span class="LC_error">'.
 2447:                       &mt('You do not have privileges to assign co-author roles.').
 2448:                       '</span>');
 2449:         } elsif (($env{'user.name'} eq $ccuname) &&
 2450:              ($env{'user.domain'} eq $ccdomain)) {
 2451:             $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'));
 2452:         } elsif (($cudom eq $ccdomain) && ($cuname eq $ccuname)) {
 2453:             $r->print(&mt("Assigning a co-author or assistant co-author role to an Authoring Space's author is not permitted"));
 2454:         }
 2455:     }
 2456:     return $addrolesdisplay;;
 2457: }
 2458: 
 2459: sub new_domain_roles {
 2460:     my ($r,$ccdomain) = @_;
 2461:     my $addrolesdisplay = 0;
 2462:     #
 2463:     # Domain level
 2464:     #
 2465:     my $num_domain_level = 0;
 2466:     my $domaintext =
 2467:     '<h4>'.&mt('Domain Level').'</h4>'.
 2468:     &Apache::loncommon::start_data_table().
 2469:     &Apache::loncommon::start_data_table_header_row().
 2470:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2471:     &mt('Extent').'</th>'.
 2472:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2473:     &Apache::loncommon::end_data_table_header_row();
 2474:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2475:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2476:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2477:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2478:         foreach my $role (@allroles) {
 2479:             next if ($role eq 'ad');
 2480:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2481:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2482:                if ($role eq 'dc') {
 2483:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2484:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2485:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2486:                        next unless ($uintdom eq $intdom);
 2487:                    }
 2488:                }
 2489:                my $plrole=&Apache::lonnet::plaintext($role);
 2490:                my %lt=&Apache::lonlocal::texthash(
 2491:                     'ssd'  => "Set Start Date",
 2492:                     'sed'  => "Set End Date"
 2493:                                        );
 2494:                $num_domain_level ++;
 2495:                $domaintext .=
 2496: &Apache::loncommon::start_data_table_row().
 2497: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2498: <td>'.$plrole.'</td>
 2499: <td>'.$thisdomain.'</td>
 2500: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2501: <a href=
 2502: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2503: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2504: <a href=
 2505: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2506: &Apache::loncommon::end_data_table_row();
 2507:             }
 2508:         }
 2509:     }
 2510:     $domaintext.= &Apache::loncommon::end_data_table();
 2511:     if ($num_domain_level > 0) {
 2512:         $r->print($domaintext);
 2513:         $addrolesdisplay = 1;
 2514:     }
 2515:     return $addrolesdisplay;
 2516: }
 2517: 
 2518: sub user_authentication {
 2519:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2520:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2521:     my $outcome;
 2522:     my %lt=&Apache::lonlocal::texthash(
 2523:                    'err'   => "ERROR",
 2524:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2525:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2526:                    'sldb'  => "Please specify login data below",
 2527:                    'ld'    => "Login Data"
 2528:     );
 2529:     # Check for a bad authentication type
 2530:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2531:         # bad authentication scheme
 2532:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2533:             &initialize_authen_forms($ccdomain,$formname);
 2534: 
 2535:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2536:             $outcome = <<ENDBADAUTH;
 2537: <script type="text/javascript" language="Javascript">
 2538: // <![CDATA[
 2539: $loginscript
 2540: // ]]>
 2541: </script>
 2542: <span class="LC_error">$lt{'err'}:
 2543: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2544: <h3>$lt{'ld'}</h3>
 2545: $choices
 2546: ENDBADAUTH
 2547:         } else {
 2548:             # This user is not allowed to modify the user's
 2549:             # authentication scheme, so just notify them of the problem
 2550:             $outcome = <<ENDBADAUTH;
 2551: <span class="LC_error"> $lt{'err'}: 
 2552: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2553: </span>
 2554: ENDBADAUTH
 2555:         }
 2556:     } else { # Authentication type is valid
 2557:         
 2558:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2559:         my ($authformcurrent,$can_modify,@authform_others) =
 2560:             &modify_login_block($ccdomain,$currentauth);
 2561:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2562:             # Current user has login modification privileges
 2563:             $outcome =
 2564:                        '<script type="text/javascript" language="Javascript">'."\n".
 2565:                        '// <![CDATA['."\n".
 2566:                        $loginscript."\n".
 2567:                        '// ]]>'."\n".
 2568:                        '</script>'."\n".
 2569:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2570:                        &Apache::loncommon::start_data_table().
 2571:                        &Apache::loncommon::start_data_table_row().
 2572:                        '<td>'.$authformnop;
 2573:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2574:                 $outcome .= '</td>'."\n".
 2575:                             &Apache::loncommon::end_data_table_row().
 2576:                             &Apache::loncommon::start_data_table_row().
 2577:                             '<td>'.$authformcurrent.'</td>'.
 2578:                             &Apache::loncommon::end_data_table_row()."\n";
 2579:             } else {
 2580:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2581:                             &Apache::loncommon::end_data_table_row()."\n";
 2582:             }
 2583:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2584:                 foreach my $item (@authform_others) { 
 2585:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2586:                                 '<td>'.$item.'</td>'.
 2587:                                 &Apache::loncommon::end_data_table_row()."\n";
 2588:                 }
 2589:             }
 2590:             $outcome .= &Apache::loncommon::end_data_table();
 2591:         } else {
 2592:             if (($currentauth =~ /^internal:/) &&
 2593:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2594:                 $outcome = <<"ENDJS";
 2595: <script type="text/javascript">
 2596: // <![CDATA[
 2597: function togglePwd(form) {
 2598:     if (form.newintpwd.length) {
 2599:         if (document.getElementById('LC_ownersetpwd')) {
 2600:             for (var i=0; i<form.newintpwd.length; i++) {
 2601:                 if (form.newintpwd[i].checked) {
 2602:                     if (form.newintpwd[i].value == 1) {
 2603:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2604:                     } else {
 2605:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2606:                     }
 2607:                 }
 2608:             }
 2609:         }
 2610:     }
 2611: }
 2612: // ]]>
 2613: </script>
 2614: ENDJS
 2615: 
 2616:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2617:                             &Apache::loncommon::start_data_table().
 2618:                             &Apache::loncommon::start_data_table_row().
 2619:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2620:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2621:                             &mt('No').'</label>'.('&nbsp;'x2).
 2622:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2623:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2624:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2625:                             '<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>'.
 2626:                             &Apache::loncommon::end_data_table_row().
 2627:                             &Apache::loncommon::end_data_table();
 2628:             }
 2629:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2630:                 # Current user has rights to view domain preferences for user's domain
 2631:                 my $result;
 2632:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2633:                     my ($krbver,$krbrealm) = ($1,$2);
 2634:                     if ($krbrealm eq '') {
 2635:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2636:                     } else {
 2637:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2638:                                       $krbrealm,$krbver);
 2639:                     }
 2640:                 } elsif ($currentauth =~ /^internal:/) {
 2641:                     $result = &mt('Currently internally authenticated.');
 2642:                 } elsif ($currentauth =~ /^localauth:/) {
 2643:                     $result = &mt('Currently using local (institutional) authentication.');
 2644:                 } elsif ($currentauth =~ /^unix:/) {
 2645:                     $result = &mt('Currently Filesystem Authenticated.');
 2646:                 } elsif ($currentauth =~ /^lti:/) {
 2647:                     $result = &mt('Currently LTI authenticated.');
 2648:                 }
 2649:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2650:                            &Apache::loncommon::start_data_table().
 2651:                            &Apache::loncommon::start_data_table_row().
 2652:                            '<td>'.$result.'</td>'.
 2653:                            &Apache::loncommon::end_data_table_row()."\n".
 2654:                            &Apache::loncommon::end_data_table();
 2655:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2656:                 my %lt=&Apache::lonlocal::texthash(
 2657:                            'ccld'  => "Change Current Login Data",
 2658:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2659:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2660:                 );
 2661:                 $outcome .= <<ENDNOPRIV;
 2662: <h3>$lt{'ccld'}</h3>
 2663: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2664: <input type="hidden" name="login" value="nochange" />
 2665: ENDNOPRIV
 2666:             }
 2667:         }
 2668:     }  ## End of "check for bad authentication type" logic
 2669:     return $outcome;
 2670: }
 2671: 
 2672: sub modify_login_block {
 2673:     my ($dom,$currentauth) = @_;
 2674:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2675:     my ($authnum,%can_assign) =
 2676:         &Apache::loncommon::get_assignable_auth($dom);
 2677:     my ($authformcurrent,@authform_others,$show_override_msg);
 2678:     if ($currentauth=~/^krb(4|5):/) {
 2679:         $authformcurrent=$authformkrb;
 2680:         if ($can_assign{'int'}) {
 2681:             push(@authform_others,$authformint);
 2682:         }
 2683:         if ($can_assign{'loc'}) {
 2684:             push(@authform_others,$authformloc);
 2685:         }
 2686:         if ($can_assign{'lti'}) {
 2687:             push(@authform_others,$authformlti);
 2688:         }
 2689:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2690:             $show_override_msg = 1;
 2691:         }
 2692:     } elsif ($currentauth=~/^internal:/) {
 2693:         $authformcurrent=$authformint;
 2694:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2695:             push(@authform_others,$authformkrb);
 2696:         }
 2697:         if ($can_assign{'loc'}) {
 2698:             push(@authform_others,$authformloc);
 2699:         }
 2700:         if ($can_assign{'lti'}) {
 2701:             push(@authform_others,$authformlti);
 2702:         }
 2703:         if ($can_assign{'int'}) {
 2704:             $show_override_msg = 1;
 2705:         }
 2706:     } elsif ($currentauth=~/^unix:/) {
 2707:         $authformcurrent=$authformfsys;
 2708:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2709:             push(@authform_others,$authformkrb);
 2710:         }
 2711:         if ($can_assign{'int'}) {
 2712:             push(@authform_others,$authformint);
 2713:         }
 2714:         if ($can_assign{'loc'}) {
 2715:             push(@authform_others,$authformloc);
 2716:         }
 2717:         if ($can_assign{'lti'}) {
 2718:             push(@authform_others,$authformlti);
 2719:         }
 2720:         if ($can_assign{'fsys'}) {
 2721:             $show_override_msg = 1;
 2722:         }
 2723:     } elsif ($currentauth=~/^localauth:/) {
 2724:         $authformcurrent=$authformloc;
 2725:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2726:             push(@authform_others,$authformkrb);
 2727:         }
 2728:         if ($can_assign{'int'}) {
 2729:             push(@authform_others,$authformint);
 2730:         }
 2731:         if ($can_assign{'lti'}) {
 2732:             push(@authform_others,$authformlti);
 2733:         }
 2734:         if ($can_assign{'loc'}) {
 2735:             $show_override_msg = 1;
 2736:         }
 2737:     } elsif ($currentauth=~/^lti:/) {
 2738:         $authformcurrent=$authformlti;
 2739:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2740:             push(@authform_others,$authformkrb);
 2741:         }
 2742:         if ($can_assign{'int'}) {
 2743:             push(@authform_others,$authformint);
 2744:         }
 2745:         if ($can_assign{'loc'}) {
 2746:             push(@authform_others,$authformloc);
 2747:         }
 2748:     }
 2749:     if ($show_override_msg) {
 2750:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2751:                            '</td></tr>'."\n".
 2752:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2753:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2754:                            '<td align="right"><span class="LC_cusr_emph">'.
 2755:                             &mt('will override current values').
 2756:                             '</span></td></tr></table>';
 2757:     }
 2758:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2759: }
 2760: 
 2761: sub personal_data_display {
 2762:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$readonly,$rolesarray,$now,
 2763:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2764:     my ($output,%userenv,%canmodify,%canmodify_status,$disabled);
 2765:     my @userinfo = ('firstname','middlename','lastname','generation',
 2766:                     'permanentemail','id');
 2767:     my $rowcount = 0;
 2768:     my $editable = 0;
 2769:     my %textboxsize = (
 2770:                        firstname      => '15',
 2771:                        middlename     => '15',
 2772:                        lastname       => '15',
 2773:                        generation     => '5',
 2774:                        permanentemail => '25',
 2775:                        id             => '15',
 2776:                       );
 2777: 
 2778:     my %lt=&Apache::lonlocal::texthash(
 2779:                 'pd'             => "Personal Data",
 2780:                 'firstname'      => "First Name",
 2781:                 'middlename'     => "Middle Name",
 2782:                 'lastname'       => "Last Name",
 2783:                 'generation'     => "Generation",
 2784:                 'permanentemail' => "Permanent e-mail address",
 2785:                 'id'             => "Student/Employee ID",
 2786:                 'lg'             => "Login Data",
 2787:                 'inststatus'     => "Affiliation",
 2788:                 'email'          => 'E-mail address',
 2789:                 'valid'          => 'Validation',
 2790:                 'username'       => 'Username',
 2791:     );
 2792: 
 2793:     %canmodify_status =
 2794:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2795:                                                    ['inststatus'],$rolesarray);
 2796:     if (!$newuser) {
 2797:         # Get the users information
 2798:         %userenv = &Apache::lonnet::get('environment',
 2799:                    ['firstname','middlename','lastname','generation',
 2800:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2801:         %canmodify =
 2802:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2803:                                                        \@userinfo,$rolesarray);
 2804:     } elsif ($context eq 'selfcreate') {
 2805:         if ($newuser eq 'email') {
 2806:             if (ref($emailusername) eq 'HASH') {
 2807:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2808:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2809:                     @userinfo = ();
 2810:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2811:                         foreach my $field (@{$infofields}) { 
 2812:                             if ($emailusername->{$usertype}->{$field}) {
 2813:                                 push(@userinfo,$field);
 2814:                                 $canmodify{$field} = 1;
 2815:                                 unless ($textboxsize{$field}) {
 2816:                                     $textboxsize{$field} = 25;
 2817:                                 }
 2818:                                 unless ($lt{$field}) {
 2819:                                     $lt{$field} = $infotitles->{$field};
 2820:                                 }
 2821:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2822:                                     $lt{$field} .= '<b>*</b>';
 2823:                                 }
 2824:                             }
 2825:                         }
 2826:                     }
 2827:                 }
 2828:             }
 2829:         } else {
 2830:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2831:                                                $inst_results,$rolesarray);
 2832:         }
 2833:     } elsif ($readonly) {
 2834:         $disabled = ' disabled="disabled"';
 2835:     }
 2836: 
 2837:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2838:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2839:               &Apache::lonhtmlcommon::start_pick_box();
 2840:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2841:         my $size = 25;
 2842:         if ($condition) {
 2843:             if ($condition =~ /^\@[^\@]+$/) {
 2844:                 $size = 10;
 2845:             } else {
 2846:                 undef($condition);
 2847:             }
 2848:         } 
 2849:         if ($excluded) {
 2850:             unless ($excluded =~ /^\@[^\@]+$/) {
 2851:                 undef($condition);
 2852:             }
 2853:         }
 2854:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2855:                                                      'LC_oddrow_value')."\n".
 2856:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2857:         if ($condition) {
 2858:             $output .= $condition;
 2859:         } elsif ($excluded) {
 2860:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2861:                                                                      $excluded).'</span>';
 2862:         }
 2863:         if ($usernameset eq 'first') {
 2864:             $output .= '<br /><span style="font-size: smaller">';
 2865:             if ($condition) {
 2866:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2867:                                       $condition);
 2868:             } else {
 2869:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2870:             }
 2871:             $output .= '</span>';
 2872:         }
 2873:         $rowcount ++;
 2874:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2875:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2876:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2877:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2878:                                                     'LC_pick_box_title',
 2879:                                                     'LC_oddrow_value')."\n".
 2880:                    $upassone."\n".
 2881:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2882:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2883:                                                      'LC_pick_box_title',
 2884:                                                      'LC_oddrow_value')."\n".
 2885:                    $upasstwo.
 2886:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2887:         if ($usernameset eq 'free') {
 2888:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2889:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2890:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2891:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2892:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2893:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2894:                        &mt('No').'</label></span>'."\n".
 2895:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2896:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2897:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2898:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2899:             $rowcount ++;
 2900:         }
 2901:     }
 2902:     foreach my $item (@userinfo) {
 2903:         my $rowtitle = $lt{$item};
 2904:         my $hiderow = 0;
 2905:         if ($item eq 'generation') {
 2906:             $rowtitle = $genhelp.$rowtitle;
 2907:         }
 2908:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2909:         if ($newuser) {
 2910:             if (ref($inst_results) eq 'HASH') {
 2911:                 if ($inst_results->{$item} ne '') {
 2912:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2913:                 } else {
 2914:                     if ($context eq 'selfcreate') {
 2915:                         if ($canmodify{$item}) {
 2916:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2917:                             $editable ++;
 2918:                         } else {
 2919:                             $hiderow = 1;
 2920:                         }
 2921:                     } else {
 2922:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2923:                     }
 2924:                 }
 2925:             } else {
 2926:                 if ($context eq 'selfcreate') {
 2927:                     if ($canmodify{$item}) {
 2928:                         if ($newuser eq 'email') {
 2929:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2930:                         } else {
 2931:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2932:                         }
 2933:                         $editable ++;
 2934:                     } else {
 2935:                         $hiderow = 1;
 2936:                     }
 2937:                 } else {
 2938:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2939:                 }
 2940:             }
 2941:         } else {
 2942:             if ($canmodify{$item}) {
 2943:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2944:                 if (($item eq 'id') && (!$newuser)) {
 2945:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2946:                 }
 2947:             } else {
 2948:                 $row .= $userenv{$item};
 2949:             }
 2950:         }
 2951:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2952:         if (!$hiderow) {
 2953:             $output .= $row;
 2954:             $rowcount ++;
 2955:         }
 2956:     }
 2957:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2958:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2959:         if (ref($types) eq 'ARRAY') {
 2960:             if (@{$types} > 0) {
 2961:                 my ($hiderow,$shown);
 2962:                 if ($canmodify_status{'inststatus'}) {
 2963:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2964:                 } else {
 2965:                     if ($userenv{'inststatus'} eq '') {
 2966:                         $hiderow = 1;
 2967:                     } else {
 2968:                         my @showitems;
 2969:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2970:                             if (exists($usertypes->{$item})) {
 2971:                                 push(@showitems,$usertypes->{$item});
 2972:                             } else {
 2973:                                 push(@showitems,$item);
 2974:                             }
 2975:                         }
 2976:                         if (@showitems) {
 2977:                             $shown = join(', ',@showitems);
 2978:                         } else {
 2979:                             $hiderow = 1;
 2980:                         }
 2981:                     }
 2982:                 }
 2983:                 if (!$hiderow) {
 2984:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2985:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2986:                     if ($context eq 'selfcreate') {
 2987:                         $rowcount ++;
 2988:                     }
 2989:                     $output .= $row;
 2990:                 }
 2991:             }
 2992:         }
 2993:     }
 2994:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2995:         if ($captchaform) {
 2996:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2997:                                                          'LC_pick_box_title')."\n".
 2998:                        $captchaform."\n".'<br /><br />'.
 2999:                        &Apache::lonhtmlcommon::row_closure(1); 
 3000:             $rowcount ++;
 3001:         }
 3002:         if ($showsubmit) {
 3003:             my $submit_text = &mt('Create account');
 3004:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 3005:                        '<br /><input type="submit" name="createaccount" value="'.
 3006:                        $submit_text.'" />';
 3007:             if ($usertype ne '') {
 3008:                 $output .= '<input type="hidden" name="type" value="'.
 3009:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 3010:             }
 3011:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 3012:         }
 3013:     }
 3014:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 3015:     if (wantarray) {
 3016:         if ($context eq 'selfcreate') {
 3017:             return($output,$rowcount,$editable);
 3018:         } else {
 3019:             return $output;
 3020:         }
 3021:     } else {
 3022:         return $output;
 3023:     }
 3024: }
 3025: 
 3026: sub pick_inst_statuses {
 3027:     my ($curr,$usertypes,$types) = @_;
 3028:     my ($output,$rem,@currtypes);
 3029:     if ($curr ne '') {
 3030:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 3031:     }
 3032:     my $numinrow = 2;
 3033:     if (ref($types) eq 'ARRAY') {
 3034:         $output = '<table>';
 3035:         my $lastcolspan; 
 3036:         for (my $i=0; $i<@{$types}; $i++) {
 3037:             if (defined($usertypes->{$types->[$i]})) {
 3038:                 my $rem = $i%($numinrow);
 3039:                 if ($rem == 0) {
 3040:                     if ($i<@{$types}-1) {
 3041:                         if ($i > 0) { 
 3042:                             $output .= '</tr>';
 3043:                         }
 3044:                         $output .= '<tr>';
 3045:                     }
 3046:                 } elsif ($i==@{$types}-1) {
 3047:                     my $colsleft = $numinrow - $rem;
 3048:                     if ($colsleft > 1) {
 3049:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 3050:                     }
 3051:                 }
 3052:                 my $check = ' ';
 3053:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 3054:                     $check = ' checked="checked" ';
 3055:                 }
 3056:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 3057:                            '<span class="LC_nobreak"><label>'.
 3058:                            '<input type="checkbox" name="inststatus" '.
 3059:                            'value="'.$types->[$i].'"'.$check.'/>'.
 3060:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 3061:             }
 3062:         }
 3063:         $output .= '</tr></table>';
 3064:     }
 3065:     return $output;
 3066: }
 3067: 
 3068: sub selfcreate_canmodify {
 3069:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 3070:     if (ref($inst_results) eq 'HASH') {
 3071:         my @inststatuses = &get_inststatuses($inst_results);
 3072:         if (@inststatuses == 0) {
 3073:             @inststatuses = ('default');
 3074:         }
 3075:         $rolesarray = \@inststatuses;
 3076:     }
 3077:     my %canmodify =
 3078:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 3079:                                                    $rolesarray);
 3080:     return %canmodify;
 3081: }
 3082: 
 3083: sub get_inststatuses {
 3084:     my ($insthashref) = @_;
 3085:     my @inststatuses = ();
 3086:     if (ref($insthashref) eq 'HASH') {
 3087:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 3088:             @inststatuses = @{$insthashref->{'inststatus'}};
 3089:         }
 3090:     }
 3091:     return @inststatuses;
 3092: }
 3093: 
 3094: # ================================================================= Phase Three
 3095: sub update_user_data {
 3096:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 3097:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 3098:                                           $env{'form.ccdomain'});
 3099:     # Error messages
 3100:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 3101:     my $end       = '</span><br /><br />';
 3102:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 3103:                     "'$env{'form.prevphase'}','modify')".'" />'.
 3104:                     &mt('Return to previous page').'</a>'.
 3105:                     &Apache::loncommon::end_page();
 3106:     my $now = time;
 3107:     my $title;
 3108:     if (exists($env{'form.makeuser'})) {
 3109: 	$title='Set Privileges for New User';
 3110:     } else {
 3111:         $title='Modify User Privileges';
 3112:     }
 3113:     my $newuser = 0;
 3114:     my ($jsback,$elements) = &crumb_utilities();
 3115:     my $jscript = '<script type="text/javascript">'."\n".
 3116:                   '// <![CDATA['."\n".
 3117:                   $jsback."\n".
 3118:                   '// ]]>'."\n".
 3119:                   '</script>'."\n";
 3120:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 3121:     push (@{$brcrum},
 3122:              {href => "javascript:backPage(document.userupdate)",
 3123:               text => $breadcrumb_text{'search'},
 3124:               faq  => 282,
 3125:               bug  => 'Instructor Interface',}
 3126:              );
 3127:     if ($env{'form.prevphase'} eq 'userpicked') {
 3128:         push(@{$brcrum},
 3129:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 3130:                 text => $breadcrumb_text{'userpicked'},
 3131:                 faq  => 282,
 3132:                 bug  => 'Instructor Interface',});
 3133:     }
 3134:     my $helpitem = 'Course_Change_Privileges';
 3135:     if ($env{'form.action'} eq 'singlestudent') {
 3136:         $helpitem = 'Course_Add_Student';
 3137:     } elsif ($context eq 'author') {
 3138:         $helpitem = 'Author_Change_Privileges';
 3139:     } elsif ($context eq 'domain') {
 3140:         $helpitem = 'Domain_Change_Privileges';
 3141:     }
 3142:     push(@{$brcrum}, 
 3143:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 3144:              text => $breadcrumb_text{'modify'},
 3145:              faq  => 282,
 3146:              bug  => 'Instructor Interface',},
 3147:             {href => "/adm/createuser",
 3148:              text => "Result",
 3149:              faq  => 282,
 3150:              bug  => 'Instructor Interface',
 3151:              help => $helpitem});
 3152:     my $args = {bread_crumbs          => $brcrum,
 3153:                 bread_crumbs_component => 'User Management'};
 3154:     if ($env{'form.popup'}) {
 3155:         $args->{'no_nav_bar'} = 1;
 3156:     }
 3157:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 3158:     $r->print(&update_result_form($uhome));
 3159:     # Check Inputs
 3160:     if (! $env{'form.ccuname'} ) {
 3161: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 3162: 	return;
 3163:     }
 3164:     if (  $env{'form.ccuname'} ne 
 3165: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 3166: 	$r->print($error.&mt('Invalid login name.').'  '.
 3167: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 3168: 		  $end.$rtnlink);
 3169: 	return;
 3170:     }
 3171:     if (! $env{'form.ccdomain'}       ) {
 3172: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 3173: 	return;
 3174:     }
 3175:     if (  $env{'form.ccdomain'} ne
 3176: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 3177: 	$r->print($error.&mt('Invalid domain name.').'  '.
 3178: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 3179: 		  $end.$rtnlink);
 3180: 	return;
 3181:     }
 3182:     if ($uhome eq 'no_host') {
 3183:         $newuser = 1;
 3184:     }
 3185:     if (! exists($env{'form.makeuser'})) {
 3186:         # Modifying an existing user, so check the validity of the name
 3187:         if ($uhome eq 'no_host') {
 3188:             $r->print(
 3189:                 $error
 3190:                .'<p class="LC_error">'
 3191:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 3192:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 3193:                .'</p>');
 3194:             return;
 3195:         }
 3196:     }
 3197:     # Determine authentication method and password for the user being modified
 3198:     my $amode='';
 3199:     my $genpwd='';
 3200:     if ($env{'form.login'} eq 'krb') {
 3201: 	$amode='krb';
 3202: 	$amode.=$env{'form.krbver'};
 3203: 	$genpwd=$env{'form.krbarg'};
 3204:     } elsif ($env{'form.login'} eq 'int') {
 3205: 	$amode='internal';
 3206: 	$genpwd=$env{'form.intarg'};
 3207:     } elsif ($env{'form.login'} eq 'fsys') {
 3208: 	$amode='unix';
 3209: 	$genpwd=$env{'form.fsysarg'};
 3210:     } elsif ($env{'form.login'} eq 'loc') {
 3211: 	$amode='localauth';
 3212: 	$genpwd=$env{'form.locarg'};
 3213: 	$genpwd=" " if (!$genpwd);
 3214:     } elsif ($env{'form.login'} eq 'lti') {
 3215:         $amode='lti';
 3216:         $genpwd=" ";
 3217:     } elsif (($env{'form.login'} eq 'nochange') ||
 3218:              ($env{'form.login'} eq ''        )) { 
 3219:         # There is no need to tell the user we did not change what they
 3220:         # did not ask us to change.
 3221:         # If they are creating a new user but have not specified login
 3222:         # information this will be caught below.
 3223:     } else {
 3224:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 3225:             return;
 3226:     }
 3227: 
 3228:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 3229:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 3230:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 3231:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 3232: 
 3233:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 3234:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3235:     my @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
 3236:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 3237:     my @requestauthor = ('requestauthor');
 3238:     my @authordefaults = ('webdav','editors');
 3239:     my ($othertitle,$usertypes,$types) = 
 3240:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 3241:     my %canmodify_status =
 3242:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 3243:                                                    ['inststatus']);
 3244:     if ($env{'form.makeuser'}) {
 3245: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 3246:         # Check for the authentication mode and password
 3247:         if (! $amode || ! $genpwd) {
 3248: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 3249: 	    return;
 3250: 	}
 3251:         # Determine desired host
 3252:         my $desiredhost = $env{'form.hserver'};
 3253:         if (lc($desiredhost) eq 'default') {
 3254:             $desiredhost = undef;
 3255:         } else {
 3256:             my %home_servers = 
 3257: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 3258:             if (! exists($home_servers{$desiredhost})) {
 3259:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 3260:                 return;
 3261:             }
 3262:         }
 3263:         # Check ID format
 3264:         my %checkhash;
 3265:         my %checks = ('id' => 1);
 3266:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 3267:             'newuser' => $newuser, 
 3268:             'id' => $env{'form.cid'},
 3269:         );
 3270:         if ($env{'form.cid'} ne '') {
 3271:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 3272:                                           \%rulematch,\%inst_results,\%curr_rules);
 3273:             if (ref($alerts{'id'}) eq 'HASH') {
 3274:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3275:                     my $domdesc =
 3276:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 3277:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 3278:                         my $userchkmsg;
 3279:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 3280:                             $userchkmsg  = 
 3281:                                 &Apache::loncommon::instrule_disallow_msg('id',
 3282:                                                                     $domdesc,1).
 3283:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 3284:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 3285:                         }
 3286:                         $r->print($error.&mt('Invalid ID format').$end.
 3287:                                   $userchkmsg.$rtnlink);
 3288:                         return;
 3289:                     }
 3290:                 }
 3291:             }
 3292:         }
 3293:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 3294: 	# Call modifyuser
 3295: 	my $result = &Apache::lonnet::modifyuser
 3296: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 3297:              $amode,$genpwd,$env{'form.cfirstname'},
 3298:              $env{'form.cmiddlename'},$env{'form.clastname'},
 3299:              $env{'form.cgeneration'},undef,$desiredhost,
 3300:              $env{'form.cpermanentemail'});
 3301: 	$r->print(&mt('Generating user').': '.$result);
 3302:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 3303:                                                $env{'form.ccdomain'});
 3304:         my (%changeHash,%newcustom,%changed,%changedinfo);
 3305:         if ($uhome ne 'no_host') {
 3306:             if ($context eq 'domain') {
 3307:                 foreach my $name ('portfolio','author') {
 3308:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3309:                         if ($env{'form.'.$name.'quota'} eq '') {
 3310:                             $newcustom{$name.'quota'} = 0;
 3311:                         } else {
 3312:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 3313:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 3314:                         }
 3315:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 3316:                             $changed{$name.'quota'} = 1;
 3317:                         }
 3318:                     }
 3319:                 }
 3320:                 foreach my $item (@usertools) {
 3321:                     if ($env{'form.custom'.$item} == 1) {
 3322:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3323:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3324:                                                      \%changeHash,'tools');
 3325:                     }
 3326:                 }
 3327:                 foreach my $item (@requestcourses) {
 3328:                     if ($env{'form.custom'.$item} == 1) {
 3329:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3330:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3331:                             $newcustom{$item} .= '=';
 3332:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3333:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3334:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3335:                             }
 3336:                         }
 3337:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3338:                                                       \%changeHash,'requestcourses');
 3339:                     }
 3340:                 }
 3341:                 if ($env{'form.customrequestauthor'} == 1) {
 3342:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3343:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3344:                                                     $newcustom{'requestauthor'},
 3345:                                                     \%changeHash,'requestauthor');
 3346:                 }
 3347:                 if ($env{'form.customeditors'} == 1) {
 3348:                     my @editors;
 3349:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 3350:                     if (@posseditors) {
 3351:                         foreach my $editor (@posseditors) {
 3352:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 3353:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 3354:                                     push(@editors,$editor);
 3355:                                 }
 3356:                             }
 3357:                         }
 3358:                     }
 3359:                     if (@editors) {
 3360:                         @editors = sort(@editors);
 3361:                         $changed{'editors'} = &tool_admin('editors',join(',',@editors),
 3362:                                                           \%changeHash,'authordefaults');
 3363:                     }
 3364:                 }
 3365:                 if ($env{'form.customwebdav'} == 1) {
 3366:                     $newcustom{'webdav'} = $env{'form.authordefaults_webdav'};
 3367:                     $changed{'webdav'} = &tool_admin('webdav',$newcustom{'webdav'},
 3368:                                                   \%changeHash,'authordefaults');
 3369:                 }
 3370:             }
 3371:             if ($canmodify_status{'inststatus'}) {
 3372:                 if (exists($env{'form.inststatus'})) {
 3373:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3374:                     if (@inststatuses > 0) {
 3375:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3376:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3377:                     }
 3378:                 }
 3379:             }
 3380:             if (keys(%changed)) {
 3381:                 foreach my $item (@userinfo) {
 3382:                     $changeHash{$item}  = $env{'form.c'.$item};
 3383:                 }
 3384:                 my $chgresult =
 3385:                      &Apache::lonnet::put('environment',\%changeHash,
 3386:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3387:             }
 3388:         }
 3389:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3390:                   &Apache::lonnet::hostname($uhome));
 3391:     } elsif (($env{'form.login'} ne 'nochange') &&
 3392:              ($env{'form.login'} ne ''        )) {
 3393: 	# Modify user privileges
 3394:         if (! $amode || ! $genpwd) {
 3395: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3396: 	    return;
 3397: 	}
 3398: 	# Only allow authentication modification if the person has authority
 3399: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3400: 	    $r->print('Modifying authentication: '.
 3401:                       &Apache::lonnet::modifyuserauth(
 3402: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3403:                        $amode,$genpwd));
 3404:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3405: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3406: 	} else {
 3407: 	    # Okay, this is a non-fatal error.
 3408: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3409: 	}
 3410:     } elsif (($env{'form.intarg'} ne '') &&
 3411:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3412:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3413:         $r->print('Modifying authentication: '.
 3414:                   &Apache::lonnet::modifyuserauth(
 3415:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3416:                   'internal',$env{'form.intarg'}));
 3417:     }
 3418:     $r->rflush(); # Finish display of header before time consuming actions start
 3419:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3420:     ##
 3421:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3422:     if ($context eq 'course') {
 3423:         ($cnum,$cdom) =
 3424:             &Apache::lonuserutils::get_course_identity();
 3425:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3426:         if ($showcredits) {
 3427:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3428:         }
 3429:     }
 3430:     if (! $env{'form.makeuser'} ) {
 3431:         # Check for need to change
 3432:         my %userenv = &Apache::lonnet::get
 3433:             ('environment',['firstname','middlename','lastname','generation',
 3434:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3435:              'tools.aboutme','tools.blog','tools.webdav',
 3436:              'tools.portfolio','tools.timezone','tools.portaccess',
 3437:              'authormanagers','authoreditors','requestauthor',
 3438:              'requestcourses.official','requestcourses.unofficial',
 3439:              'requestcourses.community','requestcourses.textbook',
 3440:              'requestcourses.placement','requestcourses.lti',
 3441:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3442:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3443:              'reqcrsotherdom.placement','domcoord.author'],
 3444:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3445:         my ($tmp) = keys(%userenv);
 3446:         if ($tmp =~ /^(con_lost|error)/i) { 
 3447:             %userenv = ();
 3448:         }
 3449:         unless (($userenv{'domcoord.author'} eq 'blocked') &&
 3450:                 (($env{'user.name'} ne $env{'form.ccuname'}) ||
 3451:                  ($env{'user.domain'} ne $env{'form.ccdomain'}))) {
 3452:             push(@authordefaults,'managers');
 3453:         }
 3454:         my $no_forceid_alert;
 3455:         # Check to see if user information can be changed
 3456:         my %domconfig =
 3457:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3458:                                      $env{'form.ccdomain'});
 3459:         my @statuses = ('active','future');
 3460:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3461:         my ($auname,$audom);
 3462:         if ($context eq 'author') {
 3463:             $auname = $env{'user.name'};
 3464:             $audom = $env{'user.domain'};     
 3465:         }
 3466:         foreach my $item (keys(%roles)) {
 3467:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3468:             if ($context eq 'course') {
 3469:                 if ($cnum ne '' && $cdom ne '') {
 3470:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3471:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3472:                             push(@userroles,$role);
 3473:                         }
 3474:                     }
 3475:                 }
 3476:             } elsif ($context eq 'author') {
 3477:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3478:                     if (!grep(/^\Q$role\E$/,@userroles)) {
 3479:                         push(@userroles,$role);
 3480:                     }
 3481:                 }
 3482:             }
 3483:         }
 3484:         if ($env{'form.action'} eq 'singlestudent') {
 3485:             if (!grep(/^st$/,@userroles)) {
 3486:                 push(@userroles,'st');
 3487:             }
 3488:         } else {
 3489:             # Check for course or co-author roles being activated or re-enabled
 3490:             if ($context eq 'author' || $context eq 'course') {
 3491:                 foreach my $key (keys(%env)) {
 3492:                     if ($context eq 'author') {
 3493:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3494:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3495:                                 push(@userroles,$1);
 3496:                             }
 3497:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3498:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3499:                                 push(@userroles,$1);
 3500:                             }
 3501:                         }
 3502:                     } elsif ($context eq 'course') {
 3503:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3504:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3505:                                 push(@userroles,$1);
 3506:                             }
 3507:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3508:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3509:                                 push(@userroles,$1);
 3510:                             }
 3511:                         }
 3512:                     }
 3513:                 }
 3514:             }
 3515:         }
 3516:         #Check to see if we can change personal data for the user 
 3517:         my (@mod_disallowed,@longroles);
 3518:         foreach my $role (@userroles) {
 3519:             if ($role eq 'cr') {
 3520:                 push(@longroles,'Custom');
 3521:             } else {
 3522:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3523:             }
 3524:         }
 3525:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3526:         foreach my $item (@userinfo) {
 3527:             # Strip leading and trailing whitespace
 3528:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3529:             if (!$canmodify{$item}) {
 3530:                 if (defined($env{'form.c'.$item})) {
 3531:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3532:                         push(@mod_disallowed,$item);
 3533:                     }
 3534:                 }
 3535:                 $env{'form.c'.$item} = $userenv{$item};
 3536:             }
 3537:         }
 3538:         # Check to see if we can change the Student/Employee ID
 3539:         my $forceid = $env{'form.forceid'};
 3540:         my $recurseid = $env{'form.recurseid'};
 3541:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3542:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3543:                                             $env{'form.ccuname'});
 3544:         if (($uidhash{$env{'form.ccuname'}}) && 
 3545:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3546:             (!$forceid)) {
 3547:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3548:                 $env{'form.cid'} = $userenv{'id'};
 3549:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3550:                                    .'<br />'
 3551:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3552:                                    .'<br />'."\n";
 3553:             }
 3554:         }
 3555:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3556:             my $checkhash;
 3557:             my $checks = { 'id' => 1 };
 3558:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3559:                    { 'newuser' => $newuser,
 3560:                      'id'  => $env{'form.cid'}, 
 3561:                    };
 3562:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3563:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3564:             if (ref($alerts{'id'}) eq 'HASH') {
 3565:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3566:                    $env{'form.cid'} = $userenv{'id'};
 3567:                 }
 3568:             }
 3569:         }
 3570:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3571:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3572:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3573:             %oldsettingstatus,%newsettingstatus);
 3574:         @disporder = ('inststatus');
 3575:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3576:             push(@disporder,('requestcourses','requestauthor','authordefaults'));
 3577:         } else {
 3578:             push(@disporder,'reqcrsotherdom');
 3579:         }
 3580:         push(@disporder,('quota','tools'));
 3581:         $oldinststatus = $userenv{'inststatus'};
 3582:         foreach my $name ('portfolio','author') {
 3583:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3584:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3585:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3586:         }
 3587:         my %canshow;
 3588:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3589:             $canshow{'quota'} = 1;
 3590:         }
 3591:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3592:             $canshow{'tools'} = 1;
 3593:         }
 3594:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3595:             $canshow{'requestcourses'} = 1;
 3596:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3597:             $canshow{'reqcrsotherdom'} = 1;
 3598:         }
 3599:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3600:             $canshow{'inststatus'} = 1;
 3601:         }
 3602:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3603:             $canshow{'requestauthor'} = 1;
 3604:             $canshow{'authordefaults'} = 1;
 3605:         }
 3606:         my (%changeHash,%changed);
 3607:         if ($oldinststatus eq '') {
 3608:             $oldsettings{'inststatus'} = $othertitle; 
 3609:         } else {
 3610:             if (ref($usertypes) eq 'HASH') {
 3611:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3612:             } else {
 3613:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3614:             }
 3615:         }
 3616:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3617:         if ($canmodify_status{'inststatus'}) {
 3618:             $canshow{'inststatus'} = 1;
 3619:             if (exists($env{'form.inststatus'})) {
 3620:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3621:                 if (@inststatuses > 0) {
 3622:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3623:                     $changeHash{'inststatus'} = $newinststatus;
 3624:                     if ($newinststatus ne $oldinststatus) {
 3625:                         $changed{'inststatus'} = $newinststatus;
 3626:                         foreach my $name ('portfolio','author') {
 3627:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3628:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3629:                         }
 3630:                     }
 3631:                     if (ref($usertypes) eq 'HASH') {
 3632:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3633:                     } else {
 3634:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3635:                     }
 3636:                 }
 3637:             } else {
 3638:                 $newinststatus = '';
 3639:                 $changeHash{'inststatus'} = $newinststatus;
 3640:                 $newsettings{'inststatus'} = $othertitle;
 3641:                 if ($newinststatus ne $oldinststatus) {
 3642:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3643:                     foreach my $name ('portfolio','author') {
 3644:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3645:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3646:                     }
 3647:                 }
 3648:             }
 3649:         } elsif ($context ne 'selfcreate') {
 3650:             $canshow{'inststatus'} = 1;
 3651:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3652:         }
 3653:         foreach my $name ('portfolio','author') {
 3654:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3655:         }
 3656:         if ($context eq 'domain') {
 3657:             foreach my $name ('portfolio','author') {
 3658:                 if ($userenv{$name.'quota'} ne '') {
 3659:                     $oldquota{$name} = $userenv{$name.'quota'};
 3660:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3661:                         if ($env{'form.'.$name.'quota'} eq '') {
 3662:                             $newquota{$name} = 0;
 3663:                         } else {
 3664:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3665:                             $newquota{$name} =~ s/[^\d\.]//g;
 3666:                         }
 3667:                         if ($newquota{$name} != $oldquota{$name}) {
 3668:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3669:                                 $changed{$name.'quota'} = 1;
 3670:                             }
 3671:                         }
 3672:                     } else {
 3673:                         if (&quota_admin('',\%changeHash,$name)) {
 3674:                             $changed{$name.'quota'} = 1;
 3675:                             $newquota{$name} = $newdefquota{$name};
 3676:                             $newisdefault{$name} = 1;
 3677:                         }
 3678:                     }
 3679:                 } else {
 3680:                     $oldisdefault{$name} = 1;
 3681:                     $oldquota{$name} = $olddefquota{$name};
 3682:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3683:                         if ($env{'form.'.$name.'quota'} eq '') {
 3684:                             $newquota{$name} = 0;
 3685:                         } else {
 3686:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3687:                             $newquota{$name} =~ s/[^\d\.]//g;
 3688:                         }
 3689:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3690:                             $changed{$name.'quota'} = 1;
 3691:                         }
 3692:                     } else {
 3693:                         $newquota{$name} = $newdefquota{$name};
 3694:                         $newisdefault{$name} = 1;
 3695:                     }
 3696:                 }
 3697:                 if ($oldisdefault{$name}) {
 3698:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3699:                 }  else {
 3700:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3701:                 }
 3702:                 if ($newisdefault{$name}) {
 3703:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3704:                 } else {
 3705:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3706:                 }
 3707:             }
 3708:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3709:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3710:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3711:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3712:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3713:                 my ($isadv,$isauthor) =
 3714:                     &Apache::lonnet::is_advanced_user($env{'form.ccdomain'},$env{'form.ccuname'});
 3715:                 unless ($isauthor) {
 3716:                     &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3717:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3718:                 }
 3719:                 &tool_changes('authordefaults',\@authordefaults,\%oldsettings,\%oldsettingstext,
 3720:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3721:             } else {
 3722:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3723:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3724:             }
 3725:         }
 3726:         foreach my $item (@userinfo) {
 3727:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3728:                 $namechanged{$item} = 1;
 3729:             }
 3730:         }
 3731:         foreach my $name ('portfolio','author') {
 3732:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3733:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3734:         }
 3735:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3736:             my ($chgresult,$namechgresult);
 3737:             if (keys(%changed) > 0) {
 3738:                 $chgresult =
 3739:                     &Apache::lonnet::put('environment',\%changeHash,
 3740:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3741:                 if ($chgresult eq 'ok') {
 3742:                     my ($ca_mgr_del,%ca_mgr_add);
 3743:                     if ($changed{'managers'}) {
 3744:                         my (@adds,@dels);
 3745:                         if ($changeHash{'authormanagers'} eq '') {
 3746:                             @dels = split(/,/,$userenv{'authormanagers'});
 3747:                         } elsif ($userenv{'authormanagers'} eq '') {
 3748:                             @adds = split(/,/,$changeHash{'authormanagers'});
 3749:                         } else {
 3750:                             my @old = split(/,/,$userenv{'authormanagers'});
 3751:                             my @new = split(/,/,$changeHash{'authormanagers'});
 3752:                             my @diffs = &Apache::loncommon::compare_arrays(\@old,\@new);
 3753:                             if (@diffs) {
 3754:                                 foreach my $user (@diffs) {
 3755:                                     if (grep(/^\Q$user\E$/,@old)) {
 3756:                                         push(@dels,$user);
 3757:                                     } elsif (grep(/^\Q$user\E$/,@new)) {
 3758:                                         push(@adds,$user);
 3759:                                     }
 3760:                                 }
 3761:                             }
 3762:                         }
 3763:                         my $key = "internal.manager./$env{'form.ccdomain'}/$env{'form.ccuname'}";
 3764:                         if (@dels) {
 3765:                             foreach my $user (@dels) {
 3766:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3767:                                     &Apache::lonnet::del('environment',[$key],$2,$1);
 3768:                                 }
 3769:                             }
 3770:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3771:                             if (grep(/^\Q$curruser\E$/,@dels)) {
 3772:                                 $ca_mgr_del = $key;
 3773:                             }
 3774:                         }
 3775:                         if (@adds) {
 3776:                             foreach my $user (@adds) {
 3777:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3778:                                     &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 3779:                                 }
 3780:                             }
 3781:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3782:                             if (grep(/^\Q$curruser\E$/,@adds)) {
 3783:                                 $ca_mgr_add{$key} = 1;
 3784:                             }
 3785:                         }
 3786:                     }
 3787:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3788:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3789:                         my (%newenvhash,$got_domdefs,%domdefaults,$got_userenv,
 3790:                             %userenv);
 3791:                         my @fromenv = keys(%changed);
 3792:                         push(@fromenv,'inststatus');
 3793:                         foreach my $key (keys(%changed)) {
 3794:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3795:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3796:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3797:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3798:                                     $changeHash{'requestcourses.'.$key};
 3799:                                 if ($changeHash{'requestcourses.'.$key}) {
 3800:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3801:                                 } else {
 3802:                                     unless ($got_domdefs) {
 3803:                                         %domdefaults =
 3804:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3805:                                         $got_domdefs = 1;
 3806:                                     }
 3807:                                     unless ($got_userenv) {
 3808:                                         %userenv =
 3809:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3810:                                                                              $env{'user.name'},@fromenv);
 3811:                                         $got_userenv = 1;
 3812:                                     }
 3813:                                     $newenvhash{'environment.canrequest.'.$key} =
 3814:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3815:                                             $key,'reload','requestcourses',\%userenv,\%domdefaults);
 3816:                                 }
 3817:                             } elsif ($key eq 'requestauthor') {
 3818:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3819:                                 if ($changeHash{$key}) {
 3820:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3821:                                 } else {
 3822:                                     unless ($got_domdefs) {
 3823:                                         %domdefaults =
 3824:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3825:                                         $got_domdefs = 1;
 3826:                                     }
 3827:                                     unless ($got_userenv) {
 3828:                                         %userenv =
 3829:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3830:                                                                              $env{'user.name'},@fromenv);
 3831:                                         $got_userenv = 1;
 3832:                                     }
 3833:                                     $newenvhash{'environment.canrequest.author'} =
 3834:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3835:                                             $key,'reload','requestauthor',\%userenv,\%domdefaults);
 3836:                                 }
 3837:                             } elsif ($key eq 'editors') {
 3838:                                 $newenvhash{'environment.author'.$key} = $changeHash{'author'.$key};
 3839:                                 if ($env{'form.customeditors'}) {
 3840:                                     $newenvhash{'environment.editors'} = $changeHash{'author'.$key};
 3841:                                 } else {
 3842:                                     unless ($got_domdefs) {
 3843:                                         %domdefaults =
 3844:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3845:                                         $got_domdefs = 1;
 3846:                                     }
 3847:                                     if ($domdefaults{'editors'} ne '') {
 3848:                                         $newenvhash{'environment.editors'} = $domdefaults{'editors'};
 3849:                                     } else {
 3850:                                         $newenvhash{'environment.editors'} = 'edit,xml';
 3851:                                     }
 3852:                                 }
 3853:                             } elsif ($key ne 'quota') {
 3854:                                 $newenvhash{'environment.tools.'.$key} = 
 3855:                                     $changeHash{'tools.'.$key};
 3856:                                 if ($changeHash{'tools.'.$key} ne '') {
 3857:                                     $newenvhash{'environment.availabletools.'.$key} =
 3858:                                         $changeHash{'tools.'.$key};
 3859:                                 } else {
 3860:                                     unless ($got_domdefs) {
 3861:                                         %domdefaults =
 3862:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3863:                                         $got_domdefs = 1;
 3864:                                     }
 3865:                                     unless ($got_userenv) {
 3866:                                         %userenv =
 3867:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3868:                                                                              $env{'user.name'},@fromenv);
 3869:                                         $got_userenv = 1;
 3870:                                     }
 3871:                                     $newenvhash{'environment.availabletools.'.$key} =
 3872:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3873:                                             $key,'reload','tools',\%userenv,\%domdefaults);
 3874:                                 }
 3875:                             }
 3876:                         }
 3877:                         if (keys(%newenvhash)) {
 3878:                             &Apache::lonnet::appenv(\%newenvhash);
 3879:                         }
 3880:                     } else {
 3881:                         if ($ca_mgr_del) {
 3882:                             &Apache::lonnet::delenv($ca_mgr_del);
 3883:                         }
 3884:                         if (keys(%ca_mgr_add)) {
 3885:                             &Apache::lonnet::appenv(\%ca_mgr_add);
 3886:                         }
 3887:                     }
 3888:                     if ($changed{'aboutme'}) {
 3889:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3890:                                                                      $env{'form.ccdomain'});
 3891:                     }
 3892:                 }
 3893:             }
 3894:             if (keys(%namechanged) > 0) {
 3895:                 foreach my $field (@userinfo) {
 3896:                     $changeHash{$field}  = $env{'form.c'.$field};
 3897:                 }
 3898: # Make the change
 3899:                 $namechgresult =
 3900:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3901:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3902:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3903:                         $changeHash{'lastname'},$changeHash{'generation'},
 3904:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3905:                 %userupdate = (
 3906:                                lastname   => $env{'form.clastname'},
 3907:                                middlename => $env{'form.cmiddlename'},
 3908:                                firstname  => $env{'form.cfirstname'},
 3909:                                generation => $env{'form.cgeneration'},
 3910:                                id         => $env{'form.cid'},
 3911:                              );
 3912:             }
 3913:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3914:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3915:             # Tell the user we changed the name
 3916:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3917:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3918:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3919:                                   \%newsettingstext);
 3920:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3921:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3922:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3923:                     if (($recurseid) &&
 3924:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3925:                         my $idresult = 
 3926:                             &Apache::lonuserutils::propagate_id_change(
 3927:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3928:                                 \%userupdate);
 3929:                         $r->print('<br />'.$idresult.'<br />');
 3930:                     }
 3931:                 }
 3932:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3933:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3934:                     my %newenvhash;
 3935:                     foreach my $key (keys(%changeHash)) {
 3936:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3937:                     }
 3938:                     &Apache::lonnet::appenv(\%newenvhash);
 3939:                 }
 3940:             } else { # error occurred
 3941:                 $r->print(
 3942:                     '<p class="LC_error">'
 3943:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3944:                             '"'.$env{'form.ccuname'}.'"',
 3945:                             '"'.$env{'form.ccdomain'}.'"')
 3946:                    .'</p>');
 3947:             }
 3948:         } else { # End of if ($env ... ) logic
 3949:             # They did not want to change the users name, quota, tool availability,
 3950:             # or ability to request creation of courses, 
 3951:             # but we can still tell them what the name and quota and availabilities are  
 3952:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3953:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3954:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3955:         }
 3956:         if (@mod_disallowed) {
 3957:             my ($rolestr,$contextname);
 3958:             if (@longroles > 0) {
 3959:                 $rolestr = join(', ',@longroles);
 3960:             } else {
 3961:                 $rolestr = &mt('No roles');
 3962:             }
 3963:             if ($context eq 'course') {
 3964:                 $contextname = 'course';
 3965:             } elsif ($context eq 'author') {
 3966:                 $contextname = 'co-author';
 3967:             }
 3968:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3969:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3970:             foreach my $field (@mod_disallowed) {
 3971:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3972:             }
 3973:             $r->print('</ul>');
 3974:             if (@mod_disallowed == 1) {
 3975:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3976:             } else {
 3977:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3978:             }
 3979:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3980:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3981:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3982:                          ,'<a href="'.$helplink.'">','</a>')
 3983:                       .'<br />');
 3984:         }
 3985:         $r->print('<span class="LC_warning">'
 3986:                   .$no_forceid_alert
 3987:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3988:                   .'</span>');
 3989:     }
 3990:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3991:     if ($env{'form.action'} eq 'singlestudent') {
 3992:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3993:                                $crstype,$showcredits,$defaultcredits);
 3994:         my $linktext = ($crstype eq 'Community' ?
 3995:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3996:         $r->print(
 3997:             &Apache::lonhtmlcommon::actionbox([
 3998:                 '<a href="javascript:backPage(document.userupdate)">'
 3999:                .($crstype eq 'Community' ? 
 4000:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 4001:                .'</a>']));
 4002:     } else {
 4003:         my @rolechanges = &update_roles($r,$context,$showcredits);
 4004:         if (keys(%namechanged) > 0) {
 4005:             if ($context eq 'course') {
 4006:                 if (@userroles > 0) {
 4007:                     if ((@rolechanges == 0) || 
 4008:                         (!(grep(/^st$/,@rolechanges)))) {
 4009:                         if (grep(/^st$/,@userroles)) {
 4010:                             my $classlistupdated =
 4011:                                 &Apache::lonuserutils::update_classlist($cdom,
 4012:                                               $cnum,$env{'form.ccdomain'},
 4013:                                        $env{'form.ccuname'},\%userupdate);
 4014:                         }
 4015:                     }
 4016:                 }
 4017:             }
 4018:         }
 4019:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 4020:                                                      $env{'form.ccdomain'});
 4021:         if ($env{'form.popup'}) {
 4022:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 4023:         } else {
 4024:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 4025:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 4026:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 4027:         }
 4028:     }
 4029: }
 4030: 
 4031: sub display_userinfo {
 4032:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 4033:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 4034:         $newsetting,$newsettingtext) = @_;
 4035:     return unless (ref($order) eq 'ARRAY' &&
 4036:                    ref($canshow) eq 'HASH' && 
 4037:                    ref($requestcourses) eq 'ARRAY' && 
 4038:                    ref($requestauthor) eq 'ARRAY' &&
 4039:                    ref($usertools) eq 'ARRAY' && 
 4040:                    ref($userenv) eq 'HASH' &&
 4041:                    ref($changedhash) eq 'HASH' &&
 4042:                    ref($oldsetting) eq 'HASH' &&
 4043:                    ref($oldsettingtext) eq 'HASH' &&
 4044:                    ref($newsetting) eq 'HASH' &&
 4045:                    ref($newsettingtext) eq 'HASH');
 4046:     my %lt=&Apache::lonlocal::texthash(
 4047:          'ui'             => 'User Information',
 4048:          'uic'            => 'User Information Changed',
 4049:          'firstname'      => 'First Name',
 4050:          'middlename'     => 'Middle Name',
 4051:          'lastname'       => 'Last Name',
 4052:          'generation'     => 'Generation',
 4053:          'id'             => 'Student/Employee ID',
 4054:          'permanentemail' => 'Permanent e-mail address',
 4055:          'portfolioquota' => 'Disk space allocated to portfolio files',
 4056:          'authorquota'    => 'Disk space allocated to Authoring Space',
 4057:          'blog'           => 'Blog Availability',
 4058:          'webdav'         => 'WebDAV Availability',
 4059:          'aboutme'        => 'Personal Information Page Availability',
 4060:          'portfolio'      => 'Portfolio Availability',
 4061:          'portaccess'     => 'Portfolio Shareable',
 4062:          'timezone'       => 'Can set own Time Zone',
 4063:          'official'       => 'Can Request Official Courses',
 4064:          'unofficial'     => 'Can Request Unofficial Courses',
 4065:          'community'      => 'Can Request Communities',
 4066:          'textbook'       => 'Can Request Textbook Courses',
 4067:          'placement'      => 'Can Request Placement Tests',
 4068:          'lti'            => 'Can Request LTI Courses',
 4069:          'requestauthor'  => 'Can Request Author Role',
 4070:          'inststatus'     => "Affiliation",
 4071:          'prvs'           => 'Previous Value:',
 4072:          'chto'           => 'Changed To:',
 4073:          'editors'        => "Available Editors in Authoring Space",
 4074:          'managers'       => "Co-authors who can add/revoke roles",
 4075:          'edit'           => 'Standard editor (Edit)',
 4076:          'xml'            => 'Text editor (EditXML)',
 4077:          'daxe'           => 'Daxe editor (Daxe)',
 4078:     );
 4079:     if ($changed) {
 4080:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 4081:                 &Apache::loncommon::start_data_table().
 4082:                 &Apache::loncommon::start_data_table_header_row());
 4083:         $r->print("<th>&nbsp;</th>\n");
 4084:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 4085:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 4086:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4087:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 4088: 
 4089:         foreach my $item (@userinfo) {
 4090:             my $value = $env{'form.c'.$item};
 4091:             #show changes only:
 4092:             unless ($value eq $userenv->{$item}){
 4093:                 $r->print(&Apache::loncommon::start_data_table_row());
 4094:                 $r->print("<td>$lt{$item}</td>\n");
 4095:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 4096:                 $r->print("<td>$value </td>\n");
 4097:                 $r->print(&Apache::loncommon::end_data_table_row());
 4098:             }
 4099:         }
 4100:         foreach my $entry (@{$order}) {
 4101:             if ($canshow->{$entry}) {
 4102:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') ||
 4103:                     ($entry eq 'requestauthor') || ($entry eq 'authordefaults')) {
 4104:                     my @items;
 4105:                     if ($entry eq 'requestauthor') {
 4106:                         @items = ($entry);
 4107:                     } elsif ($entry eq 'authordefaults') {
 4108:                         @items = ('webdav','managers','editors');
 4109:                     } else {
 4110:                         @items = @{$requestcourses};
 4111:                     }
 4112:                     foreach my $item (@items) {
 4113:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 4114:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 4115:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 4116:                             $r->print("<td>$lt{$item}</td><td>\n");
 4117:                             unless ($item eq 'managers') {
 4118:                                 $r->print($oldsetting->{$item});
 4119:                             }
 4120:                             if ($oldsettingtext->{$item}) {
 4121:                                 if ($oldsetting->{$item}) {
 4122:                                     unless ($item eq 'managers') {
 4123:                                         $r->print(' -- ');
 4124:                                     }
 4125:                                 }
 4126:                                 $r->print($oldsettingtext->{$item});
 4127:                             }
 4128:                             $r->print("</td>\n<td>");
 4129:                             unless ($item eq 'managers') {
 4130:                                 $r->print($newsetting->{$item});
 4131:                             }
 4132:                             if ($newsettingtext->{$item}) {
 4133:                                 if ($newsetting->{$item}) {
 4134:                                     unless ($item eq 'managers') {
 4135:                                         $r->print(' -- ');
 4136:                                     }
 4137:                                 }
 4138:                                 $r->print($newsettingtext->{$item});
 4139:                             }
 4140:                             $r->print("</td>\n");
 4141:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4142:                         }
 4143:                     }
 4144:                 } elsif ($entry eq 'tools') {
 4145:                     foreach my $item (@{$usertools}) {
 4146:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 4147:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4148:                             $r->print("<td>$lt{$item}</td>\n");
 4149:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 4150:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 4151:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4152:                         }
 4153:                     }
 4154:                 } elsif ($entry eq 'quota') {
 4155:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 4156:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 4157:                         foreach my $name ('portfolio','author') {
 4158:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 4159:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4160:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 4161:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 4162:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 4163:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4164:                             }
 4165:                         }
 4166:                     }
 4167:                 } else {
 4168:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 4169:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4170:                         $r->print("<td>$lt{$entry}</td>\n");
 4171:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 4172:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 4173:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4174:                     }
 4175:                 }
 4176:             }
 4177:         }
 4178:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 4179:     } else {
 4180:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 4181:                   '<p>'.&mt('No changes made to user information').'</p>');
 4182:     }
 4183:     return;
 4184: }
 4185: 
 4186: sub tool_changes {
 4187:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 4188:         $changed,$newaccess,$newaccesstext) = @_;
 4189:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 4190:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 4191:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 4192:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 4193:         return;
 4194:     }
 4195:     my %reqdisplay = &requestchange_display();
 4196:     if ($context eq 'reqcrsotherdom') {
 4197:         my @options = ('approval','validate','autolimit');
 4198:         my $optregex = join('|',@options);
 4199:         my $cdom = $env{'request.role.domain'};
 4200:         foreach my $tool (@{$usertools}) {
 4201:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4202:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4203:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 4204:             my ($newop,$limit);
 4205:             if ($env{'form.'.$context.'_'.$tool}) {
 4206:                 $newop = $env{'form.'.$context.'_'.$tool};
 4207:                 if ($newop eq 'autolimit') {
 4208:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4209:                     $limit =~ s/\D+//g;
 4210:                     $newop .= '='.$limit;
 4211:                 }
 4212:             }
 4213:             if ($userenv->{$context.'.'.$tool} eq '') {
 4214:                 if ($newop) {
 4215:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 4216:                                                   $changeHash,$context);
 4217:                     if ($changed->{$tool}) {
 4218:                         if ($newop =~ /^autolimit/) {
 4219:                             if ($limit) {
 4220:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4221:                             } else {
 4222:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4223:                             }
 4224:                         } else {
 4225:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 4226:                         }
 4227:                     } else {
 4228:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4229:                     }
 4230:                 }
 4231:             } else {
 4232:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 4233:                 my @new;
 4234:                 my $changedoms;
 4235:                 foreach my $req (@curr) {
 4236:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 4237:                         my $oldop = $1;
 4238:                         if ($oldop =~ /^autolimit=(\d*)/) {
 4239:                             my $limit = $1;
 4240:                             if ($limit) {
 4241:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4242:                             } else {
 4243:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4244:                             }
 4245:                         } else {
 4246:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 4247:                         }
 4248:                         if ($oldop ne $newop) {
 4249:                             $changedoms = 1;
 4250:                             foreach my $item (@curr) {
 4251:                                 my ($reqdom,$option) = split(':',$item);
 4252:                                 unless ($reqdom eq $cdom) {
 4253:                                     push(@new,$item);
 4254:                                 }
 4255:                             }
 4256:                             if ($newop) {
 4257:                                 push(@new,$cdom.':'.$newop);
 4258:                             }
 4259:                             @new = sort(@new);
 4260:                         }
 4261:                         last;
 4262:                     }
 4263:                 }
 4264:                 if ((!$changedoms) && ($newop)) {
 4265:                     $changedoms = 1;
 4266:                     @new = sort(@curr,$cdom.':'.$newop);
 4267:                 }
 4268:                 if ($changedoms) {
 4269:                     my $newdomstr;
 4270:                     if (@new) {
 4271:                         $newdomstr = join(',',@new);
 4272:                     }
 4273:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 4274:                                                   $context);
 4275:                     if ($changed->{$tool}) {
 4276:                         if ($env{'form.'.$context.'_'.$tool}) {
 4277:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 4278:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4279:                                 $limit =~ s/\D+//g;
 4280:                                 if ($limit) {
 4281:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4282:                                 } else {
 4283:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4284:                                 }
 4285:                             } else {
 4286:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 4287:                             }
 4288:                         } else {
 4289:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4290:                         }
 4291:                     }
 4292:                 }
 4293:             }
 4294:         }
 4295:         return;
 4296:     }
 4297:     my %tooldesc = &Apache::lonlocal::texthash(
 4298:         'edit' => 'Standard editor (Edit)',
 4299:         'xml'  => 'Text editor (EditXML)',
 4300:         'daxe' => 'Daxe editor (Daxe)',
 4301:     );
 4302:     foreach my $tool (@{$usertools}) {
 4303:         my ($newval,$limit,$envkey);
 4304:         $envkey = $context.'.'.$tool;
 4305:         if ($context eq 'requestcourses') {
 4306:             $newval = $env{'form.crsreq_'.$tool};
 4307:             if ($newval eq 'autolimit') {
 4308:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 4309:                 $limit =~ s/\D+//g;
 4310:                 $newval .= '='.$limit;
 4311:             }
 4312:         } elsif ($context eq 'requestauthor') {
 4313:             $newval = $env{'form.'.$context};
 4314:             $envkey = $context;
 4315:         } elsif ($context eq 'authordefaults') {
 4316:             if ($tool eq 'editors') {
 4317:                 $envkey = 'authoreditors';
 4318:                 if ($env{'form.customeditors'} == 1) {
 4319:                     my @editors;
 4320:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 4321:                     if (@posseditors) {
 4322:                         foreach my $editor (@posseditors) {
 4323:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 4324:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 4325:                                     push(@editors,$editor);
 4326:                                 }
 4327:                             }
 4328:                         }
 4329:                     }
 4330:                     if (@editors) {
 4331:                         $newval = join(',',(sort(@editors)));
 4332:                     }
 4333:                 }
 4334:             } elsif ($tool eq 'managers') {
 4335:                 $envkey = 'authormanagers';
 4336:                 my @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 4337:                 if (@possibles) {
 4338:                     my %ca_roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},
 4339:                                                                  undef,['active','future'],['ca']);
 4340:                     if (keys(%ca_roles)) {
 4341:                         my @custommanagers;
 4342:                         foreach my $user (@possibles) {
 4343:                             if ($user =~ /^($match_username):($match_domain)$/) {
 4344:                                 if (exists($ca_roles{$user.':ca'})) {
 4345:                                     unless ($user eq $env{'form.ccuname'}.':'.$env{'form.ccdomain'}) {
 4346:                                         push(@custommanagers,$user);
 4347:                                     }
 4348:                                 }
 4349:                             }
 4350:                         }
 4351:                         if (@custommanagers) {
 4352:                             $newval = join(',',sort(@custommanagers));
 4353:                         }
 4354:                     }
 4355:                 }
 4356:             } elsif ($tool eq 'webdav') {
 4357:                 $envkey = 'tools.webdav';
 4358:                 $newval = $env{'form.'.$context.'_'.$tool};
 4359:             }
 4360:         } else {
 4361:             $newval = $env{'form.'.$context.'_'.$tool};
 4362:         }
 4363:         if ($userenv->{$envkey} ne '') {
 4364:             $oldaccess->{$tool} = &mt('custom');
 4365:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4366:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 4367:                     my $currlimit = $1;
 4368:                     if ($currlimit eq '') {
 4369:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4370:                     } else {
 4371:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 4372:                     }
 4373:                 } elsif ($userenv->{$envkey}) {
 4374:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4375:                 } else {
 4376:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4377:                 }
 4378:             } elsif ($context eq 'authordefaults') {
 4379:                 if ($tool eq 'managers') {
 4380:                     if ($userenv->{$envkey} eq '') {
 4381:                         $oldaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4382:                     } else {
 4383:                         my $managers = $userenv->{$envkey};
 4384:                         $managers =~ s/,/, /g;
 4385:                         $oldaccesstext->{$tool} = $managers;
 4386:                     }
 4387:                 } elsif ($tool eq 'editors') {
 4388:                     $oldaccesstext->{$tool} = &mt('can use: [_1]',
 4389:                                                   join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4390:                 } elsif ($tool eq 'webdav') {
 4391:                     if ($userenv->{$envkey}) {
 4392:                         $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4393:                     } else {
 4394:                         $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4395:                     }
 4396:                 }
 4397:             } else {
 4398:                 if ($userenv->{$envkey}) {
 4399:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4400:                 } else {
 4401:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4402:                 }
 4403:             }
 4404:             $changeHash->{$envkey} = $userenv->{$envkey};
 4405:             if (($env{'form.custom'.$tool} == 1) ||
 4406:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4407:                 if ($newval ne $userenv->{$envkey}) {
 4408:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4409:                                                     $context);
 4410:                     if ($changed->{$tool}) {
 4411:                         $newaccess->{$tool} = &mt('custom');
 4412:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4413:                             if ($newval =~ /^autolimit/) {
 4414:                                 if ($limit) {
 4415:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4416:                                 } else {
 4417:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4418:                                 }
 4419:                             } elsif ($newval) {
 4420:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 4421:                             } else {
 4422:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4423:                             }
 4424:                         } elsif ($context eq 'authordefaults') {
 4425:                             if ($tool eq 'editors') {
 4426:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4427:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$changeHash->{$envkey})));
 4428:                             } elsif ($tool eq 'managers') {
 4429:                                 if ($changeHash->{$envkey} eq '') {
 4430:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4431:                                 } else {
 4432:                                     my $managers = $changeHash->{$envkey};
 4433:                                     $managers =~ s/,/, /g;
 4434:                                     $newaccesstext->{$tool} = $managers;
 4435:                                 }
 4436:                             } elsif ($tool eq 'webdav') {
 4437:                                 if ($newval) {
 4438:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4439:                                 } else {
 4440:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4441:                                 }
 4442:                             }
 4443:                         } else {
 4444:                             if ($newval) {
 4445:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4446:                             } else {
 4447:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4448:                             }
 4449:                         }
 4450:                     } else {
 4451:                         $newaccess->{$tool} = $oldaccess->{$tool};
 4452:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4453:                             if ($userenv->{$envkey} =~ /^autolimit/) {
 4454:                                 if ($limit) {
 4455:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4456:                                 } else {
 4457:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4458:                                 }
 4459:                             } elsif ($userenv->{$envkey}) {
 4460:                                 $newaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4461:                             } else {
 4462:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4463:                             }
 4464:                         } elsif ($context eq 'authordefaults') {
 4465:                             if ($tool eq 'editors') {
 4466:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4467:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4468:                             } elsif ($tool eq 'managers') {
 4469:                                 if ($userenv->{$envkey} eq '') {
 4470:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4471:                                 } else {
 4472:                                     my $managers = $userenv->{$envkey};
 4473:                                     $managers =~ s/,/, /g;
 4474:                                     $newaccesstext->{$tool} = $managers;
 4475:                                 }
 4476:                             } elsif ($tool eq 'webdav') {
 4477:                                 if ($userenv->{$envkey}) {
 4478:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4479:                                 } else {
 4480:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4481:                                 }
 4482:                             }
 4483:                         } else {
 4484:                             if ($userenv->{$context.'.'.$tool}) {
 4485:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4486:                             } else {
 4487:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4488:                             }
 4489:                         }
 4490:                     }
 4491:                 } else {
 4492:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4493:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4494:                 }
 4495:             } else {
 4496:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 4497:                 if ($changed->{$tool}) {
 4498:                     $newaccess->{$tool} = &mt('default');
 4499:                 } else {
 4500:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4501:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4502:                         if ($newval =~ /^autolimit/) {
 4503:                             if ($limit) {
 4504:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4505:                             } else {
 4506:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4507:                             }
 4508:                         } elsif ($newval) {
 4509:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4510:                         } else {
 4511:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4512:                         }
 4513:                     } elsif ($context eq 'authordefaults') {
 4514:                         if ($tool eq 'editors') {
 4515:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4516:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4517:                         } elsif ($tool eq 'managers') {
 4518:                             if ($newval eq '') {
 4519:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4520:                             } else {
 4521:                                 my $managers = $newval;
 4522:                                 $managers =~ s/,/, /g;
 4523:                                 $newaccesstext->{$tool} = $managers;
 4524:                             }
 4525:                         } elsif ($tool eq 'webdav') {
 4526:                             if ($userenv->{$envkey}) {
 4527:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4528:                             } else {
 4529:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4530:                             }
 4531:                         }
 4532:                     } else {
 4533:                         if ($userenv->{$context.'.'.$tool}) {
 4534:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4535:                         } else {
 4536:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4537:                         }
 4538:                     }
 4539:                 }
 4540:             }
 4541:         } else {
 4542:             $oldaccess->{$tool} = &mt('default');
 4543:             if (($env{'form.custom'.$tool} == 1) ||
 4544:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4545:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4546:                                                 $context);
 4547:                 if ($changed->{$tool}) {
 4548:                     $newaccess->{$tool} = &mt('custom');
 4549:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4550:                         if ($newval =~ /^autolimit/) {
 4551:                             if ($limit) {
 4552:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4553:                             } else {
 4554:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4555:                             }
 4556:                         } elsif ($newval) {
 4557:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4558:                         } else {
 4559:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4560:                         }
 4561:                     } elsif ($context eq 'authordefaults') {
 4562:                         if ($tool eq 'managers') {
 4563:                             if ($newval eq '') {
 4564:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4565:                             } else {
 4566:                                 my $managers = $newval;
 4567:                                 $managers =~ s/,/, /g;
 4568:                                 $newaccesstext->{$tool} = $managers;
 4569:                             }
 4570:                         } elsif ($tool eq 'editors') {
 4571:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4572:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4573:                         } elsif ($tool eq 'webdav') {
 4574:                             if ($newval) {
 4575:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4576:                             } else {
 4577:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4578:                             }
 4579:                         }
 4580:                     } else {
 4581:                         if ($newval) {
 4582:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4583:                         } else {
 4584:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4585:                         }
 4586:                     }
 4587:                 } else {
 4588:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4589:                 }
 4590:             } else {
 4591:                 $newaccess->{$tool} = $oldaccess->{$tool};
 4592:             }
 4593:         }
 4594:     }
 4595:     return;
 4596: }
 4597: 
 4598: sub update_roles {
 4599:     my ($r,$context,$showcredits) = @_;
 4600:     my $now=time;
 4601:     my @rolechanges;
 4602:     my (%disallowed,%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 4603:         %pending,%reject,%notifydc,%status,%unauthorized,%currqueued);
 4604:     $got_role_approvals{$context} = '';
 4605:     $process_by{$context} = {};
 4606:     my @domroles = &Apache::lonuserutils::domain_roles();
 4607:     my @cstrroles = &Apache::lonuserutils::construction_space_roles();
 4608:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
 4609:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 4610:     foreach my $key (keys(%env)) {
 4611: 	next if (! $env{$key});
 4612:         next if ($key eq 'form.action');
 4613: 	# Revoke roles
 4614: 	if ($key=~/^form\.rev/) {
 4615: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 4616: # Revoke standard role
 4617: 		my ($scope,$role) = ($1,$2);
 4618: 		my $result =
 4619: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 4620: 						$env{'form.ccuname'},
 4621: 						$scope,$role,'','',$context);
 4622:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4623:                             &mt('Revoking [_1] in [_2]',
 4624:                                 &Apache::lonnet::plaintext($role),
 4625:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4626:                                 $result ne "ok").'<br />');
 4627:                 if ($result ne "ok") {
 4628:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4629:                 }
 4630: 		if ($role eq 'st') {
 4631: 		    my $result = 
 4632:                         &Apache::lonuserutils::classlist_drop($scope,
 4633:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4634: 			    $now);
 4635:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4636: 		}
 4637:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4638:                     push(@rolechanges,$role);
 4639:                 }
 4640: 	    }
 4641: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4642: # Revoke custom role
 4643:                 my $result = &Apache::lonnet::revokecustomrole(
 4644:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4645:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4646:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4647:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4648:                             $result ne 'ok').'<br />');
 4649:                 if ($result ne "ok") {
 4650:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4651:                 }
 4652:                 if (!grep(/^cr$/,@rolechanges)) {
 4653:                     push(@rolechanges,'cr');
 4654:                 }
 4655: 	    }
 4656: 	} elsif ($key=~/^form\.del/) {
 4657: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4658: # Delete standard role
 4659: 		my ($scope,$role) = ($1,$2);
 4660: 		my $result =
 4661: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4662: 						$env{'form.ccuname'},
 4663: 						$scope,$role,$now,0,1,'',
 4664:                                                 $context);
 4665:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4666:                             &mt('Deleting [_1] in [_2]',
 4667:                                 &Apache::lonnet::plaintext($role),
 4668:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4669:                             $result ne 'ok').'<br />');
 4670:                 if ($result ne "ok") {
 4671:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4672:                 }
 4673: 
 4674: 		if ($role eq 'st') {
 4675: 		    my $result = 
 4676:                         &Apache::lonuserutils::classlist_drop($scope,
 4677:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4678: 			    $now);
 4679: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4680: 		}
 4681:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4682:                     push(@rolechanges,$role);
 4683:                 }
 4684:             }
 4685: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4686:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4687: # Delete custom role
 4688:                 my $result =
 4689:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4690:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4691:                         0,1,$context);
 4692:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4693:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4694:                       $result ne "ok").'<br />');
 4695:                 if ($result ne "ok") {
 4696:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4697:                 }
 4698: 
 4699:                 if (!grep(/^cr$/,@rolechanges)) {
 4700:                     push(@rolechanges,'cr');
 4701:                 }
 4702:             }
 4703: 	} elsif ($key=~/^form\.ren/) {
 4704:             my $udom = $env{'form.ccdomain'};
 4705:             my $uname = $env{'form.ccuname'};
 4706: # Re-enable standard role
 4707: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4708:                 my $url = $1;
 4709:                 my $role = $2;
 4710:                 my $id = $url.'_'.$role;
 4711:                 my $logmsg;
 4712:                 my $output;
 4713:                 if ($role eq 'st') {
 4714:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4715:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4716:                         my $credits;
 4717:                         if ($showcredits) {
 4718:                             my $defaultcredits =
 4719:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4720:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4721:                         }
 4722:                         unless ($udom eq $cdom) {
 4723:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4724:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,$credits,
 4725:                                          \%process_by,\%instdoms,\%got_role_approvals,
 4726:                                          \%got_instdoms,\%reject,\%pending,\%notifydc,
 4727:                                          \%status,\%unauthorized,\%currqueued));
 4728:                         }
 4729:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4730:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4731:                             if ($result eq 'refused' && $logmsg) {
 4732:                                 $output = $logmsg;
 4733:                             } else { 
 4734:                                 $output = &mt('Error: [_1]',$result)."\n";
 4735:                             }
 4736:                         } else {
 4737:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4738:                                         &Apache::lonnet::plaintext($role),
 4739:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4740:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4741:                         }
 4742:                     }
 4743:                 } else {
 4744:                     my ($cdom,$cnum,$csec);
 4745:                     if (grep(/^\Q$role\E$/,@cstrroles)) {
 4746:                         ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_username)$});
 4747:                     } elsif (grep(/^\Q$role\E$/,@domroles)) {
 4748:                         ($cdom) = ($url =~ m{^/($match_domain)/$});
 4749:                     } elsif ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4750:                         ($cdom,$cnum,$csec) = ($1,$2,$3);
 4751:                     }
 4752:                     if ($cdom ne '') {
 4753:                         unless ($udom eq $cdom) {
 4754:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4755:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4756:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4757:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4758:                         }
 4759:                     }
 4760: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4761:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4762:                                $context);
 4763:                     $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4764:                                     &Apache::lonnet::plaintext($role),
 4765:                                     &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4766:                     if ($result ne "ok") {
 4767:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4768:                     }
 4769:                 }
 4770:                 $r->print($output);
 4771:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4772:                     push(@rolechanges,$role);
 4773:                 }
 4774: 	    }
 4775: # Re-enable custom role
 4776: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4777:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4778:                 my $id = $url.'_cr'."/$rdom/$rnam/$rolename";
 4779:                 my $role = "cr/$rdom/$rnam/$rolename";
 4780:                 if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4781:                     my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4782:                     unless ($udom eq $cdom) {
 4783:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4784:                                      $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4785:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4786:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4787:                     }
 4788:                 }
 4789:                 my $result = &Apache::lonnet::assigncustomrole(
 4790:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4791:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4792:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4793:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4794:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4795:                     $result ne "ok").'<br />');
 4796:                 if ($result ne "ok") {
 4797:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4798:                 }
 4799:                 if (!grep(/^cr$/,@rolechanges)) {
 4800:                     push(@rolechanges,'cr');
 4801:                 }
 4802:             }
 4803: 	} elsif ($key=~/^form\.act/) {
 4804:             my $udom = $env{'form.ccdomain'};
 4805:             my $uname = $env{'form.ccuname'};
 4806: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4807:                 # Activate a custom role
 4808: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4809: 		my $url='/'.$one.'/'.$two;
 4810:                 my $id = $url.'_cr/'."$three/$four/$five";
 4811:                 my $role = "cr/$three/$four/$five";
 4812: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4813: 
 4814:                 my $start = ( $env{'form.start_'.$full} ?
 4815:                               $env{'form.start_'.$full} :
 4816:                               $now );
 4817:                 my $end   = ( $env{'form.end_'.$full} ?
 4818:                               $env{'form.end_'.$full} :
 4819:                               0 );
 4820: 
 4821:                 # split multiple sections
 4822:                 my %sections = ();
 4823:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$five);
 4824:                 if ($num_sections == 0) {
 4825:                     unless ($udom eq $one) {
 4826:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4827:                                      $uname,$role,$start,$end,$one,$two,'','',\%process_by,
 4828:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4829:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4830:                     }
 4831:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4832:                 } else {
 4833: 		    my %curr_groups =
 4834: 			&Apache::longroup::coursegroups($one,$two);
 4835:                     my ($restricted,$numchanges);
 4836:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4837:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4838:                             exists($curr_groups{$sec})) {
 4839:                             $disallowed{$sec} = $url;
 4840:                             next;
 4841:                         }
 4842:                         my $securl = $url.'/'.$sec;
 4843:                         my $secid = $securl.'_cr'."/$three/$four/$five";
 4844:                         undef($restricted);
 4845:                         unless ($udom eq $one) {
 4846:                             next if (&Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4847:                                          $uname,$role,$start,$end,$one,$two,$sec,'',\%process_by,
 4848:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4849:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4850:                         }
 4851:                         $numchanges ++;
 4852: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4853:                     }
 4854:                     next unless ($numchanges);
 4855:                 }
 4856:                 if (!grep(/^cr$/,@rolechanges)) {
 4857:                     push(@rolechanges,'cr');
 4858:                 }
 4859: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4860: 		# Activate roles for sections with 3 id numbers
 4861: 		# set start, end times, and the url for the class
 4862: 		my ($one,$two,$three)=($1,$2,$3);
 4863: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ?
 4864: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} :
 4865: 			      $now );
 4866: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ?
 4867: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4868: 			      0 );
 4869: 		my $url='/'.$one.'/'.$two;
 4870:                 my $id = $url.'_'.$three;
 4871:                 # split multiple sections
 4872:                 my %sections = ();
 4873:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4874:                 my ($credits,$numchanges);
 4875:                 if ($three eq 'st') {
 4876:                     if ($showcredits) {
 4877:                         my $defaultcredits = 
 4878:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4879:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4880:                         $credits =~ s/[^\d\.]//g;
 4881:                         if ($credits eq $defaultcredits) {
 4882:                             undef($credits);
 4883:                         }
 4884:                     }
 4885:                 }
 4886:                 if ($num_sections == 0) {
 4887:                     unless ($udom eq $one) {
 4888:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4889:                                      $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4890:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4891:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4892:                     }
 4893:                     $numchanges ++;
 4894:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4895:                 } else {
 4896:                     my %curr_groups = 
 4897: 			&Apache::longroup::coursegroups($one,$two);
 4898:                     my $emptysec = 0;
 4899:                     my $restricted;
 4900:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4901:                         $sec =~ s/\W//g;
 4902:                         if ($sec ne '') {
 4903:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4904:                                 exists($curr_groups{$sec})) {
 4905:                                 $disallowed{$sec} = $url;
 4906:                                 next;
 4907:                             }
 4908:                             my $securl = $url.'/'.$sec;
 4909:                             my $secid = $securl.'_'.$three;
 4910:                             unless ($udom eq $one) {
 4911:                                 undef($restricted);
 4912:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4913:                                                   $uname,$three,$start,$end,$one,$two,$sec,$credits,\%process_by,
 4914:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4915:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4916:                                 next if ($restricted);
 4917:                             }
 4918:                             $numchanges ++;
 4919:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4920:                         } else {
 4921:                             $emptysec = 1;
 4922:                         }
 4923:                     }
 4924:                     if ($emptysec) {
 4925:                         unless ($udom eq $one) {
 4926:                             undef($restricted);
 4927:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4928:                                               $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4929:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4930:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4931:                             next if ($restricted);
 4932:                         }
 4933:                         $numchanges ++;
 4934:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4935:                     }
 4936:                     next unless ($numchanges);
 4937:                 }
 4938:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4939:                     push(@rolechanges,$three);
 4940:                 }
 4941: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4942: 		# Activate roles for sections with two id numbers
 4943: 		# set start, end times, and the url for the class
 4944: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ?
 4945: 			      $env{'form.start_'.$1.'_'.$2} :
 4946: 			      $now );
 4947: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ?
 4948: 			      $env{'form.end_'.$1.'_'.$2} :
 4949: 			      0 );
 4950:                 my $one = $1;
 4951:                 my $two = $2;
 4952: 		my $url='/'.$one.'/';
 4953:                 my $id = $url.'_'.$two;
 4954:                 my ($cdom,$cnum) = split(/\//,$one);
 4955:                 # split multiple sections
 4956:                 my %sections = ();
 4957:                 my ($restricted,$numchanges);
 4958:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4959:                 if ($num_sections == 0) {
 4960:                     unless ($udom eq $one) {
 4961:                         $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4962:                                           $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4963:                                           \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4964:                                           \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4965:                         next if ($restricted);
 4966:                     }
 4967:                     $numchanges ++;
 4968:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4969:                 } else {
 4970:                     my $emptysec = 0;
 4971:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4972:                         if ($sec ne '') {
 4973:                             my $securl = $url.'/'.$sec;
 4974:                             my $secid = $securl.'_'.$two;
 4975:                             unless ($udom eq $one) {
 4976:                                 undef($restricted);
 4977:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4978:                                                   $uname,$two,$start,$end,$cdom,$cnum,$sec,'',\%process_by,
 4979:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4980:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4981:                                 next if ($restricted);
 4982:                             }
 4983:                             $numchanges ++;
 4984:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4985:                         } else {
 4986:                             $emptysec = 1;
 4987:                         }
 4988:                     }
 4989:                     if ($emptysec) {
 4990:                         unless ($udom eq $one) {
 4991:                             undef($restricted);
 4992:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4993:                                               $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4994:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4995:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4996:                             next if ($restricted);
 4997:                         }
 4998:                         $numchanges ++;
 4999:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 5000:                     }
 5001:                     next unless ($numchanges); 
 5002:                 }
 5003:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 5004:                     push(@rolechanges,$two);
 5005:                 }
 5006: 	    } else {
 5007: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 5008:             }
 5009:             foreach my $key (sort(keys(%disallowed))) {
 5010:                 $r->print('<p class="LC_warning">');
 5011:                 if (($key eq 'none') || ($key eq 'all')) {  
 5012:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 5013:                 } else {
 5014:                     $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>'));
 5015:                 }
 5016:                 $r->print('</p><p>'
 5017:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 5018:                              ,'<a href="javascript:history.go(-1)'
 5019:                              ,'</a>')
 5020:                          .'</p><br />'
 5021:                 );
 5022:             }
 5023: 	}
 5024:     } # End of foreach (keys(%env))
 5025:     if ((keys(%reject)) || (keys(%unauthorized))) {
 5026:         $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5027:     }
 5028:     if ((keys(%pending)) || (keys(%currqueued))) {
 5029:         $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5030:     }
 5031: # Flush the course logs so reverse user roles immediately updated
 5032:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5033:     if (@rolechanges == 0) {
 5034:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 5035:     }
 5036:     return @rolechanges;
 5037: }
 5038: 
 5039: sub get_user_credits {
 5040:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 5041:     if ($cdom eq '' || $cnum eq '') {
 5042:         return unless ($env{'request.course.id'});
 5043:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5044:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5045:     }
 5046:     my $credits;
 5047:     my %currhash =
 5048:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 5049:     if (keys(%currhash) > 0) {
 5050:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 5051:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 5052:         $credits = $items[$crdidx];
 5053:         $credits =~ s/[^\d\.]//g;
 5054:     }
 5055:     if ($credits eq $defaultcredits) {
 5056:         undef($credits);
 5057:     }
 5058:     return $credits;
 5059: }
 5060: 
 5061: sub enroll_single_student {
 5062:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 5063:         $showcredits,$defaultcredits) = @_;
 5064:     $r->print('<h3>');
 5065:     if ($crstype eq 'Community') {
 5066:         $r->print(&mt('Enrolling Member'));
 5067:     } else {
 5068:         $r->print(&mt('Enrolling Student'));
 5069:     }
 5070:     $r->print('</h3>');
 5071: 
 5072:     # Remove non alphanumeric values from section
 5073:     $env{'form.sections'}=~s/\W//g;
 5074: 
 5075:     my $credits;
 5076:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 5077:         $credits = $env{'form.credits'};
 5078:         $credits =~ s/[^\d\.]//g;
 5079:         if ($credits ne '') {
 5080:             if ($credits eq $defaultcredits) {
 5081:                 undef($credits);
 5082:             }
 5083:         }
 5084:     }
 5085:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 5086:     my (%got_role_approvals,%got_instdoms,%process_by,%instdoms,%pending,%reject,%notifydc,
 5087:         %status,%unauthorized,%currqueued);
 5088:     unless ($env{'form.ccdomain'} eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 5089:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5090:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5091:         my $csec = $env{'form.sections'};
 5092:         my $id = "/$cdom/$cnum";
 5093:         if ($csec ne '') {
 5094:             $id .= "/$csec";
 5095:         }
 5096:         $id .= '_st';
 5097:         if (&Apache::lonuserutils::restricted_dom($context,$id,$env{'form.ccdomain'},$env{'form.ccuname'},
 5098:                                                   'st',$startdate,$enddate,$cdom,$cnum,$csec,$credits,
 5099:                                                   \%process_by,\%instdoms,\%got_role_approvals,\%got_instdoms,
 5100:                                                   \%reject,\%pending,\%notifydc,\%status,\%unauthorized,\%currqueued)) {
 5101:             if ((keys(%reject)) || (keys(%unauthorized))) {
 5102:                 $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5103:             }
 5104:             if ((keys(%pending)) || (keys(%currqueued))) {
 5105:                 $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5106:             }
 5107:             return;
 5108:         }
 5109:     }
 5110: 
 5111:     # Clean out any old student roles the user has in this class.
 5112:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 5113:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 5114:     my $enroll_result =
 5115:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 5116:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 5117:             $env{'form.cmiddlename'},$env{'form.clastname'},
 5118:             $env{'form.generation'},$env{'form.sections'},$enddate,
 5119:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 5120:             $credits);
 5121:     if ($enroll_result =~ /^ok/) {
 5122:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 5123:         if ($env{'form.sections'} ne '') {
 5124:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 5125:         }
 5126:         my ($showstart,$showend);
 5127:         if ($startdate <= $now) {
 5128:             $showstart = &mt('Access starts immediately');
 5129:         } else {
 5130:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 5131:         }
 5132:         if ($enddate == 0) {
 5133:             $showend = &mt('ends: no ending date');
 5134:         } else {
 5135:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 5136:         }
 5137:         $r->print('.<br />'.$showstart.'; '.$showend);
 5138:         if ($startdate <= $now && !$newuser) {
 5139:             $r->print('<p class="LC_info">');
 5140:             if ($crstype eq 'Community') {
 5141:                 $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.'));
 5142:             } else {
 5143:                 $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.'));
 5144:            }
 5145:            $r->print('</p>');
 5146:         }
 5147:     } else {
 5148:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 5149:     }
 5150:     return;
 5151: }
 5152: 
 5153: sub get_defaultquota_text {
 5154:     my ($settingstatus) = @_;
 5155:     my $defquotatext; 
 5156:     if ($settingstatus eq '') {
 5157:         $defquotatext = &mt('default');
 5158:     } else {
 5159:         my ($usertypes,$order) =
 5160:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 5161:         if ($usertypes->{$settingstatus} eq '') {
 5162:             $defquotatext = &mt('default');
 5163:         } else {
 5164:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 5165:         }
 5166:     }
 5167:     return $defquotatext;
 5168: }
 5169: 
 5170: sub update_result_form {
 5171:     my ($uhome) = @_;
 5172:     my $outcome = 
 5173:     '<form name="userupdate" method="post" action="">'."\n";
 5174:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 5175:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5176:     }
 5177:     if ($env{'form.origname'} ne '') {
 5178:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 5179:     }
 5180:     foreach my $item ('sortby','seluname','seludom') {
 5181:         if (exists($env{'form.'.$item})) {
 5182:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5183:         }
 5184:     }
 5185:     if ($uhome eq 'no_host') {
 5186:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 5187:     }
 5188:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 5189:                 '<input type="hidden" name="currstate" value="" />'."\n".
 5190:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5191:                 '</form>';
 5192:     return $outcome;
 5193: }
 5194: 
 5195: sub quota_admin {
 5196:     my ($setquota,$changeHash,$name) = @_;
 5197:     my $quotachanged;
 5198:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 5199:         # Current user has quota modification privileges
 5200:         if (ref($changeHash) eq 'HASH') {
 5201:             $quotachanged = 1;
 5202:             $changeHash->{$name.'quota'} = $setquota;
 5203:         }
 5204:     }
 5205:     return $quotachanged;
 5206: }
 5207: 
 5208: sub tool_admin {
 5209:     my ($tool,$settool,$changeHash,$context) = @_;
 5210:     my $canchange = 0; 
 5211:     if ($context eq 'requestcourses') {
 5212:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 5213:             $canchange = 1;
 5214:         }
 5215:     } elsif ($context eq 'reqcrsotherdom') {
 5216:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 5217:             $canchange = 1;
 5218:         }
 5219:     } elsif ($context eq 'requestauthor') {
 5220:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5221:             $canchange = 1;
 5222:         }
 5223:     } elsif ($context eq 'authordefaults') {
 5224:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5225:             $canchange = 1;
 5226:         }
 5227:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 5228:         # Current user has quota modification privileges
 5229:         $canchange = 1;
 5230:     }
 5231:     my $toolchanged;
 5232:     if ($canchange) {
 5233:         if (ref($changeHash) eq 'HASH') {
 5234:             $toolchanged = 1;
 5235:             if ($tool eq 'requestauthor') {
 5236:                 $changeHash->{$context} = $settool;
 5237:             } elsif (($tool eq 'managers') || ($tool eq 'editors')) {
 5238:                 $changeHash->{'author'.$tool} = $settool;
 5239:             } elsif ($tool eq 'webdav') {
 5240:                 $changeHash->{'tools.'.$tool} = $settool;
 5241:             } else {
 5242:                 $changeHash->{$context.'.'.$tool} = $settool;
 5243:             }
 5244:         }
 5245:     }
 5246:     return $toolchanged;
 5247: }
 5248: 
 5249: sub build_roles {
 5250:     my ($sectionstr,$sections,$role) = @_;
 5251:     my $num_sections = 0;
 5252:     if ($sectionstr=~ /,/) {
 5253:         my @secnums = split/,/,$sectionstr;
 5254:         if ($role eq 'st') {
 5255:             $secnums[0] =~ s/\W//g;
 5256:             $$sections{$secnums[0]} = 1;
 5257:             $num_sections = 1;
 5258:         } else {
 5259:             foreach my $sec (@secnums) {
 5260:                 $sec =~ ~s/\W//g;
 5261:                 if (!($sec eq "")) {
 5262:                     if (exists($$sections{$sec})) {
 5263:                         $$sections{$sec} ++;
 5264:                     } else {
 5265:                         $$sections{$sec} = 1;
 5266:                         $num_sections ++;
 5267:                     }
 5268:                 }
 5269:             }
 5270:         }
 5271:     } else {
 5272:         $sectionstr=~s/\W//g;
 5273:         unless ($sectionstr eq '') {
 5274:             $$sections{$sectionstr} = 1;
 5275:             $num_sections ++;
 5276:         }
 5277:     }
 5278: 
 5279:     return $num_sections;
 5280: }
 5281: 
 5282: # ========================================================== Custom Role Editor
 5283: 
 5284: sub custom_role_editor {
 5285:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5286:     my $action = $env{'form.customroleaction'};
 5287:     my ($rolename,$helpitem);
 5288:     if ($action eq 'new') {
 5289:         $rolename=$env{'form.newrolename'};
 5290:     } else {
 5291:         $rolename=$env{'form.rolename'};
 5292:     }
 5293: 
 5294:     my ($crstype,$context);
 5295:     if ($env{'request.course.id'}) {
 5296:         $crstype = &Apache::loncommon::course_type();
 5297:         $context = 'course';
 5298:         $helpitem = 'Course_Editing_Custom_Roles';
 5299:     } else {
 5300:         $context = 'domain';
 5301:         $crstype = 'course';
 5302:         $helpitem = 'Domain_Editing_Custom_Roles';
 5303:     }
 5304: 
 5305:     $rolename=~s/[^A-Za-z0-9]//gs;
 5306:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 5307: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 5308:                                    $permission);
 5309:         return;
 5310:     }
 5311: 
 5312:     my $formname = 'form1';
 5313:     my %privs=();
 5314:     my $body_top = '<h2>';
 5315: # ------------------------------------------------------- Does this role exist?
 5316:     my ($rdummy,$roledef)=
 5317: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5318:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5319:         $body_top .= &mt('Existing Role').' "';
 5320: # ------------------------------------------------- Get current role privileges
 5321:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 5322:         if ($privs{'system'} =~ /bre\&S/) {
 5323:             if ($context eq 'domain') {
 5324:                 $crstype = 'Course';
 5325:             } elsif ($crstype eq 'Community') {
 5326:                 $privs{'system'} =~ s/bre\&S//;
 5327:             }
 5328:         } elsif ($context eq 'domain') {
 5329:             $crstype = 'Course';
 5330:         }
 5331:     } else {
 5332:         $body_top .= &mt('New Role').' "';
 5333:         $roledef='';
 5334:     }
 5335:     $body_top .= $rolename.'"</h2>';
 5336: 
 5337: # ------------------------------------------------------- What can be assigned?
 5338:     my %full=();
 5339:     my %levels=(
 5340:                  course => {},
 5341:                  domain => {},
 5342:                  system => {},
 5343:                );
 5344:     my %levelscurrent=(
 5345:                         course => {},
 5346:                         domain => {},
 5347:                         system => {},
 5348:                       );
 5349:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5350:     my ($jsback,$elements) = &crumb_utilities();
 5351:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5352:     my $head_script =
 5353:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 5354:                                                   \%full,\@templateroles,$jsback);
 5355:     push (@{$brcrum},
 5356:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 5357:                text => "Pick custom role",
 5358:                faq  => 282,bug=>'Instructor Interface',},
 5359:               {href => "javascript:backPage(document.$formname,'','')",
 5360:                text => "Edit custom role",
 5361:                faq  => 282,
 5362:                bug  => 'Instructor Interface',
 5363:                help => $helpitem}
 5364:               );
 5365:     my $args = { bread_crumbs          => $brcrum,
 5366:                  bread_crumbs_component => 'User Management'};
 5367:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 5368:                                              $head_script,$args).
 5369:               $body_top);
 5370:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 5371:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 5372:                                                         \@templateroles,$prefix));
 5373: 
 5374:     $r->print(<<ENDCCF);
 5375: <input type="hidden" name="phase" value="set_custom_roles" />
 5376: <input type="hidden" name="rolename" value="$rolename" />
 5377: ENDCCF
 5378:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5379:                                                        \%levelscurrent,$prefix));
 5380:     $r->print(&Apache::loncommon::end_data_table().
 5381:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 5382:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 5383:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 5384:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 5385:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 5386: }
 5387: 
 5388: # ---------------------------------------------------------- Call to definerole
 5389: sub set_custom_role {
 5390:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5391:     my $rolename=$env{'form.rolename'};
 5392:     $rolename=~s/[^A-Za-z0-9]//gs;
 5393:     if (!$rolename) {
 5394: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5395:         return;
 5396:     }
 5397:     my ($jsback,$elements) = &crumb_utilities();
 5398:     my $jscript = '<script type="text/javascript">'
 5399:                  .'// <![CDATA['."\n"
 5400:                  .$jsback."\n"
 5401:                  .'// ]]>'."\n"
 5402:                  .'</script>'."\n";
 5403:     my $helpitem = 'Course_Editing_Custom_Roles';
 5404:     if ($context eq 'domain') {
 5405:         $helpitem = 'Domain_Editing_Custom_Roles';
 5406:     }
 5407:     push(@{$brcrum},
 5408:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 5409:          text => "Pick custom role",
 5410:          faq  => 282,
 5411:          bug  => 'Instructor Interface',},
 5412:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 5413:          text => "Edit custom role",
 5414:          faq  => 282,
 5415:          bug  => 'Instructor Interface',},
 5416:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 5417:          text => "Result",
 5418:          faq  => 282,
 5419:          bug  => 'Instructor Interface',
 5420:          help => $helpitem,}
 5421:         );
 5422:     my $args = { bread_crumbs           => $brcrum,
 5423:                  bread_crumbs_component => 'User Management'};
 5424:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 5425: 
 5426:     my $newrole;
 5427:     my ($rdummy,$roledef)=
 5428: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5429: 
 5430: # ------------------------------------------------------- Does this role exist?
 5431:     $r->print('<h3>');
 5432:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5433: 	$r->print(&mt('Existing Role').' "');
 5434:     } else {
 5435: 	$r->print(&mt('New Role').' "');
 5436: 	$roledef='';
 5437:         $newrole = 1;
 5438:     }
 5439:     $r->print($rolename.'"</h3>');
 5440: # ------------------------------------------------- Assign role and show result
 5441: 
 5442:     my $errmsg;
 5443:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 5444:     # Assign role and return result
 5445:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 5446:                                              $newprivs{'c'});
 5447:     if ($result ne 'ok') {
 5448:         $errmsg = ': '.$result;
 5449:     }
 5450:     my $message =
 5451:         &Apache::lonhtmlcommon::confirm_success(
 5452:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 5453:     if ($env{'request.course.id'}) {
 5454:         my $url='/'.$env{'request.course.id'};
 5455:         $url=~s/\_/\//g;
 5456:         $result =
 5457:             &Apache::lonnet::assigncustomrole(
 5458:                 $env{'user.domain'},$env{'user.name'},
 5459:                 $url,
 5460:                 $env{'user.domain'},$env{'user.name'},
 5461:                 $rolename,undef,undef,undef,$context);
 5462:         if ($result ne 'ok') {
 5463:             $errmsg = ': '.$result;
 5464:         }
 5465:         $message .=
 5466:             '<br />'
 5467:            .&Apache::lonhtmlcommon::confirm_success(
 5468:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 5469:     }
 5470:     $r->print(
 5471:         &Apache::loncommon::confirmwrapper($message)
 5472:        .'<br />'
 5473:        .&Apache::lonhtmlcommon::actionbox([
 5474:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 5475:            .&mt('Create or edit another custom role')
 5476:            .'</a>'])
 5477:        .'<form name="customresult" method="post" action="">'
 5478:        .&Apache::lonhtmlcommon::echo_form_input([])
 5479:        .'</form>'
 5480:     );
 5481: }
 5482: 
 5483: sub show_role_requests {
 5484:     my ($caller,$dom) = @_;
 5485:     my $showrolereqs;
 5486:     my %domconfig = &Apache::lonnet::get_dom('configuration',['privacy'],$dom);
 5487:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 5488:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 5489:             my %approvalconf = %{$domconfig{'privacy'}{'approval'}};
 5490:             foreach my $key ('instdom','extdom') {
 5491:                 if (ref($approvalconf{$key}) eq 'HASH') {
 5492:                     if (keys(%{$approvalconf{$key}})) {
 5493:                         foreach my $context ('domain','author','course','community') {
 5494:                             if ($approvalconf{$key}{$context} eq $caller) {
 5495:                                 $showrolereqs = 1;
 5496:                                 last if ($showrolereqs);
 5497:                             }
 5498:                         }
 5499:                     }
 5500:                 }
 5501:                 last if ($showrolereqs);
 5502:             }
 5503:         }
 5504:     }
 5505:     return $showrolereqs;
 5506: }
 5507: 
 5508: sub display_coauthor_managers {
 5509:     my ($permission) = @_;
 5510:     my $output;
 5511:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5512:         $output = '<form action="/adm/createuser" method="post" name="camanagers">'.
 5513:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5514:                   '<p>';
 5515:         my (@possmanagers,@custommanagers);
 5516:         my %userenv =
 5517:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5518:                                              $env{'user.name'},
 5519:                                              'authormanagers');
 5520:         my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5521:                                                      ['active','future'],['ca']);
 5522:         if (keys(%ca_roles)) {
 5523:             foreach my $entry (sort(keys(%ca_roles))) {
 5524:                 if ($entry =~ /^($match_username\:$match_domain):ca$/) {
 5525:                     my $user = $1;
 5526:                     unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5527:                         push(@possmanagers,$user);
 5528:                     }
 5529:                 }
 5530:             }
 5531:         }
 5532:         if ($userenv{'authormanagers'} eq '') {
 5533:             $output .= &mt('Currently author manages co-author roles');
 5534:         } else {
 5535:             if (keys(%ca_roles)) {
 5536:                 foreach my $user (split(/,/,$userenv{'authormanagers'})) {
 5537:                     if ($user =~ /^($match_username)\:($match_domain)$/) {
 5538:                         if (exists($ca_roles{$user.':ca'})) {
 5539:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5540:                                 push(@custommanagers,$user);
 5541:                             }
 5542:                         }
 5543:                     }
 5544:                 }
 5545:             }
 5546:             if (@custommanagers) {
 5547:                 $output .= &mt('Co-authors with active or future roles who currently manage co-author roles: [_1]',
 5548:                               '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @custommanagers));
 5549:             } else {
 5550:                 $output .= &mt('Currently author manages co-author roles');
 5551:             }
 5552:         }
 5553:         $output .= "</p>\n";
 5554:         if (@possmanagers) {
 5555:             $output .= '<p>'.&mt('If checked, can manage').': ';
 5556:             foreach my $user (@possmanagers) {
 5557:                  my $checked;
 5558:                  if (grep(/^\Q$user\E$/,@custommanagers)) {
 5559:                      $checked = ' checked="checked"';
 5560:                  }
 5561:                  $output .= '<span style="LC_nobreak"><label>'.
 5562:                             '<input type="checkbox" name="custommanagers" '.
 5563:                             'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
 5564:                             &Apache::loncommon::plainname(split(/:/,$user))." ($user)".'</label></span> '."\n";
 5565:             }
 5566:             $output .= '<input type="hidden" name="state" value="process" /></p>'."\n".
 5567:                        '<p><input type="submit" value="'.&mt('Save changes').'" /></p>'."\n";
 5568:         } else {
 5569:             $output .= '<p>'.&mt('No co-author roles assignable as manager').'</p>';
 5570:         }
 5571:         $output .= '</form>';
 5572:     } else {
 5573:         $output = '<span class="LC_warning">'.
 5574:                   &mt('You do not have permission to perform this action').
 5575:                   '</span>';
 5576:     }
 5577:     return $output;
 5578: }
 5579: 
 5580: sub update_coauthor_managers {
 5581:     my ($permission) = @_;
 5582:     my $output;
 5583:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5584:         my ($current,$newval,@possibles,@managers);
 5585:         my %userenv =
 5586:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5587:                                              $env{'user.name'},
 5588:                                              'authormanagers');
 5589:         $current = $userenv{'authormanagers'};
 5590:         @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 5591:         if (@possibles) {
 5592:             my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5593:                                                          ['active','future'],['ca']);
 5594:             if (keys(%ca_roles)) {
 5595:                 foreach my $user (@possibles) {
 5596:                     if ($user =~ /^($match_username):($match_domain)$/) {
 5597:                         if (exists($ca_roles{$user.':ca'})) {
 5598:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5599:                                 push(@managers,$user);
 5600:                             }
 5601:                         }
 5602:                     }
 5603:                 }
 5604:                 if (@managers) {
 5605:                     $newval = join(',',sort(@managers));
 5606:                 }
 5607:             }
 5608:         }
 5609:         if ($current eq $newval) {
 5610:             $output = &mt('No changes made to management of co-author roles');
 5611:         } else {
 5612:             my $chgresult =
 5613:                 &Apache::lonnet::put('environment',{'authormanagers' => $newval},
 5614:                                      $env{'user.domain'},$env{'user.name'});
 5615:             if ($chgresult eq 'ok') {
 5616:                 &Apache::lonnet::appenv({'environment.authormanagers' => $newval});
 5617:                 my (@adds,@dels);
 5618:                 if ($newval eq '') {
 5619:                     @dels = split(/,/,$current);
 5620:                 } elsif ($current eq '') {
 5621:                     @adds = @managers;
 5622:                 } else {
 5623:                     my @old = split(/,/,$current);
 5624:                     my @diffs = &Apache::loncommon::compare_arrays(\@old,\@managers);
 5625:                     if (@diffs) {
 5626:                         foreach my $user (@diffs) {
 5627:                             if (grep(/^\Q$user\E$/,@old)) {
 5628:                                 push(@dels,$user);
 5629:                             } elsif (grep(/^\Q$user\E$/,@managers)) {
 5630:                                 push(@adds,$user);
 5631:                             }
 5632:                         }
 5633:                     }
 5634:                 }
 5635:                 my $key = "internal.manager./$env{'user.domain'}/$env{'user.name'}";
 5636:                 if (@dels) {
 5637:                     foreach my $user (@dels) {
 5638:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5639:                             &Apache::lonnet::del('environment',[$key],$2,$1);
 5640:                         }
 5641:                     }
 5642:                 }
 5643:                 if (@adds) {
 5644:                     foreach my $user (@adds) {
 5645:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5646:                             &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 5647:                         }
 5648:                     }
 5649:                 }
 5650:                 if ($newval eq '') {
 5651:                     $output = &mt('Management of co-authors set to be author-only');
 5652:                 } else {
 5653:                     $output .= &mt('Co-authors who can manage co-author roles set to: [_1]',
 5654:                                    '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @managers));
 5655:                 }
 5656:             }
 5657:         }
 5658:     } else {
 5659:         $output = '<span class="LC_warning">'.
 5660:                   &mt('You do not have permission to perform this action').
 5661:                   '</span>';
 5662:     }
 5663:     return $output;
 5664: }
 5665: 
 5666: # ================================================================ Main Handler
 5667: sub handler {
 5668:     my $r = shift;
 5669:     if ($r->header_only) {
 5670:        &Apache::loncommon::content_type($r,'text/html');
 5671:        $r->send_http_header;
 5672:        return OK;
 5673:     }
 5674:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 5675: 
 5676:     if ($env{'request.course.id'}) {
 5677:         $context = 'course';
 5678:         $crstype = &Apache::loncommon::course_type();
 5679:     } elsif ($env{'request.role'} =~ /^au\./) {
 5680:         $context = 'author';
 5681:     } elsif ($env{'request.role'} =~ m{^(ca|aa)\./$match_domain/$match_username$}) {
 5682:         $context = 'coauthor';
 5683:     } else {
 5684:         $context = 'domain';
 5685:     }
 5686: 
 5687:     my ($permission,$allowed) =
 5688:         &Apache::lonuserutils::get_permission($context,$crstype);
 5689:     if (($context eq 'coauthor') && ($allowed)) {
 5690:         $context = 'author';
 5691:     }
 5692: 
 5693:     if ($allowed) {
 5694:         my @allhelp;
 5695:         if ($context eq 'course') {
 5696:             $cid = $env{'request.course.id'};
 5697:             $cdom = $env{'course.'.$cid.'.domain'};
 5698:             $cnum = $env{'course.'.$cid.'.num'};
 5699: 
 5700:             if ($permission->{'cusr'}) {
 5701:                 push(@allhelp,'Course_Create_Class_List');
 5702:             }
 5703:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5704:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 5705:             }
 5706:             if ($permission->{'custom'}) {
 5707:                 push(@allhelp,'Course_Editing_Custom_Roles');
 5708:             }
 5709:             if ($permission->{'cusr'}) {
 5710:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 5711:             }
 5712:             unless ($permission->{'cusr_section'}) {
 5713:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 5714:                     push(@allhelp,'Course_Automated_Enrollment');
 5715:                 }
 5716:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 5717:                     push(@allhelp,'Course_Approve_Selfenroll');
 5718:                 }
 5719:             }
 5720:             if ($permission->{'grp_manage'}) {
 5721:                 push(@allhelp,'Course_Manage_Group');
 5722:             }
 5723:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5724:                 push(@allhelp,'Course_User_Logs');
 5725:             }
 5726:         } elsif ($context eq 'author') {
 5727:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5728:                            'Author_View_Coauthor_List','Author_User_Logs'));
 5729:         } elsif ($context eq 'coauthor') {
 5730:             if ($permission->{'cusr'}) {
 5731:                 push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5732:                                'Author_View_Coauthor_List','Author_User_Logs'));
 5733:             } elsif ($permission->{'view'}) {
 5734:                 push(@allhelp,'Author_View_Coauthor_List');
 5735:             }
 5736:         } else {
 5737:             if ($permission->{'cusr'}) {
 5738:                 push(@allhelp,'Domain_Change_Privileges');
 5739:                 if ($permission->{'activity'}) {
 5740:                     push(@allhelp,'Domain_User_Access_Logs');
 5741:                 }
 5742:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 5743:                 if ($permission->{'custom'}) {
 5744:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 5745:                 }
 5746:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 5747:             } elsif ($permission->{'view'}) {
 5748:                 push(@allhelp,'Domain_View_Privileges');
 5749:                 if ($permission->{'activity'}) {
 5750:                     push(@allhelp,'Domain_User_Access_Logs');
 5751:                 }
 5752:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 5753:             }
 5754:         }
 5755:         if (@allhelp) {
 5756:             $allhelpitems = join(',',@allhelp);
 5757:         }
 5758:     }
 5759: 
 5760:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5761:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 5762:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue',
 5763:          'forceedit']);
 5764:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5765:     my $args;
 5766:     my $brcrum = [];
 5767:     my $bread_crumbs_component = 'User Management';
 5768:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 5769:         $brcrum = [{href=>"/adm/createuser",
 5770:                     text=>"User Management",
 5771:                     help=>$allhelpitems}
 5772:                   ];
 5773:     }
 5774:     if (!$allowed) {
 5775:         if ($context eq 'course') {
 5776:             $r->internal_redirect('/adm/viewclasslist');
 5777:             return OK;
 5778:         } elsif ($context eq 'coauthor') {
 5779:             $r->internal_redirect('/adm/viewcoauthors');
 5780:             return OK;
 5781:         }
 5782:         $env{'user.error.msg'}=
 5783:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 5784:                                  "or view user status.";
 5785:         return HTTP_NOT_ACCEPTABLE;
 5786:     }
 5787: 
 5788:     &Apache::loncommon::content_type($r,'text/html');
 5789:     $r->send_http_header;
 5790: 
 5791:     my $showcredits;
 5792:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 5793:          ($context eq 'domain')) {
 5794:         my %domdefaults = 
 5795:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 5796:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 5797:             $showcredits = 1;
 5798:         }
 5799:     }
 5800: 
 5801:     # Main switch on form.action and form.state, as appropriate
 5802:     if (! exists($env{'form.action'})) {
 5803:         $args = {bread_crumbs => $brcrum,
 5804:                  bread_crumbs_component => $bread_crumbs_component}; 
 5805:         $r->print(&header(undef,$args));
 5806:         $r->print(&print_main_menu($permission,$context,$crstype));
 5807:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 5808:         my $helpitem = 'Course_Create_Class_List';
 5809:         if ($context eq 'author') {
 5810:             $helpitem = 'Author_Create_Coauthor_List';
 5811:         } elsif ($context eq 'domain') {
 5812:             $helpitem = 'Domain_Create_Users';
 5813:         }
 5814:         push(@{$brcrum},
 5815:               { href => '/adm/createuser?action=upload&state=',
 5816:                 text => 'Upload Users List',
 5817:                 help => $helpitem,
 5818:               });
 5819:         $bread_crumbs_component = 'Upload Users List';
 5820:         $args = {bread_crumbs           => $brcrum,
 5821:                  bread_crumbs_component => $bread_crumbs_component};
 5822:         $r->print(&header(undef,$args));
 5823:         $r->print('<form name="studentform" method="post" '.
 5824:                   'enctype="multipart/form-data" '.
 5825:                   ' action="/adm/createuser">'."\n");
 5826:         if (! exists($env{'form.state'})) {
 5827:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5828:         } elsif ($env{'form.state'} eq 'got_file') {
 5829:             my $result = 
 5830:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 5831:                                                                  $permission,
 5832:                                                                  $crstype,$showcredits);
 5833:             if ($result eq 'missingdata') {
 5834:                 delete($env{'form.state'});
 5835:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5836:             }
 5837:         } elsif ($env{'form.state'} eq 'enrolling') {
 5838:             if ($env{'form.datatoken'}) {
 5839:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 5840:                                                                     $permission,
 5841:                                                                     $showcredits);
 5842:                 if ($result eq 'missingdata') {
 5843:                     delete($env{'form.state'});
 5844:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5845:                 } elsif ($result eq 'invalidhome') {
 5846:                     $env{'form.state'} = 'got_file';
 5847:                     delete($env{'form.lcserver'});
 5848:                     my $result =
 5849:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 5850:                                                                          $crstype,$showcredits);
 5851:                     if ($result eq 'missingdata') {
 5852:                         delete($env{'form.state'});
 5853:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5854:                     }
 5855:                 }
 5856:             } else {
 5857:                 delete($env{'form.state'});
 5858:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5859:             }
 5860:         } else {
 5861:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5862:         }
 5863:         $r->print('</form>');
 5864:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 5865:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 5866:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 5867:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 5868:         my $phase = $env{'form.phase'};
 5869:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 5870: 	&Apache::loncreateuser::restore_prev_selections();
 5871: 	my $srch;
 5872: 	foreach my $item (@search) {
 5873: 	    $srch->{$item} = $env{'form.'.$item};
 5874: 	}
 5875:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 5876:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 5877:             if ($env{'form.phase'} eq 'createnewuser') {
 5878:                 my $response;
 5879:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 5880:                     my $response =
 5881:                         '<span class="LC_warning">'
 5882:                        .&mt('You must specify a valid username. Only the following are allowed:'
 5883:                            .' letters numbers - . @')
 5884:                        .'</span>';
 5885:                     $env{'form.phase'} = '';
 5886:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 5887:                                                $crstype,$brcrum,$permission);
 5888:                 } else {
 5889:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 5890:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 5891:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 5892:                                                   $srch,$response,$context,
 5893:                                                   $permission,$crstype,$brcrum,
 5894:                                                   $showcredits);
 5895:                 }
 5896:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 5897:                 my ($currstate,$response,$forcenewuser,$results) = 
 5898:                     &user_search_result($context,$srch);
 5899:                 if ($env{'form.currstate'} eq 'modify') {
 5900:                     $currstate = $env{'form.currstate'};
 5901:                 }
 5902:                 if ($currstate eq 'select') {
 5903:                     &print_user_selection_page($r,$response,$srch,$results,
 5904:                                                \@search,$context,undef,$crstype,
 5905:                                                $brcrum);
 5906:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 5907:                     my ($ccuname,$ccdomain,$uhome);
 5908:                     if (($srch->{'srchby'} eq 'uname') && 
 5909:                         ($srch->{'srchtype'} eq 'exact')) {
 5910:                         $ccuname = $srch->{'srchterm'};
 5911:                         $ccdomain= $srch->{'srchdomain'};
 5912:                     } else {
 5913:                         my @matchedunames = keys(%{$results});
 5914:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 5915:                     }
 5916:                     $ccuname =&LONCAPA::clean_username($ccuname);
 5917:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 5918:                     if ($env{'form.action'} eq 'accesslogs') {
 5919:                         my $uhome;
 5920:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 5921:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 5922:                         }
 5923:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 5924:                             $env{'form.phase'} = '';
 5925:                             undef($forcenewuser);
 5926:                             #if ($response) {
 5927:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 5928:                             #        $response .= '<br /><br />';
 5929:                             #    }
 5930:                             #}
 5931:                             &print_username_entry_form($r,$context,$response,$srch,
 5932:                                                        $forcenewuser,$crstype,$brcrum,
 5933:                                                        $permission);
 5934:                         } else {
 5935:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5936:                         }
 5937:                     } else {
 5938:                         if ($env{'form.forcenewuser'}) {
 5939:                             $response = '';
 5940:                         }
 5941:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 5942:                                                       $srch,$response,$context,
 5943:                                                       $permission,$crstype,$brcrum);
 5944:                     }
 5945:                 } elsif ($currstate eq 'query') {
 5946:                     &print_user_query_page($r,'createuser',$brcrum);
 5947:                 } else {
 5948:                     $env{'form.phase'} = '';
 5949:                     &print_username_entry_form($r,$context,$response,$srch,
 5950:                                                $forcenewuser,$crstype,$brcrum,
 5951:                                                $permission);
 5952:                 }
 5953:             } elsif ($env{'form.phase'} eq 'userpicked') {
 5954:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 5955:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 5956:                 if ($env{'form.action'} eq 'accesslogs') {
 5957:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5958:                 } else {
 5959:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 5960:                                                   $context,$permission,$crstype,
 5961:                                                   $brcrum);
 5962:                 }
 5963:             } elsif ($env{'form.action'} eq 'accesslogs') {
 5964:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 5965:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 5966:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5967:             }
 5968:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 5969:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 5970:         } else {
 5971:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 5972:                                        $brcrum,$permission);
 5973:         }
 5974:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 5975:         my $prefix;
 5976:         if ($env{'form.phase'} eq 'set_custom_roles') {
 5977:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 5978:         } else {
 5979:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5980:         }
 5981:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 5982:              ($permission->{'cusr'}) && 
 5983:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5984:         push(@{$brcrum},
 5985:                  {href => '/adm/createuser?action=processauthorreq',
 5986:                   text => 'Authoring Space requests',
 5987:                   help => 'Domain_Role_Approvals'});
 5988:         $bread_crumbs_component = 'Authoring requests';
 5989:         if ($env{'form.state'} eq 'done') {
 5990:             push(@{$brcrum},
 5991:                      {href => '/adm/createuser?action=authorreqqueue',
 5992:                       text => 'Result',
 5993:                       help => 'Domain_Role_Approvals'});
 5994:             $bread_crumbs_component = 'Authoring request result';
 5995:         }
 5996:         $args = { bread_crumbs           => $brcrum,
 5997:                   bread_crumbs_component => $bread_crumbs_component};
 5998:         my $js = &usernamerequest_javascript();
 5999:         $r->print(&header(&add_script($js),$args));
 6000:         if (!exists($env{'form.state'})) {
 6001:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 6002:                                                                             $env{'request.role.domain'}));
 6003:         } elsif ($env{'form.state'} eq 'done') {
 6004:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 6005:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 6006:                                                                          $env{'request.role.domain'}));
 6007:         }
 6008:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 6009:              ($permission->{'cusr'}) &&
 6010:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 6011:         push(@{$brcrum},
 6012:                  {href => '/adm/createuser?action=processusernamereq',
 6013:                   text => 'LON-CAPA account requests',
 6014:                   help => 'Domain_Username_Approvals'});
 6015:         $bread_crumbs_component = 'Account requests';
 6016:         if ($env{'form.state'} eq 'done') {
 6017:             push(@{$brcrum},
 6018:                      {href => '/adm/createuser?action=usernamereqqueue',
 6019:                       text => 'Result',
 6020:                       help => 'Domain_Username_Approvals'});
 6021:             $bread_crumbs_component = 'LON-CAPA account request result';
 6022:         }
 6023:         $args = { bread_crumbs           => $brcrum,
 6024:                   bread_crumbs_component => $bread_crumbs_component};
 6025:         my $js = &usernamerequest_javascript();
 6026:         $r->print(&header(&add_script($js),$args));
 6027:         if (!exists($env{'form.state'})) {
 6028:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 6029:                                                                             $env{'request.role.domain'}));
 6030:         } elsif ($env{'form.state'} eq 'done') {
 6031:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 6032:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 6033:                                                                          $env{'request.role.domain'}));
 6034:         }
 6035:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 6036:              ($permission->{'cusr'})) {
 6037:         my $dom = $env{'form.domain'};
 6038:         my $uname = $env{'form.username'};
 6039:         my $warning;
 6040:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 6041:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 6042:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 6043:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 6044:                     if ($uhome eq 'no_host') {
 6045:                         my $queue = $env{'form.queue'};
 6046:                         my $reqkey = &escape($uname).'_'.$queue; 
 6047:                         my $namespace = 'usernamequeue';
 6048:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 6049:                         my %queued =
 6050:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 6051:                         unless ($queued{$reqkey}) {
 6052:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 6053:                         }
 6054:                     } else {
 6055:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 6056:                     }
 6057:                 } else {
 6058:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 6059:                 }
 6060:             } else {
 6061:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 6062:             }
 6063:         } else {
 6064:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 6065:         }
 6066:         my $args = { only_body => 1 };
 6067:         $r->print(&header(undef,$args).
 6068:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 6069:         if ($warning ne '') {
 6070:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 6071:         } else {
 6072:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 6073:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 6074:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6075:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6076:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 6077:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 6078:                         my %info =
 6079:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 6080:                         if (ref($info{$uname}) eq 'HASH') {
 6081:                             my $usertype = $info{$uname}{'inststatus'};
 6082:                             unless ($usertype) {
 6083:                                 $usertype = 'default';
 6084:                             }
 6085:                             my ($showstatus,$showemail,$pickstart);
 6086:                             my $numextras = 0;
 6087:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6088:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 6089:                                 if (ref($usertypes) eq 'HASH') {
 6090:                                     if ($usertypes->{$usertype}) {
 6091:                                         $showstatus = $usertypes->{$usertype};
 6092:                                     } else {
 6093:                                         $showstatus = $othertitle;
 6094:                                     }
 6095:                                     if ($showstatus) {
 6096:                                         $numextras ++;
 6097:                                     }
 6098:                                 }
 6099:                             }
 6100:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 6101:                                 $showemail = $info{$uname}{'email'};
 6102:                                 $numextras ++;
 6103:                             }
 6104:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 6105:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 6106:                                     $pickstart = 1;
 6107:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6108:                                     my ($num,$count);
 6109:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 6110:                                     $count += $numextras;
 6111:                                     foreach my $field (@{$infofields}) {
 6112:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 6113:                                         next unless ($infotitles->{$field});
 6114:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 6115:                                                   $info{$uname}{$field});
 6116:                                         $num ++;
 6117:                                         unless ($count == $num) {
 6118:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 6119:                                         }
 6120:                                     }
 6121:                                 }
 6122:                             }
 6123:                             if ($numextras) {
 6124:                                 unless ($pickstart) {
 6125:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6126:                                     $pickstart = 1;
 6127:                                 }
 6128:                                 if ($showemail) {
 6129:                                     my $closure = '';
 6130:                                     unless ($showstatus) {
 6131:                                         $closure = 1;
 6132:                                     }
 6133:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 6134:                                               $showemail.
 6135:                                               &Apache::lonhtmlcommon::row_closure($closure));
 6136:                                 }
 6137:                                 if ($showstatus) {
 6138:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 6139:                                               $showstatus.
 6140:                                               &Apache::lonhtmlcommon::row_closure(1));
 6141:                                 }
 6142:                             }
 6143:                             if ($pickstart) { 
 6144:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 6145:                             } else {
 6146:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 6147:                             }
 6148:                         } else {
 6149:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 6150:                         }
 6151:                     }
 6152:                 }
 6153:             }
 6154:         }
 6155:         $r->print(&close_popup_form());
 6156:     } elsif (($env{'form.action'} eq 'listusers') && 
 6157:              ($permission->{'view'} || $permission->{'cusr'})) {
 6158:         my $helpitem = 'Course_View_Class_List';
 6159:         if ($context eq 'author') {
 6160:             $helpitem = 'Author_View_Coauthor_List';
 6161:         } elsif ($context eq 'domain') {
 6162:             $helpitem = 'Domain_View_Users_List';
 6163:         }
 6164:         if ($env{'form.phase'} eq 'bulkchange') {
 6165:             push(@{$brcrum},
 6166:                     {href => '/adm/createuser?action=listusers',
 6167:                      text => "List Users"},
 6168:                     {href => "/adm/createuser",
 6169:                      text => "Result",
 6170:                      help => $helpitem});
 6171:             $bread_crumbs_component = 'Update Users';
 6172:             $args = {bread_crumbs           => $brcrum,
 6173:                      bread_crumbs_component => $bread_crumbs_component};
 6174:             $r->print(&header(undef,$args));
 6175:             my $setting = $env{'form.roletype'};
 6176:             my $choice = $env{'form.bulkaction'};
 6177:             if ($permission->{'cusr'}) {
 6178:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 6179:             } else {
 6180:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 6181:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 6182:             }
 6183:         } else {
 6184:             push(@{$brcrum},
 6185:                     {href => '/adm/createuser?action=listusers',
 6186:                      text => "List Users",
 6187:                      help => $helpitem});
 6188:             $bread_crumbs_component = 'List Users';
 6189:             $args = {bread_crumbs           => $brcrum,
 6190:                      bread_crumbs_component => $bread_crumbs_component};
 6191:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 6192:             my $formname = 'studentform';
 6193:             my $hidecall = "hide_searching();";
 6194:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 6195:                 ($env{'form.roletype'} eq 'community'))) {
 6196:                 if ($env{'form.roletype'} eq 'course') {
 6197:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 6198:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 6199:                                                                 $formname);
 6200:                 } elsif ($env{'form.roletype'} eq 'community') {
 6201:                     $cb_jscript = 
 6202:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 6203:                     my %elements = (
 6204:                                       coursepick => 'radio',
 6205:                                       coursetotal => 'text',
 6206:                                       courselist => 'text',
 6207:                                    );
 6208:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 6209:                 }
 6210:                 $jscript .= &verify_user_display($context)."\n".
 6211:                             &Apache::loncommon::check_uncheck_jscript();
 6212:                 my $js = &add_script($jscript).$cb_jscript;
 6213:                 my $loadcode = 
 6214:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 6215:                 if ($loadcode ne '') {
 6216:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 6217:                 } else {
 6218:                     $args->{add_entries} = {onload => $hidecall};
 6219:                 }
 6220:                 $r->print(&header($js,$args));
 6221:             } else {
 6222:                 $args->{add_entries} = {onload => $hidecall};
 6223:                 $jscript = &verify_user_display($context).
 6224:                            &Apache::loncommon::check_uncheck_jscript(); 
 6225:                 $r->print(&header(&add_script($jscript),$args));
 6226:             }
 6227:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 6228:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 6229:                          $showcredits);
 6230:         }
 6231:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 6232:         my $brtext;
 6233:         if ($crstype eq 'Community') {
 6234:             $brtext = 'Drop Members';
 6235:         } else {
 6236:             $brtext = 'Drop Students';
 6237:         }
 6238:         push(@{$brcrum},
 6239:                 {href => '/adm/createuser?action=drop',
 6240:                  text => $brtext,
 6241:                  help => 'Course_Drop_Student'});
 6242:         if ($env{'form.state'} eq 'done') {
 6243:             push(@{$brcrum},
 6244:                      {href=>'/adm/createuser?action=drop',
 6245:                       text=>"Result"});
 6246:         }
 6247:         $bread_crumbs_component = $brtext;
 6248:         $args = {bread_crumbs           => $brcrum,
 6249:                  bread_crumbs_component => $bread_crumbs_component}; 
 6250:         $r->print(&header(undef,$args));
 6251:         if (!exists($env{'form.state'})) {
 6252:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 6253:         } elsif ($env{'form.state'} eq 'done') {
 6254:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 6255:                                                     $env{'form.action'});
 6256:         }
 6257:     } elsif ($env{'form.action'} eq 'dateselect') {
 6258:         if ($permission->{'cusr'}) {
 6259:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6260:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 6261:                                                                    $crstype,$showcredits));
 6262:         } else {
 6263:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6264:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 6265:         }
 6266:     } elsif ($env{'form.action'} eq 'selfenroll') {
 6267:         my %currsettings;
 6268:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 6269:             %currsettings = (
 6270:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 6271:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 6272:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 6273:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 6274:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 6275:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 6276:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 6277:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 6278:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 6279:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 6280:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 6281:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 6282:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 6283:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 6284:             );
 6285:         }
 6286:         if ($permission->{selfenrolladmin}) {
 6287:             push(@{$brcrum},
 6288:                     {href => '/adm/createuser?action=selfenroll',
 6289:                      text => "Configure Self-enrollment",
 6290:                      help => 'Course_Self_Enrollment'});
 6291:             if (!exists($env{'form.state'})) {
 6292:                 $args = { bread_crumbs           => $brcrum,
 6293:                           bread_crumbs_component => 'Configure Self-enrollment'};
 6294:                 $r->print(&header(undef,$args));
 6295:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6296:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 6297:             } elsif ($env{'form.state'} eq 'done') {
 6298:                 push (@{$brcrum},
 6299:                           {href=>'/adm/createuser?action=selfenroll',
 6300:                            text=>"Result"});
 6301:                 $args = { bread_crumbs           => $brcrum,
 6302:                           bread_crumbs_component => 'Self-enrollment result'};
 6303:                 $r->print(&header(undef,$args));
 6304:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6305:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 6306:             }
 6307:         } elsif ($permission->{selfenrollview}) {
 6308:             push(@{$brcrum},
 6309:                     {href => '/adm/createuser?action=selfenroll',
 6310:                      text => "View Self-enrollment configuration",
 6311:                      help => 'Course_Self_Enrollment'});
 6312:             $args = { bread_crumbs           => $brcrum,
 6313:                       bread_crumbs_component => 'Self-enrollment Settings'};
 6314:             $r->print(&header(undef,$args));
 6315:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6316:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 6317:         } else {
 6318:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6319:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 6320:         }
 6321:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 6322:         if ($permission->{selfenrolladmin}) {
 6323:             push(@{$brcrum},
 6324:                      {href => '/adm/createuser?action=selfenrollqueue',
 6325:                       text => 'Enrollment requests',
 6326:                       help => 'Course_Approve_Selfenroll'});
 6327:             $bread_crumbs_component = 'Enrollment requests';
 6328:             if ($env{'form.state'} eq 'done') {
 6329:                 push(@{$brcrum},
 6330:                          {href => '/adm/createuser?action=selfenrollqueue',
 6331:                           text => 'Result',
 6332:                           help => 'Course_Approve_Selfenroll'});
 6333:                 $bread_crumbs_component = 'Enrollment result';
 6334:             }
 6335:             $args = { bread_crumbs           => $brcrum,
 6336:                       bread_crumbs_component => $bread_crumbs_component};
 6337:             $r->print(&header(undef,$args));
 6338:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6339:             if (!exists($env{'form.state'})) {
 6340:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 6341:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 6342:                                                                                 $cdom,$cnum));
 6343:             } elsif ($env{'form.state'} eq 'done') {
 6344:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 6345:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 6346:                               $cdom,$cnum,$coursedesc));
 6347:             }
 6348:         } else {
 6349:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6350:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 6351:         }
 6352:     } elsif ($env{'form.action'} eq 'changelogs') {
 6353:         if ($permission->{cusr} || $permission->{view}) {
 6354:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 6355:         } else {
 6356:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6357:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 6358:         }
 6359:     } elsif ($env{'form.action'} eq 'helpdesk') {
 6360:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6361:             ($permission->{'cusr'} || $permission->{'view'})) {
 6362:             if ($env{'form.state'} eq 'process') {
 6363:                 if ($permission->{'owner'}) {
 6364:                     &update_helpdeskaccess($r,$permission,$brcrum);
 6365:                 } else {
 6366:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 6367:                 }
 6368:             } else {
 6369:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 6370:             }
 6371:         } else {
 6372:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6373:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 6374:         }
 6375:     } elsif ($env{'form.action'} eq 'rolerequests') {
 6376:         if ($permission->{cusr} || $permission->{view}) {
 6377:             &print_queued_roles($r,$context,$permission,$brcrum);
 6378:         }
 6379:     } elsif ($env{'form.action'} eq 'queuedroles') {
 6380:         if (($permission->{cusr}) && ($context eq 'domain')) {
 6381:             if (&show_role_requests($context,$env{'request.role.domain'})) {
 6382:                 if ($env{'form.state'} eq 'done') {
 6383:                     &process_pendingroles($r,$context,$permission,$brcrum);
 6384:                 } else {
 6385:                     &print_pendingroles($r,$context,$permission,$brcrum);
 6386:                 }
 6387:             } else {
 6388:                 $r->print(&header(undef,{'no_nav_bar' => 1}).
 6389:                           '<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>');
 6390:             }
 6391:         } else {
 6392:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6393:                      '<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>');
 6394:         }
 6395:     } elsif ($env{'form.action'} eq 'camanagers') {
 6396:         if (($permission->{cusr}) && ($context eq 'author')) {
 6397:             push(@{$brcrum},
 6398:                      {href => '/adm/createuser?action=camanagers',
 6399:                       text => 'Co-author Managers',
 6400:                       help => 'Author_Manage_Coauthors'});
 6401:             if ($env{'form.state'} eq 'process') {
 6402:                 push(@{$brcrum},
 6403:                          {href => '/adm/createuser?action=camanagers',
 6404:                           text => 'Result',
 6405:                           help => 'Author_Manage_Coauthors'});
 6406:             }
 6407:             $args = { bread_crumbs           => $brcrum };
 6408:             $r->print(&header(undef,$args));
 6409:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6410:             if (!exists($env{'form.state'})) {
 6411:                 $r->print('<h3>'.&mt('Co-author Management').'</h3>'."\n".
 6412:                           &display_coauthor_managers($permission));
 6413:             } elsif ($env{'form.state'} eq 'process') {
 6414:                 $r->print('<h3>'.&mt('Co-author Management Update Result').'</h3>'."\n".
 6415:                           &update_coauthor_managers($permission));
 6416:             }
 6417:         }
 6418:     } elsif (($env{'form.action'} eq 'calist') && ($context eq 'author')) {
 6419:         if ($permission->{'cusr'}) {
 6420:             my ($role,$audom,$auname,$canview,$canedit) =
 6421:                 &Apache::lonviewcoauthors::get_allowable();
 6422:             if (($canedit) && ($env{'form.forceedit'})) {
 6423:                 &Apache::lonviewcoauthors::get_editor_crumbs($brcrum,'/adm/createuser');
 6424:                 my $args = { 'bread_crumbs' => $brcrum };
 6425:                 $r->print(&Apache::loncommon::start_page('Configure co-author listing',undef,
 6426:                                                          $args).
 6427:                           &Apache::lonviewcoauthors::edit_settings($audom,$auname,$role,
 6428:                                                                    '/adm/createuser'));
 6429:             } else {
 6430:                 push(@{$brcrum},
 6431:                        {href => '/adm/createuser?action=calist',
 6432:                         text => 'Coauthor-viewable list',
 6433:                         help => 'Author_List_Coauthors'});
 6434:                 my $args = { 'bread_crumbs' => $brcrum };
 6435:                 $r->print(&Apache::loncommon::start_page('Coauthor-viewable list',undef,
 6436:                                                          $args));
 6437:                 my %viewsettings =
 6438:                     &Apache::lonviewcoauthors::retrieve_view_settings($auname,$audom,$role);
 6439:                 if ($viewsettings{'show'} eq 'none') {
 6440:                     $r->print('<h3>'.&mt('Coauthor-viewable listing').'</h3>'.
 6441:                               '<p class="LC_info">'.
 6442:                               &mt('Listing of co-authors not enabled for this Authoring Space').
 6443:                               '</p>');
 6444:                 } else {
 6445:                     &Apache::lonviewcoauthors::print_coauthors($r,$auname,$audom,$role,
 6446:                                                                '/adm/createuser',\%viewsettings);
 6447:                 }
 6448:             }
 6449:         } else {
 6450:             $r->internal_redirect('/adm/viewcoauthors');
 6451:             return OK;
 6452:         }
 6453:     } else {
 6454:         $bread_crumbs_component = 'User Management';
 6455:         $args = { bread_crumbs           => $brcrum,
 6456:                   bread_crumbs_component => $bread_crumbs_component};
 6457:         $r->print(&header(undef,$args));
 6458:         $r->print(&print_main_menu($permission,$context,$crstype));
 6459:     }
 6460:     $r->print(&Apache::loncommon::end_page());
 6461:     return OK;
 6462: }
 6463: 
 6464: sub header {
 6465:     my ($jscript,$args) = @_;
 6466:     my $start_page;
 6467:     if (ref($args) eq 'HASH') {
 6468:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 6469:     } else {
 6470:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 6471:     }
 6472:     return $start_page;
 6473: }
 6474: 
 6475: sub add_script {
 6476:     my ($js) = @_;
 6477:     return '<script type="text/javascript">'."\n"
 6478:           .'// <![CDATA['."\n"
 6479:           .$js."\n"
 6480:           .'// ]]>'."\n"
 6481:           .'</script>'."\n";
 6482: }
 6483: 
 6484: sub usernamerequest_javascript {
 6485:     my $js = <<ENDJS;
 6486: 
 6487: function openusernamereqdisplay(dom,uname,queue) {
 6488:     var url = '/adm/createuser?action=displayuserreq';
 6489:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 6490:     var title = 'Account_Request_Browser';
 6491:     var options = 'scrollbars=1,resizable=1,menubar=0';
 6492:     options += ',width=700,height=600';
 6493:     var stdeditbrowser = open(url,title,options,'1');
 6494:     stdeditbrowser.focus();
 6495:     return;
 6496: }
 6497:  
 6498: ENDJS
 6499: }
 6500: 
 6501: sub close_popup_form {
 6502:     my $close= &mt('Close Window');
 6503:     return << "END";
 6504: <p><form name="displayreq" action="" method="post">
 6505: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 6506: </form></p>
 6507: END
 6508: }
 6509: 
 6510: sub verify_user_display {
 6511:     my ($context) = @_;
 6512:     my %lt = &Apache::lonlocal::texthash (
 6513:         course    => 'course(s): description, section(s), status',
 6514:         community => 'community(s): description, section(s), status',
 6515:         author    => 'author',
 6516:     );
 6517:     my $photos;
 6518:     if (($context eq 'course') && $env{'request.course.id'}) {
 6519:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 6520:     }
 6521:     my $output = <<"END";
 6522: 
 6523: function hide_searching() {
 6524:     if (document.getElementById('searching')) {
 6525:         document.getElementById('searching').style.display = 'none';
 6526:     }
 6527:     return;
 6528: }
 6529: 
 6530: function display_update() {
 6531:     document.studentform.action.value = 'listusers';
 6532:     document.studentform.phase.value = 'display';
 6533:     document.studentform.submit();
 6534: }
 6535: 
 6536: function updateCols(caller) {
 6537:     var context = '$context';
 6538:     var photos = '$photos';
 6539:     if (caller == 'Status') {
 6540:         if ((context == 'domain') && 
 6541:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6542:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 6543:             document.getElementById('showcolstatus').checked = false;
 6544:             document.getElementById('showcolstatus').disabled = 'disabled';
 6545:             document.getElementById('showcolstart').checked = false;
 6546:             document.getElementById('showcolend').checked = false;
 6547:         } else {
 6548:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6549:                 document.getElementById('showcolstatus').checked = true;
 6550:                 document.getElementById('showcolstatus').disabled = '';
 6551:                 document.getElementById('showcolstart').checked = true;
 6552:                 document.getElementById('showcolend').checked = true;
 6553:             } else {
 6554:                 document.getElementById('showcolstatus').checked = false;
 6555:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6556:                 document.getElementById('showcolstart').checked = false;
 6557:                 document.getElementById('showcolend').checked = false;
 6558:             }
 6559:             if (context == 'author') {
 6560:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Expired') {
 6561:                     document.getElementById('showcolmanager').checked = false;
 6562:                     document.getElementById('showcolmanager').disabled = 'disabled';
 6563:                 } else if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value != 'aa') {
 6564:                     document.getElementById('showcolmanager').checked = true;
 6565:                     document.getElementById('showcolmanager').disabled = '';
 6566:                 }
 6567:             }
 6568:         }
 6569:     }
 6570:     if (caller == 'output') {
 6571:         if (photos == 1) {
 6572:             if (document.getElementById('showcolphoto')) {
 6573:                 var photoitem = document.getElementById('showcolphoto');
 6574:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 6575:                     photoitem.checked = true;
 6576:                     photoitem.disabled = '';
 6577:                 } else {
 6578:                     photoitem.checked = false;
 6579:                     photoitem.disabled = 'disabled';
 6580:                 }
 6581:             }
 6582:         }
 6583:     }
 6584:     if (caller == 'showrole') {
 6585:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 6586:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 6587:             document.getElementById('showcolrole').checked = true;
 6588:             document.getElementById('showcolrole').disabled = '';
 6589:         } else {
 6590:             document.getElementById('showcolrole').checked = false;
 6591:             document.getElementById('showcolrole').disabled = 'disabled';
 6592:         }
 6593:         if (context == 'domain') {
 6594:             var quotausageshow = 0;
 6595:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6596:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 6597:                 document.getElementById('showcolstatus').checked = false;
 6598:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6599:                 document.getElementById('showcolstart').checked = false;
 6600:                 document.getElementById('showcolend').checked = false;
 6601:             } else {
 6602:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6603:                     document.getElementById('showcolstatus').checked = true;
 6604:                     document.getElementById('showcolstatus').disabled = '';
 6605:                     document.getElementById('showcolstart').checked = true;
 6606:                     document.getElementById('showcolend').checked = true;
 6607:                 }
 6608:             }
 6609:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 6610:                 document.getElementById('showcolextent').disabled = 'disabled';
 6611:                 document.getElementById('showcolextent').checked = 'false';
 6612:                 document.getElementById('showextent').style.display='none';
 6613:                 document.getElementById('showcoltextextent').innerHTML = '';
 6614:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 6615:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 6616:                     if (document.getElementById('showcolauthorusage')) {
 6617:                         document.getElementById('showcolauthorusage').disabled = '';
 6618:                     }
 6619:                     if (document.getElementById('showcolauthorquota')) {
 6620:                         document.getElementById('showcolauthorquota').disabled = '';
 6621:                     }
 6622:                     quotausageshow = 1;
 6623:                 }
 6624:             } else {
 6625:                 document.getElementById('showextent').style.display='block';
 6626:                 document.getElementById('showextent').style.textAlign='left';
 6627:                 document.getElementById('showextent').style.textFace='normal';
 6628:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 6629:                     document.getElementById('showcolextent').disabled = '';
 6630:                     document.getElementById('showcolextent').checked = 'true';
 6631:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 6632:                 } else {
 6633:                     document.getElementById('showcolextent').disabled = '';
 6634:                     document.getElementById('showcolextent').checked = 'true';
 6635:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 6636:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 6637:                     } else {
 6638:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 6639:                     }
 6640:                 }
 6641:             }
 6642:             if (quotausageshow == 0)  {
 6643:                 if (document.getElementById('showcolauthorusage')) {
 6644:                     document.getElementById('showcolauthorusage').checked = false;
 6645:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 6646:                 }
 6647:                 if (document.getElementById('showcolauthorquota')) {
 6648:                     document.getElementById('showcolauthorquota').checked = false;
 6649:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 6650:                 }
 6651:             }
 6652:         }
 6653:         if (context == 'author') {
 6654:             if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'aa') {
 6655:                 document.getElementById('showcolmanager').checked = false;
 6656:                 document.getElementById('showcolmanager').disabled = 'disabled';
 6657:             } else if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value != 'Expired') {
 6658:                 document.getElementById('showcolmanager').checked = true;
 6659:                 document.getElementById('showcolmanager').disabled = '';
 6660:             }
 6661:         }
 6662:     }
 6663:     return;
 6664: }
 6665: 
 6666: END
 6667:     return $output;
 6668: 
 6669: }
 6670: 
 6671: ###############################################################
 6672: ###############################################################
 6673: #  Menu Phase One
 6674: sub print_main_menu {
 6675:     my ($permission,$context,$crstype) = @_;
 6676:     my $linkcontext = $context;
 6677:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 6678:     if (($context eq 'course') && ($crstype eq 'Community')) {
 6679:         $linkcontext = lc($crstype);
 6680:         $stuterm = 'Members';
 6681:     }
 6682:     my %links = (
 6683:                 domain => {
 6684:                             upload     => 'Upload a File of Users',
 6685:                             singleuser => 'Add/Modify a User',
 6686:                             listusers  => 'Manage Users',
 6687:                             },
 6688:                 author => {
 6689:                             upload     => 'Upload a File of Co-authors',
 6690:                             singleuser => 'Add/Modify a Co-author',
 6691:                             listusers  => 'Manage Co-authors',
 6692:                             },
 6693:                 course => {
 6694:                             upload     => 'Upload a File of Course Users',
 6695:                             singleuser => 'Add/Modify a Course User',
 6696:                             listusers  => 'List and Modify Multiple Course Users',
 6697:                             },
 6698:                 community => {
 6699:                             upload     => 'Upload a File of Community Users',
 6700:                             singleuser => 'Add/Modify a Community User',
 6701:                             listusers  => 'List and Modify Multiple Community Users',
 6702:                            },
 6703:                 );
 6704:      my %linktitles = (
 6705:                 domain => {
 6706:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 6707:                             listusers  => 'Show and manage users in this domain.',
 6708:                             },
 6709:                 author => {
 6710:                             singleuser => 'Add a user with a co- or assistant author role.',
 6711:                             listusers  => 'Show and manage co- or assistant authors.',
 6712:                             },
 6713:                 course => {
 6714:                             singleuser => 'Add a user with a certain role to this course.',
 6715:                             listusers  => 'Show and manage users in this course.',
 6716:                             },
 6717:                 community => {
 6718:                             singleuser => 'Add a user with a certain role to this community.',
 6719:                             listusers  => 'Show and manage users in this community.',
 6720:                            },
 6721:                 );
 6722: 
 6723:   if ($linkcontext eq 'domain') {
 6724:       unless ($permission->{'cusr'}) {
 6725:           $links{'domain'}{'singleuser'} = 'View a User';
 6726:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 6727:       }
 6728:   } elsif ($linkcontext eq 'course') {
 6729:       unless ($permission->{'cusr'}) {
 6730:           $links{'course'}{'singleuser'} = 'View a Course User';
 6731:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 6732:           $links{'course'}{'listusers'} = 'List Course Users';
 6733:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 6734:       }
 6735:   } elsif ($linkcontext eq 'community') {
 6736:       unless ($permission->{'cusr'}) {
 6737:           $links{'community'}{'singleuser'} = 'View a Community User';
 6738:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 6739:           $links{'community'}{'listusers'} = 'List Community Users';
 6740:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 6741:       }
 6742:   }
 6743:   my @menu = ( {categorytitle => 'Single Users', 
 6744:          items =>
 6745:          [
 6746:             {
 6747:              linktext => $links{$linkcontext}{'singleuser'},
 6748:              icon => 'edit-redo.png',
 6749:              #help => 'Course_Change_Privileges',
 6750:              url => '/adm/createuser?action=singleuser',
 6751:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6752:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 6753:             },
 6754:          ]},
 6755: 
 6756:          {categorytitle => 'Multiple Users',
 6757:          items => 
 6758:          [
 6759:             {
 6760:              linktext => $links{$linkcontext}{'upload'},
 6761:              icon => 'uplusr.png',
 6762:              #help => 'Course_Create_Class_List',
 6763:              url => '/adm/createuser?action=upload',
 6764:              permission => $permission->{'cusr'},
 6765:              linktitle => 'Upload a CSV or a text file containing users.',
 6766:             },
 6767:             {
 6768:              linktext => $links{$linkcontext}{'listusers'},
 6769:              icon => 'mngcu.png',
 6770:              #help => 'Course_View_Class_List',
 6771:              url => '/adm/createuser?action=listusers',
 6772:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6773:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 6774:             },
 6775: 
 6776:          ]},
 6777: 
 6778:          {categorytitle => 'Administration',
 6779:          items => [ ]},
 6780:        );
 6781: 
 6782:     if ($context eq 'domain'){
 6783:         push(@{  $menu[0]->{items} }, # Single Users
 6784:             {
 6785:              linktext => 'User Access Log',
 6786:              icon => 'document-properties.png',
 6787:              #help => 'Domain_User_Access_Logs',
 6788:              url => '/adm/createuser?action=accesslogs',
 6789:              permission => $permission->{'activity'},
 6790:              linktitle => 'View user access log.',
 6791:             }
 6792:         );
 6793:         
 6794:         push(@{ $menu[2]->{items} }, #Category: Administration
 6795:             {
 6796:              linktext => 'Custom Roles',
 6797:              icon => 'emblem-photos.png',
 6798:              #help => 'Course_Editing_Custom_Roles',
 6799:              url => '/adm/createuser?action=custom',
 6800:              permission => $permission->{'custom'},
 6801:              linktitle => 'Configure a custom role.',
 6802:             },
 6803:             {
 6804:              linktext => 'Authoring Space Requests',
 6805:              icon => 'selfenrl-queue.png',
 6806:              #help => 'Domain_Role_Approvals',
 6807:              url => '/adm/createuser?action=processauthorreq',
 6808:              permission => $permission->{'cusr'},
 6809:              linktitle => 'Approve or reject author role requests',
 6810:             },
 6811:             {
 6812:              linktext => 'LON-CAPA Account Requests',
 6813:              icon => 'list-add.png',
 6814:              #help => 'Domain_Username_Approvals',
 6815:              url => '/adm/createuser?action=processusernamereq',
 6816:              permission => $permission->{'cusr'},
 6817:              linktitle => 'Approve or reject LON-CAPA account requests',
 6818:             },
 6819:             {
 6820:              linktext => 'Change Log',
 6821:              icon => 'document-properties.png',
 6822:              #help => 'Course_User_Logs',
 6823:              url => '/adm/createuser?action=changelogs',
 6824:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 6825:              linktitle => 'View change log.',
 6826:             },
 6827:         );
 6828:         
 6829:     }elsif ($context eq 'course'){
 6830:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 6831: 
 6832:         my %linktext = (
 6833:                          'Course'    => {
 6834:                                           single => 'Add/Modify a Student', 
 6835:                                           drop   => 'Drop Students',
 6836:                                           groups => 'Course Groups',
 6837:                                         },
 6838:                          'Community' => {
 6839:                                           single => 'Add/Modify a Member', 
 6840:                                           drop   => 'Drop Members',
 6841:                                           groups => 'Community Groups',
 6842:                                         },
 6843:                        );
 6844:         $linktext{'Placement'} = $linktext{'Course'};
 6845: 
 6846:         my %linktitle = (
 6847:             'Course' => {
 6848:                   single => 'Add a user with the role of student to this course',
 6849:                   drop   => 'Remove a student from this course.',
 6850:                   groups => 'Manage course groups',
 6851:                         },
 6852:             'Community' => {
 6853:                   single => 'Add a user with the role of member to this community',
 6854:                   drop   => 'Remove a member from this community.',
 6855:                   groups => 'Manage community groups',
 6856:                            },
 6857:         );
 6858: 
 6859:         $linktitle{'Placement'} = $linktitle{'Course'};
 6860: 
 6861:         push(@{ $menu[0]->{items} }, #Category: Single Users
 6862:             {   
 6863:              linktext => $linktext{$crstype}{'single'},
 6864:              #help => 'Course_Add_Student',
 6865:              icon => 'list-add.png',
 6866:              url => '/adm/createuser?action=singlestudent',
 6867:              permission => $permission->{'cusr'},
 6868:              linktitle => $linktitle{$crstype}{'single'},
 6869:             },
 6870:         );
 6871:         
 6872:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 6873:             {
 6874:              linktext => $linktext{$crstype}{'drop'},
 6875:              icon => 'edit-undo.png',
 6876:              #help => 'Course_Drop_Student',
 6877:              url => '/adm/createuser?action=drop',
 6878:              permission => $permission->{'cusr'},
 6879:              linktitle => $linktitle{$crstype}{'drop'},
 6880:             },
 6881:         );
 6882:         push(@{ $menu[2]->{items} }, #Category: Administration
 6883:             {
 6884:              linktext => 'Helpdesk Access',
 6885:              icon => 'helpdesk-access.png',
 6886:              #help => 'Course_Helpdesk_Access',
 6887:              url => '/adm/createuser?action=helpdesk',
 6888:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6889:                             ($permission->{'view'} || $permission->{'cusr'})),
 6890:              linktitle => 'Helpdesk access options',
 6891:             },
 6892:             {
 6893:              linktext => 'Custom Roles',
 6894:              icon => 'emblem-photos.png',
 6895:              #help => 'Course_Editing_Custom_Roles',
 6896:              url => '/adm/createuser?action=custom',
 6897:              permission => $permission->{'custom'},
 6898:              linktitle => 'Configure a custom role.',
 6899:             },
 6900:             {
 6901:              linktext => $linktext{$crstype}{'groups'},
 6902:              icon => 'grps.png',
 6903:              #help => 'Course_Manage_Group',
 6904:              url => '/adm/coursegroups?refpage=cusr',
 6905:              permission => $permission->{'grp_manage'},
 6906:              linktitle => $linktitle{$crstype}{'groups'},
 6907:             },
 6908:             {
 6909:              linktext => 'Change Log',
 6910:              icon => 'document-properties.png',
 6911:              #help => 'Course_User_Logs',
 6912:              url => '/adm/createuser?action=changelogs',
 6913:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6914:              linktitle => 'View change log.',
 6915:             },
 6916:         );
 6917:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 6918:             push(@{ $menu[2]->{items} },
 6919:                     {
 6920:                      linktext => 'Enrollment Requests',
 6921:                      icon => 'selfenrl-queue.png',
 6922:                      #help => 'Course_Approve_Selfenroll',
 6923:                      url => '/adm/createuser?action=selfenrollqueue',
 6924:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6925:                      linktitle =>'Approve or reject enrollment requests.',
 6926:                     },
 6927:             );
 6928:         }
 6929:         
 6930:         if (!exists($permission->{'cusr_section'})){
 6931:             if ($crstype ne 'Community') {
 6932:                 push(@{ $menu[2]->{items} },
 6933:                     {
 6934:                      linktext => 'Automated Enrollment',
 6935:                      icon => 'roles.png',
 6936:                      #help => 'Course_Automated_Enrollment',
 6937:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 6938:                                          && (($permission->{'cusr'}) ||
 6939:                                              ($permission->{'view'}))),
 6940:                      url  => '/adm/populate',
 6941:                      linktitle => 'Automated enrollment manager.',
 6942:                     }
 6943:                 );
 6944:             }
 6945:             push(@{ $menu[2]->{items} }, 
 6946:                 {
 6947:                  linktext => 'User Self-Enrollment',
 6948:                  icon => 'self_enroll.png',
 6949:                  #help => 'Course_Self_Enrollment',
 6950:                  url => '/adm/createuser?action=selfenroll',
 6951:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6952:                  linktitle => 'Configure user self-enrollment.',
 6953:                 },
 6954:             );
 6955:         }
 6956:     } elsif ($context eq 'author') {
 6957:         push(@{ $menu[2]->{items} }, #Category: Administration
 6958:             {
 6959:              linktext => 'Change Log',
 6960:              icon => 'document-properties.png',
 6961:              #help => 'Course_User_Logs',
 6962:              url => '/adm/createuser?action=changelogs',
 6963:              permission => $permission->{'cusr'},
 6964:              linktitle => 'View change log.',
 6965:             },
 6966:             {
 6967:              linktext => 'Co-author Managers',
 6968:              icon => 'camanager.png',
 6969:              #help => 'Coauthor_Management',
 6970:              url => '/adm/createuser?action=camanagers',
 6971:              permission => $permission->{'author'},
 6972:              linktitle => 'Assign/Revoke right to manage co-author roles',
 6973:             },
 6974:             {
 6975:              linktext => 'Configure Co-author Listing',
 6976:              icon => 'coauthors.png',
 6977:              #help => 'Coauthor_Settings',
 6978:              url => '/adm/createuser?action=calist&forceedit=1',
 6979:              permission => ($permission->{'cusr'}),
 6980:              linktitle => 'Set availability of coauthor-viewable user listing',
 6981:             },
 6982:         );
 6983:     }
 6984:     push(@{ $menu[2]->{items} },
 6985:         {
 6986:          linktext => 'Role Requests (other domains)',
 6987:          icon => 'edit-find.png',
 6988:          #help => 'Role_Requests',
 6989:          url => '/adm/createuser?action=rolerequests',
 6990:          permission => $permission->{'cusr'},
 6991:          linktitle => 'Role requests for users in other domains',
 6992:         },
 6993:     );
 6994:     if (&show_role_requests($context,$env{'request.role.domain'})) {
 6995:         push(@{ $menu[2]->{items} },
 6996:             {
 6997:              linktext => 'Queued Role Assignments (this domain)',
 6998:              icon => 'edit-find.png',
 6999:              #help => 'Role_Approvals',
 7000:              url => '/adm/createuser?action=queuedroles',
 7001:              permission => $permission->{'cusr'},
 7002:              linktitle => "Role requests for this domain's users",
 7003:             },
 7004:         );
 7005:     }
 7006:     return Apache::lonhtmlcommon::generate_menu(@menu);
 7007: #               { text => 'View Log-in History',
 7008: #                 help => 'Course_User_Logins',
 7009: #                 action => 'logins',
 7010: #                 permission => $permission->{'cusr'},
 7011: #               });
 7012: }
 7013: 
 7014: sub restore_prev_selections {
 7015:     my %saveable_parameters = ('srchby'   => 'scalar',
 7016: 			       'srchin'   => 'scalar',
 7017: 			       'srchtype' => 'scalar',
 7018: 			       );
 7019:     &Apache::loncommon::store_settings('user','user_picker',
 7020: 				       \%saveable_parameters);
 7021:     &Apache::loncommon::restore_settings('user','user_picker',
 7022: 					 \%saveable_parameters);
 7023: }
 7024: 
 7025: sub print_selfenroll_menu {
 7026:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 7027:     my $crstype = &Apache::loncommon::course_type();
 7028:     my $formname = 'selfenroll';
 7029:     my $nolink = 1;
 7030:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7031:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 7032:     my $setsec_js = 
 7033:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 7034:     my %alerts = &Apache::lonlocal::texthash(
 7035:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 7036:         butn => 'but no user types have been checked.',
 7037:         wilf => "Please uncheck 'activate' or check at least one type.",
 7038:     );
 7039:     my $disabled;
 7040:     if ($readonly) {
 7041:        $disabled = ' disabled="disabled"';
 7042:     }
 7043:     &js_escape(\%alerts);
 7044:     my $selfenroll_js = <<"ENDSCRIPT";
 7045: function update_types(caller,num) {
 7046:     var delidx = getIndexByName('selfenroll_delete');
 7047:     var actidx = getIndexByName('selfenroll_activate');
 7048:     if (caller == 'selfenroll_all') {
 7049:         var selall;
 7050:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7051:             if (document.$formname.selfenroll_all[i].checked) {
 7052:                 selall = document.$formname.selfenroll_all[i].value;
 7053:             }
 7054:         }
 7055:         if (selall == 1) {
 7056:             if (delidx != -1) {
 7057:                 if (document.$formname.selfenroll_delete.length) {
 7058:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7059:                         document.$formname.selfenroll_delete[j].checked = true;
 7060:                     }
 7061:                 } else {
 7062:                     document.$formname.elements[delidx].checked = true;
 7063:                 }
 7064:             }
 7065:             if (actidx != -1) {
 7066:                 if (document.$formname.selfenroll_activate.length) {
 7067:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7068:                         document.$formname.selfenroll_activate[j].checked = false;
 7069:                     }
 7070:                 } else {
 7071:                     document.$formname.elements[actidx].checked = false;
 7072:                 }
 7073:             }
 7074:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 7075:         }
 7076:     }
 7077:     if (caller == 'selfenroll_activate') {
 7078:         if (document.$formname.selfenroll_activate.length) {
 7079:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7080:                 if (document.$formname.selfenroll_activate[j].value == num) {
 7081:                     if (document.$formname.selfenroll_activate[j].checked) {
 7082:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7083:                             if (document.$formname.selfenroll_all[i].value == '1') {
 7084:                                 document.$formname.selfenroll_all[i].checked = false;
 7085:                             }
 7086:                             if (document.$formname.selfenroll_all[i].value == '0') {
 7087:                                 document.$formname.selfenroll_all[i].checked = true;
 7088:                             }
 7089:                         }
 7090:                     }
 7091:                 }
 7092:             }
 7093:         } else {
 7094:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7095:                 if (document.$formname.selfenroll_all[i].value == '1') {
 7096:                     document.$formname.selfenroll_all[i].checked = false;
 7097:                 }
 7098:                 if (document.$formname.selfenroll_all[i].value == '0') {
 7099:                     document.$formname.selfenroll_all[i].checked = true;
 7100:                 }
 7101:             }
 7102:         }
 7103:     }
 7104:     if (caller == 'selfenroll_delete') {
 7105:         if (document.$formname.selfenroll_delete.length) {
 7106:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7107:                 if (document.$formname.selfenroll_delete[j].value == num) {
 7108:                     if (document.$formname.selfenroll_delete[j].checked) {
 7109:                         var delindex = getIndexByName('selfenroll_types_'+num);
 7110:                         if (delindex != -1) { 
 7111:                             if (document.$formname.elements[delindex].length) {
 7112:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7113:                                     document.$formname.elements[delindex][k].checked = false;
 7114:                                 }
 7115:                             } else {
 7116:                                 document.$formname.elements[delindex].checked = false;
 7117:                             }
 7118:                         }
 7119:                     }
 7120:                 }
 7121:             }
 7122:         } else {
 7123:             if (document.$formname.selfenroll_delete.checked) {
 7124:                 var delindex = getIndexByName('selfenroll_types_'+num);
 7125:                 if (delindex != -1) {
 7126:                     if (document.$formname.elements[delindex].length) {
 7127:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7128:                             document.$formname.elements[delindex][k].checked = false;
 7129:                         }
 7130:                     } else {
 7131:                         document.$formname.elements[delindex].checked = false;
 7132:                     }
 7133:                 }
 7134:             }
 7135:         }
 7136:     }
 7137:     return;
 7138: }
 7139: 
 7140: function validate_types(form) {
 7141:     var needaction = new Array();
 7142:     var countfail = 0;
 7143:     var actidx = getIndexByName('selfenroll_activate');
 7144:     if (actidx != -1) {
 7145:         if (document.$formname.selfenroll_activate.length) {
 7146:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7147:                 var num = document.$formname.selfenroll_activate[j].value;
 7148:                 if (document.$formname.selfenroll_activate[j].checked) {
 7149:                     countfail = check_types(num,countfail,needaction)
 7150:                 }
 7151:             }
 7152:         } else {
 7153:             if (document.$formname.selfenroll_activate.checked) {
 7154:                 var num = document.$formname.selfenroll_activate.value;
 7155:                 countfail = check_types(num,countfail,needaction)
 7156:             }
 7157:         }
 7158:     }
 7159:     if (countfail > 0) {
 7160:         var msg = "$alerts{'acto'}\\n";
 7161:         var loopend = needaction.length -1;
 7162:         if (loopend > 0) {
 7163:             for (var m=0; m<loopend; m++) {
 7164:                 msg += needaction[m]+", ";
 7165:             }
 7166:         }
 7167:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 7168:         alert(msg);
 7169:         return; 
 7170:     }
 7171:     setSections(form);
 7172: }
 7173: 
 7174: function check_types(num,countfail,needaction) {
 7175:     var boxname = 'selfenroll_types_'+num;
 7176:     var typeidx = getIndexByName(boxname);
 7177:     var count = 0;
 7178:     if (typeidx != -1) {
 7179:         if (document.$formname.elements[boxname].length) {
 7180:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 7181:                 if (document.$formname.elements[boxname][k].checked) {
 7182:                     count ++;
 7183:                 }
 7184:             }
 7185:         } else {
 7186:             if (document.$formname.elements[typeidx].checked) {
 7187:                 count ++;
 7188:             }
 7189:         }
 7190:         if (count == 0) {
 7191:             var domidx = getIndexByName('selfenroll_dom_'+num);
 7192:             if (domidx != -1) {
 7193:                 var domname = document.$formname.elements[domidx].value;
 7194:                 needaction[countfail] = domname;
 7195:                 countfail ++;
 7196:             }
 7197:         }
 7198:     }
 7199:     return countfail;
 7200: }
 7201: 
 7202: function toggleNotify() {
 7203:     var selfenrollApproval = 0;
 7204:     if (document.$formname.selfenroll_approval.length) {
 7205:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 7206:             if (document.$formname.selfenroll_approval[i].checked) {
 7207:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 7208:                 break;        
 7209:             }
 7210:         }
 7211:     }
 7212:     if (document.getElementById('notified')) {
 7213:         if (selfenrollApproval == 0) {
 7214:             document.getElementById('notified').style.display='none';
 7215:         } else {
 7216:             document.getElementById('notified').style.display='block';
 7217:         }
 7218:     }
 7219:     return;
 7220: }
 7221: 
 7222: function getIndexByName(item) {
 7223:     for (var i=0;i<document.$formname.elements.length;i++) {
 7224:         if (document.$formname.elements[i].name == item) {
 7225:             return i;
 7226:         }
 7227:     }
 7228:     return -1;
 7229: }
 7230: ENDSCRIPT
 7231: 
 7232:     my $output = '<script type="text/javascript">'."\n".
 7233:                  '// <![CDATA['."\n".
 7234:                  $setsec_js."\n".$selfenroll_js."\n".
 7235:                  '// ]]>'."\n".
 7236:                  '</script>'."\n".
 7237:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 7238:     my $visactions = &cat_visibility($cdom);
 7239:     my ($cathash,%cattype);
 7240:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7241:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7242:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7243:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7244:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7245:         if ($cattype{'auth'} eq '') {
 7246:             $cattype{'auth'} = 'std';
 7247:         }
 7248:         if ($cattype{'unauth'} eq '') {
 7249:             $cattype{'unauth'} = 'std';
 7250:         }
 7251:     } else {
 7252:         $cathash = {};
 7253:         $cattype{'auth'} = 'std';
 7254:         $cattype{'unauth'} = 'std';
 7255:     }
 7256:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7257:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7258:                   '<br />'.
 7259:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7260:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7261:                   '</ul>');
 7262:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7263:         if ($currsettings->{'uniquecode'}) {
 7264:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7265:         } else {
 7266:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7267:                   '<br />'.
 7268:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7269:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7270:                   '</ul><br />');
 7271:         }
 7272:     } else {
 7273:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7274:         if (ref($visactions) eq 'HASH') {
 7275:             if ($visible) {
 7276:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 7277:            } else {
 7278:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 7279:                           .$visactions->{'yous'}.
 7280:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 7281:                 if (ref($vismsgs) eq 'ARRAY') {
 7282:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 7283:                     foreach my $item (@{$vismsgs}) {
 7284:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 7285:                     }
 7286:                     $output .= '</ul>';
 7287:                 }
 7288:                 $output .= '</p>';
 7289:             }
 7290:         }
 7291:     }
 7292:     my $actionhref = '/adm/createuser';
 7293:     if ($context eq 'domain') {
 7294:         $actionhref = '/adm/modifycourse';
 7295:     }
 7296: 
 7297:     my %noedit;
 7298:     unless ($context eq 'domain') {
 7299:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7300:     }
 7301:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 7302:                &Apache::lonhtmlcommon::start_pick_box();
 7303:     if (ref($row) eq 'ARRAY') {
 7304:         foreach my $item (@{$row}) {
 7305:             my $title = $item; 
 7306:             if (ref($lt) eq 'HASH') {
 7307:                 $title = $lt->{$item};
 7308:             }
 7309:             $output .= &Apache::lonhtmlcommon::row_title($title);
 7310:             if ($item eq 'types') {
 7311:                 my $curr_types;
 7312:                 if (ref($currsettings) eq 'HASH') {
 7313:                     $curr_types = $currsettings->{'selfenroll_types'};
 7314:                 }
 7315:                 if ($noedit{$item}) {
 7316:                     if ($curr_types eq '*') {
 7317:                         $output .= &mt('Any user in any domain');   
 7318:                     } else {
 7319:                         my @entries = split(/;/,$curr_types);
 7320:                         if (@entries > 0) {
 7321:                             $output .= '<ul>'; 
 7322:                             foreach my $entry (@entries) {
 7323:                                 my ($currdom,$typestr) = split(/:/,$entry);
 7324:                                 next if ($typestr eq '');
 7325:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 7326:                                 my @currinsttypes = split(',',$typestr);
 7327:                                 my ($othertitle,$usertypes,$types) = 
 7328:                                     &Apache::loncommon::sorted_inst_types($currdom);
 7329:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7330:                                     $usertypes->{'any'} = &mt('any user'); 
 7331:                                     if (keys(%{$usertypes}) > 0) {
 7332:                                         $usertypes->{'other'} = &mt('other users');
 7333:                                     }
 7334:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 7335:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 7336:                                  }
 7337:                             }
 7338:                             $output .= '</ul>';
 7339:                         } else {
 7340:                             $output .= &mt('None');
 7341:                         }
 7342:                     }
 7343:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7344:                     next;
 7345:                 }
 7346:                 my $showdomdesc = 1;
 7347:                 my $includeempty = 1;
 7348:                 my $num = 0;
 7349:                 $output .= &Apache::loncommon::start_data_table().
 7350:                            &Apache::loncommon::start_data_table_row()
 7351:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 7352:                            .&mt('Any user in any domain:')
 7353:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 7354:                 if ($curr_types eq '*') {
 7355:                     $output .= ' checked="checked" '; 
 7356:                 }
 7357:                 $output .= 'onchange="javascript:update_types('.
 7358:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 7359:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 7360:                 if ($curr_types ne '*') {
 7361:                     $output .= ' checked="checked" ';
 7362:                 }
 7363:                 $output .= ' onchange="javascript:update_types('.
 7364:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 7365:                            &Apache::loncommon::end_data_table_row().
 7366:                            &Apache::loncommon::end_data_table().
 7367:                            &mt('Or').'<br />'.
 7368:                            &Apache::loncommon::start_data_table();
 7369:                 my %currdoms;
 7370:                 if ($curr_types eq '') {
 7371:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 7372:                 } elsif ($curr_types ne '*') {
 7373:                     my @entries = split(/;/,$curr_types);
 7374:                     if (@entries > 0) {
 7375:                         foreach my $entry (@entries) {
 7376:                             my ($currdom,$typestr) = split(/:/,$entry);
 7377:                             $currdoms{$currdom} = 1;
 7378:                             my $domdesc = &Apache::lonnet::domain($currdom);
 7379:                             my @currinsttypes = split(',',$typestr);
 7380:                             $output .= &Apache::loncommon::start_data_table_row()
 7381:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 7382:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 7383:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 7384:                                        .'" value="'.$currdom.'" /></span><br />'
 7385:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 7386:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 7387:                                        .&mt('Delete').'</label></span></td>';
 7388:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 7389:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 7390:                                        .&Apache::loncommon::end_data_table_row();
 7391:                             $num ++;
 7392:                         }
 7393:                     }
 7394:                 }
 7395:                 my $add_domtitle = &mt('Users in additional domain:');
 7396:                 if ($curr_types eq '*') { 
 7397:                     $add_domtitle = &mt('Users in specific domain:');
 7398:                 } elsif ($curr_types eq '') {
 7399:                     $add_domtitle = &mt('Users in other domain:');
 7400:                 }
 7401:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 7402:                 $output .= &Apache::loncommon::start_data_table_row()
 7403:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 7404:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 7405:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 7406:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 7407:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 7408:                            .&Apache::loncommon::end_data_table();
 7409:             } elsif ($item eq 'registered') {
 7410:                 my ($regon,$regoff);
 7411:                 my $registered;
 7412:                 if (ref($currsettings) eq 'HASH') {
 7413:                     $registered = $currsettings->{'selfenroll_registered'};
 7414:                 }
 7415:                 if ($noedit{$item}) {
 7416:                     if ($registered) {
 7417:                         $output .= &mt('Must be registered in course');
 7418:                     } else {
 7419:                         $output .= &mt('No requirement');
 7420:                     }
 7421:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7422:                     next;
 7423:                 }
 7424:                 if ($registered) {
 7425:                     $regon = ' checked="checked" ';
 7426:                     $regoff = '';
 7427:                 } else {
 7428:                     $regon = '';
 7429:                     $regoff = ' checked="checked" ';
 7430:                 }
 7431:                 $output .= '<label>'.
 7432:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 7433:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 7434:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 7435:                            &mt('No').'</label>';
 7436:             } elsif ($item eq 'enroll_dates') {
 7437:                 my ($starttime,$endtime);
 7438:                 if (ref($currsettings) eq 'HASH') {
 7439:                     $starttime = $currsettings->{'selfenroll_start_date'};
 7440:                     $endtime = $currsettings->{'selfenroll_end_date'};
 7441:                     if ($starttime eq '') {
 7442:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7443:                     }
 7444:                     if ($endtime eq '') {
 7445:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7446:                     }
 7447:                 }
 7448:                 if ($noedit{$item}) {
 7449:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7450:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7451:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7452:                     next;
 7453:                 }
 7454:                 my $startform =
 7455:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 7456:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7457:                 my $endform =
 7458:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 7459:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7460:                 $output .= &selfenroll_date_forms($startform,$endform);
 7461:             } elsif ($item eq 'access_dates') {
 7462:                 my ($starttime,$endtime);
 7463:                 if (ref($currsettings) eq 'HASH') {
 7464:                     $starttime = $currsettings->{'selfenroll_start_access'};
 7465:                     $endtime = $currsettings->{'selfenroll_end_access'};
 7466:                     if ($starttime eq '') {
 7467:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7468:                     }
 7469:                     if ($endtime eq '') {
 7470:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7471:                     }
 7472:                 }
 7473:                 if ($noedit{$item}) {
 7474:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7475:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7476:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7477:                     next;
 7478:                 }
 7479:                 my $startform =
 7480:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 7481:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7482:                 my $endform =
 7483:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 7484:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7485:                 $output .= &selfenroll_date_forms($startform,$endform);
 7486:             } elsif ($item eq 'section') {
 7487:                 my $currsec;
 7488:                 if (ref($currsettings) eq 'HASH') {
 7489:                     $currsec = $currsettings->{'selfenroll_section'};
 7490:                 }
 7491:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 7492:                 my $newsecval;
 7493:                 if ($currsec ne 'none' && $currsec ne '') {
 7494:                     if (!defined($sections_count{$currsec})) {
 7495:                         $newsecval = $currsec;
 7496:                     }
 7497:                 }
 7498:                 if ($noedit{$item}) {
 7499:                     if ($currsec ne '') {
 7500:                         $output .= $currsec;
 7501:                     } else {
 7502:                         $output .= &mt('No specific section');
 7503:                     }
 7504:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7505:                     next;
 7506:                 }
 7507:                 my $sections_select = 
 7508:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 7509:                 $output .= '<table class="LC_createuser">'."\n".
 7510:                            '<tr class="LC_section_row">'."\n".
 7511:                            '<td align="center">'.&mt('Existing sections')."\n".
 7512:                            '<br />'.$sections_select.'</td><td align="center">'.
 7513:                            &mt('New section').'<br />'."\n".
 7514:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 7515:                            '<input type="hidden" name="sections" value="" />'."\n".
 7516:                            '</td></tr></table>'."\n";
 7517:             } elsif ($item eq 'approval') {
 7518:                 my ($currnotified,$currapproval,%appchecked);
 7519:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7520:                 if (ref($currsettings) eq 'HASH') {
 7521:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 7522:                     $currapproval = $currsettings->{'selfenroll_approval'};
 7523:                 }
 7524:                 if ($currapproval !~ /^[012]$/) {
 7525:                     $currapproval = 0;
 7526:                 }
 7527:                 if ($noedit{$item}) {
 7528:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 7529:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 7530:                     next;
 7531:                 }
 7532:                 $appchecked{$currapproval} = ' checked="checked"';
 7533:                 for my $i (0..2) {
 7534:                     $output .= '<label>'.
 7535:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 7536:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 7537:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 7538:                 }
 7539:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 7540:                 my (@ccs,%notified);
 7541:                 my $ccrole = 'cc';
 7542:                 if ($crstype eq 'Community') {
 7543:                     $ccrole = 'co';
 7544:                 }
 7545:                 if ($advhash{$ccrole}) {
 7546:                     @ccs = split(/,/,$advhash{$ccrole});
 7547:                 }
 7548:                 if ($currnotified) {
 7549:                     foreach my $current (split(/,/,$currnotified)) {
 7550:                         $notified{$current} = 1;
 7551:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 7552:                             push(@ccs,$current);
 7553:                         }
 7554:                     }
 7555:                 }
 7556:                 if (@ccs) {
 7557:                     my $style;
 7558:                     unless ($currapproval) {
 7559:                         $style = ' style="display: none;"'; 
 7560:                     }
 7561:                     $output .= '<br /><div id="notified"'.$style.'>'.
 7562:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 7563:                                &Apache::loncommon::start_data_table().
 7564:                                &Apache::loncommon::start_data_table_row();
 7565:                     my $count = 0;
 7566:                     my $numcols = 4;
 7567:                     foreach my $cc (sort(@ccs)) {
 7568:                         my $notifyon;
 7569:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 7570:                         if ($notified{$cc}) {
 7571:                             $notifyon = ' checked="checked" ';
 7572:                         }
 7573:                         if ($count && !$count%$numcols) {
 7574:                             $output .= &Apache::loncommon::end_data_table_row().
 7575:                                        &Apache::loncommon::start_data_table_row()
 7576:                         }
 7577:                         $output .= '<td><span class="LC_nobreak"><label>'.
 7578:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 7579:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 7580:                                    '</label></span></td>';
 7581:                         $count ++;
 7582:                     }
 7583:                     my $rem = $count%$numcols;
 7584:                     if ($rem) {
 7585:                         my $emptycols = $numcols - $rem;
 7586:                         for (my $i=0; $i<$emptycols; $i++) { 
 7587:                             $output .= '<td>&nbsp;</td>';
 7588:                         }
 7589:                     }
 7590:                     $output .= &Apache::loncommon::end_data_table_row().
 7591:                                &Apache::loncommon::end_data_table().
 7592:                                '</div>';
 7593:                 }
 7594:             } elsif ($item eq 'limit') {
 7595:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 7596:                 if (ref($currsettings) eq 'HASH') {
 7597:                     $currlim = $currsettings->{'selfenroll_limit'};
 7598:                     $currcap = $currsettings->{'selfenroll_cap'};
 7599:                 }
 7600:                 if ($noedit{$item}) {
 7601:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 7602:                         if ($currlim eq 'allstudents') {
 7603:                             $output .= &mt('Limit by total students');
 7604:                         } elsif ($currlim eq 'selfenrolled') {
 7605:                             $output .= &mt('Limit by total self-enrolled students');
 7606:                         }
 7607:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 7608:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 7609:                     } else {
 7610:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 7611:                     }
 7612:                     next;
 7613:                 }
 7614:                 if ($currlim eq 'allstudents') {
 7615:                     $crslimit = ' checked="checked" ';
 7616:                     $selflimit = ' ';
 7617:                     $nolimit = ' ';
 7618:                 } elsif ($currlim eq 'selfenrolled') {
 7619:                     $crslimit = ' ';
 7620:                     $selflimit = ' checked="checked" ';
 7621:                     $nolimit = ' '; 
 7622:                 } else {
 7623:                     $crslimit = ' ';
 7624:                     $selflimit = ' ';
 7625:                     $nolimit = ' checked="checked" ';
 7626:                 }
 7627:                 $output .= '<table><tr><td><label>'.
 7628:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 7629:                            &mt('No limit').'</label></td><td><label>'.
 7630:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 7631:                            &mt('Limit by total students').'</label></td><td><label>'.
 7632:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 7633:                            &mt('Limit by total self-enrolled students').
 7634:                            '</td></tr><tr>'.
 7635:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 7636:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 7637:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 7638:             }
 7639:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 7640:         }
 7641:     }
 7642:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 7643:     unless ($readonly) {
 7644:         $output .= '<input type="button" name="selfenrollconf" value="'
 7645:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 7646:     }
 7647:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 7648:               .'<input type="hidden" name="state" value="done" />'."\n"
 7649:               .$additional.'</form>';
 7650:     $r->print($output);
 7651:     return;
 7652: }
 7653: 
 7654: sub get_noedit_fields {
 7655:     my ($cdom,$cnum,$crstype,$row) = @_;
 7656:     my %noedit;
 7657:     if (ref($row) eq 'ARRAY') {
 7658:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 7659:                                                            'internal.selfenrollmgrdc',
 7660:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 7661:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 7662:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 7663:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 7664:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 7665:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 7666:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 7667: 
 7668:         foreach my $item (@{$row}) {
 7669:             next if ($specific_managebycc{$item});
 7670:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 7671:                 $noedit{$item} = 1;
 7672:             }
 7673:         }
 7674:     }
 7675:     return %noedit;
 7676: }
 7677: 
 7678: sub visible_in_stdcat {
 7679:     my ($cdom,$cnum,$domconf) = @_;
 7680:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 7681:     unless (ref($domconf) eq 'HASH') {
 7682:         return ($visible,$cansetvis,\@vismsgs);
 7683:     }
 7684:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7685:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 7686:             $settable{'togglecats'} = 1;
 7687:         }
 7688:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 7689:             $settable{'categorize'} = 1;
 7690:         }
 7691:         $cathash = $domconf->{'coursecategories'}{'cats'};
 7692:     }
 7693:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 7694:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 7695:     } elsif ($settable{'togglecats'}) {
 7696:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 7697:     } elsif ($settable{'categorize'}) {
 7698:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 7699:     } else {
 7700:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 7701:     }
 7702:      
 7703:     my %currsettings =
 7704:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 7705:                              $cdom,$cnum);
 7706:     $visible = 0;
 7707:     if ($currsettings{'internal.coursecode'} ne '') {
 7708:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7709:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7710:             if (ref($cathash) eq 'HASH') {
 7711:                 if ($cathash->{'instcode::0'} eq '') {
 7712:                     push(@vismsgs,'dc_addinst'); 
 7713:                 } else {
 7714:                     $visible = 1;
 7715:                 }
 7716:             } else {
 7717:                 $visible = 1;
 7718:             }
 7719:         } else {
 7720:             $visible = 1;
 7721:         }
 7722:     } else {
 7723:         if (ref($cathash) eq 'HASH') {
 7724:             if ($cathash->{'instcode::0'} ne '') {
 7725:                 push(@vismsgs,'dc_instcode');
 7726:             }
 7727:         } else {
 7728:             push(@vismsgs,'dc_instcode');
 7729:         }
 7730:     }
 7731:     if ($currsettings{'categories'} ne '') {
 7732:         my $cathash;
 7733:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7734:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7735:             if (ref($cathash) eq 'HASH') {
 7736:                 if (keys(%{$cathash}) == 0) {
 7737:                     push(@vismsgs,'dc_catalog');
 7738:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 7739:                     push(@vismsgs,'dc_categories');
 7740:                 } else {
 7741:                     my @currcategories = split('&',$currsettings{'categories'});
 7742:                     my $matched = 0;
 7743:                     foreach my $cat (@currcategories) {
 7744:                         if ($cathash->{$cat} ne '') {
 7745:                             $visible = 1;
 7746:                             $matched = 1;
 7747:                             last;
 7748:                         }
 7749:                     }
 7750:                     if (!$matched) {
 7751:                         if ($settable{'categorize'}) { 
 7752:                             push(@vismsgs,'chgcat');
 7753:                         } else {
 7754:                             push(@vismsgs,'dc_chgcat');
 7755:                         }
 7756:                     }
 7757:                 }
 7758:             }
 7759:         }
 7760:     } else {
 7761:         if (ref($cathash) eq 'HASH') {
 7762:             if ((keys(%{$cathash}) > 1) || 
 7763:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 7764:                 if ($settable{'categorize'}) {
 7765:                     push(@vismsgs,'addcat');
 7766:                 } else {
 7767:                     push(@vismsgs,'dc_addcat');
 7768:                 }
 7769:             }
 7770:         }
 7771:     }
 7772:     if ($currsettings{'hidefromcat'} eq 'yes') {
 7773:         $visible = 0;
 7774:         if ($settable{'togglecats'}) {
 7775:             unshift(@vismsgs,'unhide');
 7776:         } else {
 7777:             unshift(@vismsgs,'dc_unhide')
 7778:         }
 7779:     }
 7780:     return ($visible,$cansetvis,\@vismsgs);
 7781: }
 7782: 
 7783: sub cat_visibility {
 7784:     my ($cdom) = @_;
 7785:     my %visactions = &Apache::lonlocal::texthash(
 7786:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 7787:                    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.',
 7788:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 7789:                    none => 'Display of a course catalog is disabled for this domain.',
 7790:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 7791:                    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.',
 7792:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 7793:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 7794:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 7795:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 7796:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 7797:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 7798:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 7799:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 7800:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 7801:                    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',
 7802:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 7803:     );
 7804:     if ($env{'request.role'} eq "dc./$cdom/") {
 7805:         $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;');
 7806:         $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;');
 7807:         $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;');
 7808:         $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;');
 7809:         $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;');
 7810:         $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;');
 7811:         $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;');
 7812:         $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;');
 7813:         $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;');
 7814:     }
 7815:     $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>"');
 7816:     $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>"');
 7817:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 7818:     return \%visactions;
 7819: }
 7820: 
 7821: sub new_selfenroll_dom_row {
 7822:     my ($newdom,$num) = @_;
 7823:     my $domdesc = &Apache::lonnet::domain($newdom);
 7824:     my $output;
 7825:     if ($domdesc ne '') {
 7826:         $output .= &Apache::loncommon::start_data_table_row()
 7827:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 7828:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 7829:                    .'" value="'.$newdom.'" /></span><br />'
 7830:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 7831:                    .'name="selfenroll_activate" value="'.$num.'" '
 7832:                    .'onchange="javascript:update_types('
 7833:                    ."'selfenroll_activate','$num'".');" />'
 7834:                    .&mt('Activate').'</label></span></td>';
 7835:         my @currinsttypes;
 7836:         $output .= '<td>'.&mt('User types:').'<br />'
 7837:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 7838:                    .&Apache::loncommon::end_data_table_row();
 7839:     }
 7840:     return $output;
 7841: }
 7842: 
 7843: sub selfenroll_inst_types {
 7844:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 7845:     my $output;
 7846:     my $numinrow = 4;
 7847:     my $count = 0;
 7848:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 7849:     my $othervalue = 'any';
 7850:     my $disabled;
 7851:     if ($readonly) {
 7852:         $disabled = ' disabled="disabled"';
 7853:     }
 7854:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7855:         if (keys(%{$usertypes}) > 0) {
 7856:             $othervalue = 'other';
 7857:         }
 7858:         $output .= '<table><tr>';
 7859:         foreach my $type (@{$types}) {
 7860:             if (($count > 0) && ($count%$numinrow == 0)) {
 7861:                 $output .= '</tr><tr>';
 7862:             }
 7863:             if (defined($usertypes->{$type})) {
 7864:                 my $esc_type = &escape($type);
 7865:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 7866:                            $esc_type.'" ';
 7867:                 if (ref($currinsttypes) eq 'ARRAY') {
 7868:                     if (@{$currinsttypes} > 0) {
 7869:                         if (grep(/^any$/,@{$currinsttypes})) {
 7870:                             $output .= 'checked="checked"';
 7871:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 7872:                             $output .= 'checked="checked"';
 7873:                         }
 7874:                     } else {
 7875:                         $output .= 'checked="checked"';
 7876:                     }
 7877:                 }
 7878:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 7879:             }
 7880:             $count ++;
 7881:         }
 7882:         if (($count > 0) && ($count%$numinrow == 0)) {
 7883:             $output .= '</tr><tr>';
 7884:         }
 7885:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 7886:         if (ref($currinsttypes) eq 'ARRAY') {
 7887:             if (@{$currinsttypes} > 0) {
 7888:                 if (grep(/^any$/,@{$currinsttypes})) { 
 7889:                     $output .= ' checked="checked"';
 7890:                 } elsif ($othervalue eq 'other') {
 7891:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 7892:                         $output .= ' checked="checked"';
 7893:                     }
 7894:                 }
 7895:             } else {
 7896:                 $output .= ' checked="checked"';
 7897:             }
 7898:         } else {
 7899:             $output .= ' checked="checked"';
 7900:         }
 7901:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 7902:     }
 7903:     return $output;
 7904: }
 7905: 
 7906: sub selfenroll_date_forms {
 7907:     my ($startform,$endform) = @_;
 7908:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 7909:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 7910:                                                     'LC_oddrow_value')."\n".
 7911:                   $startform."\n".
 7912:                   &Apache::lonhtmlcommon::row_closure(1).
 7913:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 7914:                                                    'LC_oddrow_value')."\n".
 7915:                   $endform."\n".
 7916:                   &Apache::lonhtmlcommon::row_closure(1).
 7917:                   &Apache::lonhtmlcommon::end_pick_box();
 7918:     return $output;
 7919: }
 7920: 
 7921: sub print_userchangelogs_display {
 7922:     my ($r,$context,$permission,$brcrum) = @_;
 7923:     my $formname = 'rolelog';
 7924:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 7925:     if ($context eq 'domain') {
 7926:         $domain = $env{'request.role.domain'};
 7927:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 7928:     } else {
 7929:         if ($context eq 'course') { 
 7930:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7931:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 7932:             $crstype = &Apache::loncommon::course_type();
 7933:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 7934:             my %saveable_parameters = ('show' => 'scalar',);
 7935:             &Apache::loncommon::store_course_settings('roles_log',
 7936:                                                       \%saveable_parameters);
 7937:             &Apache::loncommon::restore_course_settings('roles_log',
 7938:                                                         \%saveable_parameters);
 7939:         } elsif ($context eq 'author') {
 7940:             $domain = $env{'user.domain'};
 7941:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 7942:                 $username = $env{'user.name'};
 7943:             } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 7944:                 ($domain,$username) = ($1,$2);
 7945:             } else {
 7946:                 undef($domain);
 7947:             }
 7948:         }
 7949:         if ($domain ne '' && $username ne '') { 
 7950:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 7951:         }
 7952:     }
 7953:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 7954: 
 7955:     my $helpitem;
 7956:     if ($context eq 'course') {
 7957:         $helpitem = 'Course_User_Logs';
 7958:     } elsif ($context eq 'domain') {
 7959:         $helpitem = 'Domain_Role_Logs';
 7960:     } elsif ($context eq 'author') {
 7961:         $helpitem = 'Author_User_Logs';
 7962:     }
 7963:     push (@{$brcrum},
 7964:              {href => '/adm/createuser?action=changelogs',
 7965:               text => 'User Management Logs',
 7966:               help => $helpitem});
 7967:     my $bread_crumbs_component = 'User Changes';
 7968:     my $args = { bread_crumbs           => $brcrum,
 7969:                  bread_crumbs_component => $bread_crumbs_component};
 7970: 
 7971:     # Create navigation javascript
 7972:     my $jsnav = &userlogdisplay_js($formname);
 7973: 
 7974:     my $jscript = (<<ENDSCRIPT);
 7975: <script type="text/javascript">
 7976: // <![CDATA[
 7977: $jsnav
 7978: // ]]>
 7979: </script>
 7980: ENDSCRIPT
 7981: 
 7982:     # print page header
 7983:     $r->print(&header($jscript,$args));
 7984: 
 7985:     # set defaults
 7986:     my $now = time();
 7987:     my $defstart = $now - (7*24*3600); #7 days ago 
 7988:     my %defaults = (
 7989:                      page               => '1',
 7990:                      show               => '10',
 7991:                      role               => 'any',
 7992:                      chgcontext         => 'any',
 7993:                      rolelog_start_date => $defstart,
 7994:                      rolelog_end_date   => $now,
 7995:                      approvals          => 'any',
 7996:                    );
 7997:     my $more_records = 0;
 7998: 
 7999:     # set current
 8000:     my %curr;
 8001:     foreach my $item ('show','page','role','chgcontext','approvals') {
 8002:         $curr{$item} = $env{'form.'.$item};
 8003:     }
 8004:     my ($startdate,$enddate) = 
 8005:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 8006:     $curr{'rolelog_start_date'} = $startdate;
 8007:     $curr{'rolelog_end_date'} = $enddate;
 8008:     foreach my $key (keys(%defaults)) {
 8009:         if ($curr{$key} eq '') {
 8010:             $curr{$key} = $defaults{$key};
 8011:         }
 8012:     }
 8013:     my (%whodunit,%changed,$version);
 8014:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 8015:     my ($minshown,$maxshown);
 8016:     $minshown = 1;
 8017:     my $count = 0;
 8018:     if ($curr{'show'} =~ /\D/) {
 8019:         $curr{'page'} = 1;
 8020:     } else {
 8021:         $maxshown = $curr{'page'} * $curr{'show'};
 8022:         if ($curr{'page'} > 1) {
 8023:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8024:         }
 8025:     }
 8026: 
 8027:     # Form Header
 8028:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8029:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 8030:                                    $version,$crstype));
 8031: 
 8032:     my $showntableheader = 0;
 8033: 
 8034:     # Table Header
 8035:     my $tableheader = 
 8036:         &Apache::loncommon::start_data_table_header_row()
 8037:        .'<th>&nbsp;</th>'
 8038:        .'<th>'.&mt('When').'</th>'
 8039:        .'<th>'.&mt('Who made the change').'</th>'
 8040:        .'<th>'.&mt('Changed User').'</th>'
 8041:        .'<th>'.&mt('Role').'</th>';
 8042: 
 8043:     if ($context eq 'course') {
 8044:         $tableheader .= '<th>'.&mt('Section').'</th>';
 8045:     }
 8046:     $tableheader .=
 8047:         '<th>'.&mt('Context').'</th>'
 8048:        .'<th>'.&mt('Start').'</th>'
 8049:        .'<th>'.&mt('End').'</th>'
 8050:        .&Apache::loncommon::end_data_table_header_row();
 8051: 
 8052:     # Display user change log data
 8053:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 8054:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 8055:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 8056:         if ($curr{'show'} !~ /\D/) {
 8057:             if ($count >= $curr{'page'} * $curr{'show'}) {
 8058:                 $more_records = 1;
 8059:                 last;
 8060:             }
 8061:         }
 8062:         if ($curr{'role'} ne 'any') {
 8063:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 8064:         }
 8065:         if ($curr{'chgcontext'} ne 'any') {
 8066:             if ($curr{'chgcontext'} eq 'selfenroll') {
 8067:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 8068:             } else {
 8069:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 8070:             }
 8071:         }
 8072:         if (($context eq 'course') && ($viewablesec ne '')) {
 8073:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 8074:         }
 8075:         if ($curr{'approvals'} eq 'none') {
 8076:             next if ($roleslog{$id}{'logentry'}{'approval'});
 8077:         } elsif ($curr{'approvals'} ne 'any') { 
 8078:             next if ($roleslog{$id}{'logentry'}{'approval'} ne $curr{'approvals'});
 8079:         }
 8080:         $count ++;
 8081:         next if ($count < $minshown);
 8082:         unless ($showntableheader) {
 8083:             $r->print(&Apache::loncommon::start_data_table()
 8084:                      .$tableheader);
 8085:             $r->rflush();
 8086:             $showntableheader = 1;
 8087:         }
 8088:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 8089:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 8090:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 8091:         }
 8092:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 8093:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 8094:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 8095:         }
 8096:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 8097:         if ($sec eq '') {
 8098:             $sec = &mt('None');
 8099:         }
 8100:         my ($rolestart,$roleend);
 8101:         if ($roleslog{$id}{'delflag'}) {
 8102:             $rolestart = &mt('deleted');
 8103:             $roleend = &mt('deleted');
 8104:         } else {
 8105:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 8106:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 8107:             if ($rolestart eq '' || $rolestart == 0) {
 8108:                 $rolestart = &mt('No start date'); 
 8109:             } else {
 8110:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 8111:             }
 8112:             if ($roleend eq '' || $roleend == 0) { 
 8113:                 $roleend = &mt('No end date');
 8114:             } else {
 8115:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 8116:             }
 8117:         }
 8118:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 8119:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 8120:             $chgcontext = 'selfenroll';
 8121:         }
 8122:         my %lt = &rolechg_contexts($context,$crstype);
 8123:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 8124:             $chgcontext = $lt{$chgcontext};
 8125:         }
 8126:         my ($showreqby,%reqby);
 8127:         if (($roleslog{$id}{'logentry'}{'approval'}) &&
 8128:             ($roleslog{$id}{'logentry'}{'requester'})) {
 8129:             if ($reqby{$roleslog{$id}{'logentry'}{'requester'}} eq '') {
 8130:                 my ($requname,$requdom) = split(/:/,$roleslog{$id}{'logentry'}{'requester'});
 8131:                 $reqby{$roleslog{$id}{'logentry'}{'requester'}} =
 8132:                     &Apache::loncommon::plainname($requname,$requdom);
 8133:             }
 8134:             $showreqby = &mt('Requester').': <span class="LC_nobreak">'.$reqby{$roleslog{$id}{'logentry'}{'requester'}}.'</span><br />';
 8135:             if ($roleslog{$id}{'logentry'}{'approval'} eq 'domain') {
 8136:                 $showreqby .= &mt('Adjudicator').': <span class="LC_nobreak">'.
 8137:                               $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.
 8138:                               '</span>';
 8139:             } else {
 8140:                 $showreqby .= '<span class="LC_nobreak">'.&mt('User approved').'</span>';
 8141:             }
 8142:         } else {
 8143:             $showreqby = $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}};
 8144:         }
 8145:         $r->print(
 8146:             &Apache::loncommon::start_data_table_row()
 8147:            .'<td>'.$count.'</td>'
 8148:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 8149:            .'<td>'.$showreqby.'</td>'
 8150:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 8151:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 8152:         if ($context eq 'course') { 
 8153:             $r->print('<td>'.$sec.'</td>');
 8154:         }
 8155:         $r->print(
 8156:             '<td>'.$chgcontext.'</td>'
 8157:            .'<td>'.$rolestart.'</td>'
 8158:            .'<td>'.$roleend.'</td>'
 8159:            .&Apache::loncommon::end_data_table_row()."\n");
 8160:     }
 8161: 
 8162:     if ($showntableheader) { # Table footer, if content displayed above
 8163:         $r->print(&Apache::loncommon::end_data_table().
 8164:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8165:     } else { # No content displayed above
 8166:         $r->print('<p class="LC_info">'
 8167:                  .&mt('There are no records to display.')
 8168:                  .'</p>'
 8169:         );
 8170:     }
 8171: 
 8172:     # Form Footer
 8173:     $r->print( 
 8174:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8175:        .'<input type="hidden" name="action" value="changelogs" />'
 8176:        .'</form>');
 8177:     return;
 8178: }
 8179: 
 8180: sub print_useraccesslogs_display {
 8181:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 8182:     my $formname = 'accesslog';
 8183:     my $form = 'document.accesslog';
 8184: 
 8185: # set breadcrumbs
 8186:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 8187:     my $prevphasestr;
 8188:     if ($env{'form.popup'}) {
 8189:         $brcrum = [];
 8190:     } else {
 8191:         push (@{$brcrum},
 8192:             {href => "javascript:backPage($form)",
 8193:              text => $breadcrumb_text{'search'}});
 8194:         my @prevphases;
 8195:         if ($env{'form.prevphases'}) {
 8196:             @prevphases = split(/,/,$env{'form.prevphases'});
 8197:             $prevphasestr = $env{'form.prevphases'};
 8198:         }
 8199:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 8200:             push(@{$brcrum},
 8201:                   {href => "javascript:backPage($form,'get_user_info','select')",
 8202:                    text => $breadcrumb_text{'userpicked'}});
 8203:             if ($env{'form.phase'} eq 'userpicked') {
 8204:                 $prevphasestr = 'userpicked';
 8205:             }
 8206:         }
 8207:     }
 8208:     push(@{$brcrum},
 8209:              {href => '/adm/createuser?action=accesslogs',
 8210:               text => 'User access logs',
 8211:               help => 'Domain_User_Access_Logs'});
 8212:     my $bread_crumbs_component = 'User Access Logs';
 8213:     my $args = { bread_crumbs           => $brcrum,
 8214:                  bread_crumbs_component => 'User Management'};
 8215:     if ($env{'form.popup'}) {
 8216:         $args->{'no_nav_bar'} = 1;
 8217:         $args->{'bread_crumbs_nomenu'} = 1;
 8218:     }
 8219: 
 8220: # set javascript
 8221:     my ($jsback,$elements) = &crumb_utilities();
 8222:     my $jsnav = &userlogdisplay_js($formname);
 8223: 
 8224:     my $jscript = (<<ENDSCRIPT);
 8225: <script type="text/javascript">
 8226: // <![CDATA[
 8227: 
 8228: $jsback
 8229: $jsnav
 8230: 
 8231: // ]]>
 8232: </script>
 8233: 
 8234: ENDSCRIPT
 8235: 
 8236: # print page header
 8237:     $r->print(&header($jscript,$args));
 8238: 
 8239: # early out unless log data can be displayed.
 8240:     unless ($permission->{'activity'}) {
 8241:         $r->print('<p class="LC_warning">'
 8242:                  .&mt('You do not have rights to display user access logs.')
 8243:                  .'</p>');
 8244:         if ($env{'form.popup'}) {
 8245:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8246:         } else {
 8247:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8248:         }
 8249:         return;
 8250:     }
 8251: 
 8252:     unless ($udom eq $env{'request.role.domain'}) {
 8253:         $r->print('<p class="LC_warning">'
 8254:                  .&mt("User's domain must match role's domain")
 8255:                  .'</p>'
 8256:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8257:         return;
 8258:     }
 8259: 
 8260:     if (($uname eq '') || ($udom eq '')) {
 8261:         $r->print('<p class="LC_warning">'
 8262:                  .&mt('Invalid username or domain')
 8263:                  .'</p>'
 8264:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8265:         return;
 8266:     }
 8267: 
 8268:     if (&Apache::lonnet::privileged($uname,$udom,
 8269:                                     [$env{'request.role.domain'}],['dc','su'])) {
 8270:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 8271:                                             [$env{'request.role.domain'}],['dc','su'])) {
 8272:             $r->print('<p class="LC_warning">'
 8273:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 8274:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 8275:                                                          $uname,$udom))
 8276:                  .'</p>');
 8277:             if ($env{'form.popup'}) {
 8278:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8279:             } else {
 8280:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8281:             }
 8282:             return;
 8283:         }
 8284:     }
 8285: 
 8286: # set defaults
 8287:     my $now = time();
 8288:     my $defstart = $now - (7*24*3600);
 8289:     my %defaults = (
 8290:                      page                 => '1',
 8291:                      show                 => '10',
 8292:                      activity             => 'any',
 8293:                      accesslog_start_date => $defstart,
 8294:                      accesslog_end_date   => $now,
 8295:                    );
 8296:     my $more_records = 0;
 8297: 
 8298: # set current
 8299:     my %curr;
 8300:     foreach my $item ('show','page','activity') {
 8301:         $curr{$item} = $env{'form.'.$item};
 8302:     }
 8303:     my ($startdate,$enddate) =
 8304:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 8305:     $curr{'accesslog_start_date'} = $startdate;
 8306:     $curr{'accesslog_end_date'} = $enddate;
 8307:     foreach my $key (keys(%defaults)) {
 8308:         if ($curr{$key} eq '') {
 8309:             $curr{$key} = $defaults{$key};
 8310:         }
 8311:     }
 8312:     my ($minshown,$maxshown);
 8313:     $minshown = 1;
 8314:     my $count = 0;
 8315:     if ($curr{'show'} =~ /\D/) {
 8316:         $curr{'page'} = 1;
 8317:     } else {
 8318:         $maxshown = $curr{'page'} * $curr{'show'};
 8319:         if ($curr{'page'} > 1) {
 8320:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8321:         }
 8322:     }
 8323: 
 8324: # form header
 8325:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8326:               &activity_display_filter($formname,\%curr));
 8327: 
 8328:     my $showntableheader = 0;
 8329:     my ($nav_script,$nav_links);
 8330: 
 8331: # table header
 8332:     my $heading = '<h3>'.
 8333:         &mt('User access logs for: [_1]',
 8334:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 8335:     my $tableheader = $heading
 8336:        .&Apache::loncommon::start_data_table_header_row()
 8337:        .'<th>&nbsp;</th>'
 8338:        .'<th>'.&mt('When').'</th>'
 8339:        .'<th>'.&mt('HostID').'</th>'
 8340:        .'<th>'.&mt('Event').'</th>'
 8341:        .'<th>'.&mt('Other data').'</th>'
 8342:        .&Apache::loncommon::end_data_table_header_row();
 8343: 
 8344:     my %filters=(
 8345:         start  => $curr{'accesslog_start_date'},
 8346:         end    => $curr{'accesslog_end_date'},
 8347:         action => $curr{'activity'},
 8348:     );
 8349: 
 8350:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 8351:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8352:         my (%courses,%missing);
 8353:         my @results = split(/\&/,$reply);
 8354:         foreach my $item (reverse(@results)) {
 8355:             my ($timestamp,$host,$event) = split(/:/,$item);
 8356:             next unless ($event =~ /^(Log|Role)/);
 8357:             if ($curr{'show'} !~ /\D/) {
 8358:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 8359:                     $more_records = 1;
 8360:                     last;
 8361:                 }
 8362:             }
 8363:             $count ++;
 8364:             next if ($count < $minshown);
 8365:             unless ($showntableheader) {
 8366:                 $r->print($nav_script
 8367:                          .&Apache::loncommon::start_data_table()
 8368:                          .$tableheader);
 8369:                 $r->rflush();
 8370:                 $showntableheader = 1;
 8371:             }
 8372:             my ($shown,$extra);
 8373:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 8374:             if ($event eq 'Role') {
 8375:                 my ($rolecode,$extent) = split(/\./,$data,2);
 8376:                 next if ($extent eq '');
 8377:                 my ($crstype,$desc,$info);
 8378:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 8379:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 8380:                     my $cid = $cdom.'_'.$cnum;
 8381:                     if (exists($courses{$cid})) {
 8382:                         $crstype = $courses{$cid}{'type'};
 8383:                         $desc = $courses{$cid}{'description'};
 8384:                     } elsif ($missing{$cid}) {
 8385:                         $crstype = 'Course';
 8386:                         $desc = 'Course/Community';
 8387:                     } else {
 8388:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8389:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 8390:                             $courses{$cid} = $crsinfo{$cid};
 8391:                             $crstype = $crsinfo{$cid}{'type'};
 8392:                             $desc = $crsinfo{$cid}{'description'};
 8393:                         } else {
 8394:                             $missing{$cid} = 1;
 8395:                         }
 8396:                     }
 8397:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 8398:                     if ($sec ne '') {
 8399:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 8400:                     }
 8401:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 8402:                     my ($dom,$name) = ($1,$2);
 8403:                     if ($rolecode eq 'au') {
 8404:                         $extra = '';
 8405:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 8406:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 8407:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 8408:                         $extra = &mt('Domain: [_1]',$dom);
 8409:                     }
 8410:                 }
 8411:                 my $rolename;
 8412:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 8413:                     my $role = $3;
 8414:                     my $owner = "($2:$1)";
 8415:                     if ($2 eq $1.'-domainconfig') {
 8416:                         $owner = '(ad hoc)';
 8417:                     }
 8418:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 8419:                 } else {
 8420:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 8421:                 }
 8422:                 $shown = &mt('Role selection: [_1]',$rolename);
 8423:             } else {
 8424:                 $shown = &mt($event);
 8425:                 if ($data =~ /^webdav/) {
 8426:                     my ($path,$clientip) = split(/\s+/,$data,2);
 8427:                     $path =~ s/^webdav//;
 8428:                     if ($clientip ne '') {
 8429:                         $extra = &mt('Client IP address: [_1]',$clientip);
 8430:                     }
 8431:                     if ($path ne '') {
 8432:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 8433:                     }
 8434:                 } elsif ($data ne '') {
 8435:                     $extra = &mt('Client IP address: [_1]',$data);
 8436:                 }
 8437:             }
 8438:             $r->print(
 8439:             &Apache::loncommon::start_data_table_row()
 8440:            .'<td>'.$count.'</td>'
 8441:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 8442:            .'<td>'.$host.'</td>'
 8443:            .'<td>'.$shown.'</td>'
 8444:            .'<td>'.$extra.'</td>'
 8445:            .&Apache::loncommon::end_data_table_row()."\n");
 8446:         }
 8447:     }
 8448: 
 8449:     if ($showntableheader) { # Table footer, if content displayed above
 8450:         $r->print(&Apache::loncommon::end_data_table().
 8451:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8452:     } else { # No content displayed above
 8453:         $r->print($heading.'<p class="LC_info">'
 8454:                  .&mt('There are no records to display.')
 8455:                  .'</p>');
 8456:     }
 8457: 
 8458:     if ($env{'form.popup'} == 1) {
 8459:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 8460:     }
 8461: 
 8462:     # Form Footer
 8463:     $r->print(
 8464:         '<input type="hidden" name="currstate" value="" />'
 8465:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 8466:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 8467:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8468:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 8469:        .'<input type="hidden" name="phase" value="activity" />'
 8470:        .'<input type="hidden" name="action" value="accesslogs" />'
 8471:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 8472:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 8473:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 8474:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 8475:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 8476:        .'</form>');
 8477:     return;
 8478: }
 8479: 
 8480: sub earlyout_accesslog_form {
 8481:     my ($formname,$prevphasestr,$udom) = @_;
 8482:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 8483:    return <<"END";
 8484: <form action="/adm/createuser" method="post" name="$formname">
 8485: <input type="hidden" name="currstate" value="" />
 8486: <input type="hidden" name="prevphases" value="$prevphasestr" />
 8487: <input type="hidden" name="phase" value="activity" />
 8488: <input type="hidden" name="action" value="accesslogs" />
 8489: <input type="hidden" name="srchdomain" value="$udom" />
 8490: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 8491: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 8492: <input type="hidden" name="srchterm" value="$srchterm" />
 8493: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 8494: </form>
 8495: END
 8496: }
 8497: 
 8498: sub activity_display_filter {
 8499:     my ($formname,$curr) = @_;
 8500:     my $nolink = 1;
 8501:     my $output = '<table><tr><td valign="top">'.
 8502:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 8503:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8504:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8505:                  '</td><td>&nbsp;&nbsp;</td>';
 8506:     my $startform =
 8507:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 8508:                                             $curr->{'accesslog_start_date'},undef,
 8509:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8510:     my $endform =
 8511:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 8512:                                             $curr->{'accesslog_end_date'},undef,
 8513:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8514:     my %lt = &Apache::lonlocal::texthash (
 8515:                                           activity => 'Activity',
 8516:                                           Role     => 'Role selection',
 8517:                                           log      => 'Log-in or Logout',
 8518:     );
 8519:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 8520:                '<table><tr><td>'.&mt('After:').
 8521:                '</td><td>'.$startform.'</td></tr>'.
 8522:                '<tr><td>'.&mt('Before:').'</td>'.
 8523:                '<td>'.$endform.'</td></tr></table>'.
 8524:                '</td>'.
 8525:                '<td>&nbsp;&nbsp;</td>'.
 8526:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 8527:                '<select name="activity"><option value="any"';
 8528:     if ($curr->{'activity'} eq 'any') {
 8529:         $output .= ' selected="selected"';
 8530:     }
 8531:     $output .= '>'.&mt('Any').'</option>'."\n";
 8532:     foreach my $activity ('Role','log') {
 8533:         my $selstr = '';
 8534:         if ($activity eq $curr->{'activity'}) {
 8535:             $selstr = ' selected="selected"';
 8536:         }
 8537:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 8538:     }
 8539:     $output .= '</select></td>'.
 8540:                '</tr></table>';
 8541:     # Update Display button
 8542:     $output .= '<p>'
 8543:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8544:               .'</p><hr />';
 8545:     return $output;
 8546: }
 8547: 
 8548: sub userlogdisplay_js {
 8549:     my ($formname) = @_;
 8550:     return <<"ENDSCRIPT";
 8551: 
 8552: function chgPage(caller) {
 8553:     if (caller == 'previous') {
 8554:         document.$formname.page.value --;
 8555:     }
 8556:     if (caller == 'next') {
 8557:         document.$formname.page.value ++;
 8558:     }
 8559:     document.$formname.submit();
 8560:     return;
 8561: }
 8562: ENDSCRIPT
 8563: }
 8564: 
 8565: sub userlogdisplay_navlinks {
 8566:     my ($curr,$more_records) = @_;
 8567:     return unless(ref($curr) eq 'HASH');
 8568:     # Navigation Buttons
 8569:     my $nav_links = '<p>';
 8570:     if (($curr->{'page'} > 1) || ($more_records)) {
 8571:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 8572:             $nav_links .= '<input type="button"'
 8573:                          .' onclick="javascript:chgPage('."'previous'".');"'
 8574:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 8575:                          .'" /> ';
 8576:         }
 8577:         if ($more_records) {
 8578:             $nav_links .= '<input type="button"'
 8579:                          .' onclick="javascript:chgPage('."'next'".');"'
 8580:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 8581:                          .'" />';
 8582:         }
 8583:     }
 8584:     $nav_links .= '</p>';
 8585:     return $nav_links;
 8586: }
 8587: 
 8588: sub role_display_filter {
 8589:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 8590:     my $nolink = 1;
 8591:     my $output = '<table><tr><td valign="top">'.
 8592:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 8593:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8594:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8595:                  '</td><td>&nbsp;&nbsp;</td>';
 8596:     my $startform =
 8597:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 8598:                                             $curr->{'rolelog_start_date'},undef,
 8599:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8600:     my $endform =
 8601:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 8602:                                             $curr->{'rolelog_end_date'},undef,
 8603:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8604:     my %lt = &rolechg_contexts($context,$crstype);
 8605:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 8606:                '<table><tr><td>'.&mt('After:').
 8607:                '</td><td>'.$startform.'</td></tr>'.
 8608:                '<tr><td>'.&mt('Before:').'</td>'.
 8609:                '<td>'.$endform.'</td></tr></table>'.
 8610:                '</td>'.
 8611:                '<td>&nbsp;&nbsp;</td>'.
 8612:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 8613:                '<select name="role"><option value="any"';
 8614:     if ($curr->{'role'} eq 'any') {
 8615:         $output .= ' selected="selected"';
 8616:     }
 8617:     $output .= '>'.&mt('Any').'</option>'."\n";
 8618:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 8619:     foreach my $role (@roles) {
 8620:         my $plrole;
 8621:         if ($role eq 'cr') {
 8622:             $plrole = &mt('Custom Role');
 8623:         } else {
 8624:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8625:         }
 8626:         my $selstr = '';
 8627:         if ($role eq $curr->{'role'}) {
 8628:             $selstr = ' selected="selected"';
 8629:         }
 8630:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 8631:     }
 8632:     $output .= '</select></td>'.
 8633:                '<td>&nbsp;&nbsp;</td>'.
 8634:                '<td valign="top"><b>'.
 8635:                &mt('Context:').'</b><br /><select name="chgcontext">';
 8636:     my @posscontexts;
 8637:     if ($context eq 'course') {
 8638:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype','ltienroll');
 8639:     } elsif ($context eq 'domain') {
 8640:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 8641:     } else {
 8642:         @posscontexts = ('any','author','coauthor','domain');
 8643:     }
 8644:     foreach my $chgtype (@posscontexts) {
 8645:         my $selstr = '';
 8646:         if ($curr->{'chgcontext'} eq $chgtype) {
 8647:             $selstr = ' selected="selected"';
 8648:         }
 8649:         if ($context eq 'course') {
 8650:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 8651:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 8652:             }
 8653:         }
 8654:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 8655:     }
 8656:     my @possapprovals = ('any','none','domain','user');
 8657:     my %apptxt = &approval_types();
 8658:     $output .= '</select></td>'.
 8659:                '<td>&nbsp;&nbsp;</td>'.
 8660:                '<td valign="top"><b>'.
 8661:                &mt('Approvals:').'</b><br /><select name="approvals">';
 8662:     foreach my $approval (@possapprovals) {
 8663:         my $selstr = '';
 8664:         if ($curr->{'approvals'} eq $approval) {
 8665:             $selstr = ' selected="selected"';
 8666:         }    
 8667:         $output .= '<option value="'.$approval.'"'.$selstr.'>'.$apptxt{$approval}.'</option>';
 8668:     }
 8669:     $output .= '</select></td></tr></table>';
 8670: 
 8671:     # Update Display button
 8672:     $output .= '<p>'
 8673:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8674:               .'</p>';
 8675: 
 8676:     # Server version info
 8677:     my $needsrev = '2.11.0';
 8678:     if ($context eq 'course') {
 8679:         $needsrev = '2.7.0';
 8680:     }
 8681:     
 8682:     $output .= '<p class="LC_info">'
 8683:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 8684:                   ,$needsrev);
 8685:     if ($version) {
 8686:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 8687:     }
 8688:     $output .= '</p><hr />';
 8689:     return $output;
 8690: }
 8691: 
 8692: sub rolechg_contexts {
 8693:     my ($context,$crstype) = @_;
 8694:     my %lt;
 8695:     if ($context eq 'course') {
 8696:         %lt = &Apache::lonlocal::texthash (
 8697:                                              any          => 'Any',
 8698:                                              automated    => 'Automated Enrollment',
 8699:                                              chgtype      => 'Enrollment Type/Lock Change',
 8700:                                              updatenow    => 'Roster Update',
 8701:                                              createcourse => 'Course Creation',
 8702:                                              course       => 'User Management in course',
 8703:                                              domain       => 'User Management in domain',
 8704:                                              selfenroll   => 'Self-enrolled',
 8705:                                              requestcourses => 'Course Request',
 8706:                                              ltienroll    => 'Enrollment via LTI',
 8707:                                          );
 8708:         if ($crstype eq 'Community') {
 8709:             $lt{'createcourse'} = &mt('Community Creation');
 8710:             $lt{'course'} = &mt('User Management in community');
 8711:             $lt{'requestcourses'} = &mt('Community Request');
 8712:         }
 8713:     } elsif ($context eq 'domain') {
 8714:         %lt = &Apache::lonlocal::texthash (
 8715:                                              any           => 'Any',
 8716:                                              domain        => 'User Management in domain',
 8717:                                              requestauthor => 'Authoring Request',
 8718:                                              server        => 'Command line script (DC role)',
 8719:                                              domconfig     => 'Self-enrolled',
 8720:                                          );
 8721:     } else {
 8722:         %lt = &Apache::lonlocal::texthash (
 8723:                                              any    => 'Any',
 8724:                                              domain => 'User Management in domain',
 8725:                                              author => 'User Management by author',
 8726:                                              coauthor => 'User Management by coauthor',
 8727:                                          );
 8728:     } 
 8729:     return %lt;
 8730: }
 8731: 
 8732: sub approval_types {
 8733:     return &Apache::lonlocal::texthash (
 8734:                                           any => 'Any',
 8735:                                           none => 'No approval needed',
 8736:                                           user => 'Role recipient approval',
 8737:                                           domain => 'Domain coordinator approval',
 8738:                                        );
 8739: }
 8740: 
 8741: sub print_helpdeskaccess_display {
 8742:     my ($r,$permission,$brcrum) = @_;
 8743:     my $formname = 'helpdeskaccess';
 8744:     my $helpitem = 'Course_Helpdesk_Access';
 8745:     push (@{$brcrum},
 8746:              {href => '/adm/createuser?action=helpdesk',
 8747:               text => 'Helpdesk Access',
 8748:               help => $helpitem});
 8749:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8750:     my $args = { bread_crumbs           => $brcrum,
 8751:                  bread_crumbs_component => $bread_crumbs_component};
 8752: 
 8753:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8754:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8755:     my $confname = $cdom.'-domainconfig';
 8756:     my $crstype = &Apache::loncommon::course_type();
 8757: 
 8758:     my @accesstypes = ('all','dh','da','none');
 8759:     my ($numstatustypes,@jsarray);
 8760:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8761:     if (ref($types) eq 'ARRAY') {
 8762:         if (@{$types} > 0) {
 8763:             $numstatustypes = scalar(@{$types});
 8764:             push(@accesstypes,'status');
 8765:             @jsarray = ('bystatus');
 8766:         }
 8767:     }
 8768:     my %customroles = &get_domain_customroles($cdom,$confname);
 8769:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8770:     if (keys(%domhelpdesk)) {
 8771:        push(@accesstypes,('inc','exc'));
 8772:        push(@jsarray,('notinc','notexc'));
 8773:     }
 8774:     push(@jsarray,'privs');
 8775:     my $hiddenstr = join("','",@jsarray);
 8776:     my $rolestr = join("','",sort(keys(%customroles)));
 8777: 
 8778:     my $jscript;
 8779:     my (%settings,%overridden);
 8780:     if (keys(%customroles)) {
 8781:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8782:                                 $types,\%customroles,\%settings,\%overridden);
 8783:         my %jsfull=();
 8784:         my %jslevels= (
 8785:                      course => {},
 8786:                      domain => {},
 8787:                      system => {},
 8788:                     );
 8789:         my %jslevelscurrent=(
 8790:                            course => {},
 8791:                            domain => {},
 8792:                            system => {},
 8793:                           );
 8794:         my (%privs,%jsprivs);
 8795:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 8796:         foreach my $priv (keys(%jsfull)) {
 8797:             if ($jslevels{'course'}{$priv}) {
 8798:                 $jsprivs{$priv} = 1;
 8799:             }
 8800:         }
 8801:         my (%elements,%stored);
 8802:         foreach my $role (keys(%customroles)) {
 8803:             $elements{$role.'_access'} = 'radio';
 8804:             $elements{$role.'_incrs'} = 'radio';
 8805:             if ($numstatustypes) {
 8806:                 $elements{$role.'_status'} = 'checkbox';
 8807:             }
 8808:             if (keys(%domhelpdesk) > 0) {
 8809:                 $elements{$role.'_staff_inc'} = 'checkbox';
 8810:                 $elements{$role.'_staff_exc'} = 'checkbox';
 8811:             }
 8812:             $elements{$role.'_override'} = 'checkbox';
 8813:             if (ref($settings{$role}) eq 'HASH') {
 8814:                 if ($settings{$role}{'access'} ne '') {
 8815:                     my $curraccess = $settings{$role}{'access'};
 8816:                     $stored{$role.'_access'} = $curraccess;
 8817:                     $stored{$role.'_incrs'} = 1;
 8818:                     if ($curraccess eq 'status') {
 8819:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 8820:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 8821:                         }
 8822:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8823:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 8824:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 8825:                         }
 8826:                     }
 8827:                 } else {
 8828:                     $stored{$role.'_incrs'} = 0;
 8829:                 }
 8830:                 $stored{$role.'_override'} = [];
 8831:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 8832:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 8833:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 8834:                             push(@{$stored{$role.'_override'}},$priv);
 8835:                         }
 8836:                     }
 8837:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 8838:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 8839:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 8840:                                 push(@{$stored{$role.'_override'}},$priv);
 8841:                             }
 8842:                         }
 8843:                     }
 8844:                 }
 8845:             } else {
 8846:                 $stored{$role.'_incrs'} = 0;
 8847:             }
 8848:         }
 8849:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 8850:     }
 8851: 
 8852:     my $js = <<"ENDJS";
 8853: <script type="text/javascript">
 8854: // <![CDATA[
 8855: $jscript;
 8856: 
 8857: function switchRoleTab(caller,role) {
 8858:     if (document.getElementById(role+'_maindiv')) {
 8859:         if (caller.id != 'LC_current_minitab') {
 8860:             if (document.getElementById('LC_current_minitab')) {
 8861:                 document.getElementById('LC_current_minitab').id=null;
 8862:             }
 8863:             var roledivs = Array('$rolestr');
 8864:             if (roledivs.length > 0) {
 8865:                 for (var i=0; i<roledivs.length; i++) {
 8866:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 8867:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 8868:                     }
 8869:                 }
 8870:             }
 8871:             caller.id = 'LC_current_minitab';
 8872:             document.getElementById(role+'_maindiv').style.display='block';
 8873:         }
 8874:     }
 8875:     return false;
 8876: }
 8877: 
 8878: function helpdeskAccess(role) {
 8879:     var curraccess = null;
 8880:     if (document.$formname.elements[role+'_access'].length) {
 8881:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 8882:             if (document.$formname.elements[role+'_access'][i].checked) {
 8883:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 8884:             }
 8885:         }
 8886:     }
 8887:     var shown = Array();
 8888:     var hidden = Array();
 8889:     if (curraccess == 'none') {
 8890:         hidden = Array ('$hiddenstr');
 8891:     } else {
 8892:         if (curraccess == 'status') {
 8893:             shown = Array ('bystatus','privs');
 8894:             hidden = Array ('notinc','notexc');
 8895:         } else {
 8896:             if (curraccess == 'exc') {
 8897:                 shown = Array ('notexc','privs');
 8898:                 hidden = Array ('notinc','bystatus');
 8899:             }
 8900:             if (curraccess == 'inc') {
 8901:                 shown = Array ('notinc','privs');
 8902:                 hidden = Array ('notexc','bystatus');
 8903:             }
 8904:             if (curraccess == 'all') {
 8905:                 shown = Array ('privs');
 8906:                 hidden = Array ('notinc','notexc','bystatus');
 8907:             }
 8908:         }
 8909:     }
 8910:     if (hidden.length > 0) {
 8911:         for (var i=0; i<hidden.length; i++) {
 8912:             if (document.getElementById(role+'_'+hidden[i])) {
 8913:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 8914:             }
 8915:         }
 8916:     }
 8917:     if (shown.length > 0) {
 8918:         for (var i=0; i<shown.length; i++) {
 8919:             if (document.getElementById(role+'_'+shown[i])) {
 8920:                 if (shown[i] == 'privs') {
 8921:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 8922:                 } else {
 8923:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 8924:                 }
 8925:             }
 8926:         }
 8927:     }
 8928:     return;
 8929: }
 8930: 
 8931: function toggleAccess(role) {
 8932:     if ((document.getElementById(role+'_setincrs')) &&
 8933:         (document.getElementById(role+'_setindom'))) {
 8934:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 8935:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 8936:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 8937:                     document.getElementById(role+'_setindom').style.display = 'none';
 8938:                     document.getElementById(role+'_setincrs').style.display = 'block';
 8939:                 } else {
 8940:                     document.getElementById(role+'_setincrs').style.display = 'none';
 8941:                     document.getElementById(role+'_setindom').style.display = 'block';
 8942:                 }
 8943:                 break;
 8944:             }
 8945:         }
 8946:     }
 8947:     return;
 8948: }
 8949: 
 8950: // ]]>
 8951: </script>
 8952: ENDJS
 8953: 
 8954:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 8955: 
 8956:     # print page header
 8957:     $r->print(&header($js,$args));
 8958:     # print form header
 8959:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 8960: 
 8961:     if (keys(%customroles)) {
 8962:         my %lt = &Apache::lonlocal::texthash(
 8963:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 8964:                     'rou'    => 'Role usage',
 8965:                     'whi'    => 'Which helpdesk personnel may use this role?',
 8966:                     'udd'    => 'Use domain default',
 8967:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 8968:                     'dh'     => 'All with domain helpdesk role',
 8969:                     'da'     => 'All with domain helpdesk assistant role',
 8970:                     'none'   => 'None',
 8971:                     'status' => 'Determined based on institutional status',
 8972:                     'inc'    => 'Include all, but exclude specific personnel',
 8973:                     'exc'    => 'Exclude all, but include specific personnel',
 8974:                     'hel'    => 'Helpdesk',
 8975:                     'rpr'    => 'Role privileges',
 8976:                  );
 8977:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 8978:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8979:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 8980:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8981:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8982:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8983:             }
 8984:         }
 8985:         my $count = 0;
 8986:         foreach my $role (sort(keys(%customroles))) {
 8987:             my ($order,$desc,$access_in_dom);
 8988:             if (ref($domcurrent{$role}) eq 'HASH') {
 8989:                 $order = $domcurrent{$role}{'order'};
 8990:                 $desc = $domcurrent{$role}{'desc'};
 8991:                 $access_in_dom = $domcurrent{$role}{'access'};
 8992:             }
 8993:             if ($order eq '') {
 8994:                 $order = $count;
 8995:             }
 8996:             $ordered{$order} = $role;
 8997:             if ($desc ne '') {
 8998:                 $description{$role} = $desc;
 8999:             } else {
 9000:                 $description{$role}= $role;
 9001:             }
 9002:             $count++;
 9003:         }
 9004:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9005:         my @roles_by_num = ();
 9006:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9007:             push(@roles_by_num,$ordered{$item});
 9008:         }
 9009:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 9010:         if ($permission->{'owner'}) {
 9011:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 9012:             $r->print('<input type="hidden" name="state" value="process" />'.
 9013:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 9014:         } else {
 9015:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 9016:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 9017:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 9018:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 9019:             }
 9020:             $disabled = ' disabled="disabled"';
 9021:         }
 9022:         $r->print('</p>');
 9023: 
 9024:         $r->print('<div id="LC_minitab_header"><ul>');
 9025:         my $count = 0;
 9026:         my %visibility;
 9027:         foreach my $role (@roles_by_num) {
 9028:             my $id;
 9029:             if ($count == 0) {
 9030:                 $id=' id="LC_current_minitab"';
 9031:                 $visibility{$role} = ' style="display:block"';
 9032:             } else {
 9033:                 $visibility{$role} = ' style="display:none"';
 9034:             }
 9035:             $count ++;
 9036:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 9037:         }
 9038:         $r->print('</ul></div>');
 9039: 
 9040:         foreach my $role (@roles_by_num) {
 9041:             my %usecheck = (
 9042:                              all => ' checked="checked"',
 9043:                            );
 9044:             my %displaydiv = (
 9045:                                 status => 'none',
 9046:                                 inc    => 'none',
 9047:                                 exc    => 'none',
 9048:                                 priv   => 'block',
 9049:                              );
 9050:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 9051:             if (ref($settings{$role}) eq 'HASH') {
 9052:                 if ($settings{$role}{'access'} ne '') {
 9053:                     $indomvis = ' style="display:none"';
 9054:                     $incrsvis = ' style="display:block"';
 9055:                     $incrscheck = ' checked="checked"';
 9056:                     if ($settings{$role}{'access'} ne 'all') {
 9057:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 9058:                         delete($usecheck{'all'});
 9059:                         if ($settings{$role}{'access'} eq 'status') {
 9060:                             my $access = 'status';
 9061:                             $displaydiv{$access} = 'inline';
 9062:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9063:                                 $selected{$access} = $settings{$role}{$access};
 9064:                             }
 9065:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 9066:                             my $access = $1;
 9067:                             $displaydiv{$access} = 'inline';
 9068:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9069:                                 $selected{$access} = $settings{$role}{$access};
 9070:                             }
 9071:                         } elsif ($settings{$role}{'access'} eq 'none') {
 9072:                             $displaydiv{'priv'} = 'none';
 9073:                         }
 9074:                     }
 9075:                 } else {
 9076:                     $indomcheck = ' checked="checked"';
 9077:                     $indomvis = ' style="display:block"';
 9078:                     $incrsvis = ' style="display:none"';
 9079:                 }
 9080:             } else {
 9081:                 $indomcheck = ' checked="checked"';
 9082:                 $indomvis = ' style="display:block"';
 9083:                 $incrsvis = ' style="display:none"';
 9084:             }
 9085:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 9086:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 9087:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 9088:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9089:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 9090:                       '<span>'.('&nbsp;'x2).
 9091:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9092:                       $lt{'udd'}.'</label><span></p>'.
 9093:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 9094:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 9095:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 9096:             foreach my $access (@accesstypes) {
 9097:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 9098:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 9099:                 if ($access eq 'status') {
 9100:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 9101:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 9102:                                                                         $othertitle,$usertypes,$types,$disabled).
 9103:                               '</div>');
 9104:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 9105:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 9106:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9107:                                                                  \%domhelpdesk,$disabled).
 9108:                               '</div>');
 9109:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 9110:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 9111:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9112:                                                                  \%domhelpdesk,$disabled).
 9113:                               '</div>');
 9114:                 }
 9115:                 $r->print('</p>');
 9116:             }
 9117:             $r->print('</div></fieldset>');
 9118:             my %full=();
 9119:             my %levels= (
 9120:                          course => {},
 9121:                          domain => {},
 9122:                          system => {},
 9123:                         );
 9124:             my %levelscurrent=(
 9125:                                course => {},
 9126:                                domain => {},
 9127:                                system => {},
 9128:                               );
 9129:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9130:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 9131:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 9132:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 9133:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 9134:         }
 9135:         if ($permission->{'owner'}) {
 9136:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 9137:         }
 9138:     } else {
 9139:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 9140:     }
 9141:     # Form Footer
 9142:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 9143:              .'</form>');
 9144:     return;
 9145: }
 9146: 
 9147: sub print_queued_roles {
 9148:     my ($r,$context,$permission,$brcrum) = @_;
 9149:     push (@{$brcrum},
 9150:              {href => '/adm/createuser?action=rolerequests',
 9151:               text => 'Role Requests (other domains)',
 9152:               help => ''});
 9153:     my $bread_crumbs_component = 'Role Requests';
 9154:     my $args = { bread_crumbs           => $brcrum,
 9155:                  bread_crumbs_component => $bread_crumbs_component};
 9156:     # print page header
 9157:     $r->print(&header('',$args));
 9158:     my ($dom,$cnum);
 9159:     $dom = $env{'request.role.domain'};
 9160:     if ($context eq 'course') {
 9161:         if ($env{'request.course.id'}) {
 9162:             if (&Apache::loncommon::course_type() eq 'Community') {
 9163:                 $context = 'community';
 9164:             }
 9165:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9166:         }
 9167:     } elsif ($context eq 'author') {
 9168:         $cnum = $env{'user.name'};
 9169:     }
 9170:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomqueue',$dom,$cnum,$context));
 9171:     return;
 9172: }
 9173: 
 9174: sub print_pendingroles {
 9175:     my ($r,$context,$permission,$brcrum) = @_;
 9176:     push (@{$brcrum},
 9177:              {href => '/adm/createuser?action=queuedroles',
 9178:               text => 'Queued Role Assignments (users in this domain)',
 9179:               help => ''});
 9180:     my $bread_crumbs_component = 'Queued Role Assignments';
 9181:     my $args = { bread_crumbs           => $brcrum,
 9182:                  bread_crumbs_component => $bread_crumbs_component};
 9183:     # print page header
 9184:     $r->print(&header('',$args));
 9185:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomaction',$env{'request.role.domain'},'','domain'));
 9186:     return;
 9187: }
 9188: 
 9189: sub process_pendingroles {
 9190:     my ($r,$context,$permission,$brcrum) = @_;
 9191:     push (@{$brcrum},
 9192:              {href => '/adm/createuser?action=queuedroles',
 9193:               text => 'Queued Role Assignments (users in this domain)',
 9194:               help => ''},
 9195:              {href => '/adm/createuser?action=processrolereq',
 9196:               text => 'Process Queue',
 9197:               help => ''});
 9198:     my $bread_crumbs_component = 'Queued Role Assignments';
 9199:     my $args = { bread_crumbs           => $brcrum,
 9200:                  bread_crumbs_component => $bread_crumbs_component};
 9201:     # print page header
 9202:     $r->print(&header('',$args));
 9203:     $r->print(&Apache::loncoursequeueadmin::update_request_queue('othdombydc',
 9204:                                                                  $env{'request.role.domain'}));
 9205:     return;
 9206: }
 9207: 
 9208: sub domain_adhoc_access {
 9209:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 9210:     my %domusage;
 9211:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 9212:     foreach my $role (keys(%{$roles})) {
 9213:         if (ref($domcurrent->{$role}) eq 'HASH') {
 9214:             my $access = $domcurrent->{$role}{'access'};
 9215:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 9216:                 $access = 'all';
 9217:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 9218:                                                                                           &Apache::lonnet::plaintext('da'));
 9219:             } elsif ($access eq 'status') {
 9220:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 9221:                     my @shown;
 9222:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 9223:                         unless ($type eq 'default') {
 9224:                             if ($usertypes->{$type}) {
 9225:                                 push(@shown,$usertypes->{$type});
 9226:                             }
 9227:                         }
 9228:                     }
 9229:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 9230:                         push(@shown,$othertitle);
 9231:                     }
 9232:                     if (@shown) {
 9233:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 9234:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 9235:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 9236:                     } else {
 9237:                         $domusage{$role} = &mt('No one in the domain');
 9238:                     }
 9239:                 }
 9240:             } elsif ($access eq 'inc') {
 9241:                 my @dominc = ();
 9242:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 9243:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 9244:                         my ($uname,$udom) = split(/:/,$user);
 9245:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9246:                     }
 9247:                     my $showninc = join(', ',@dominc);
 9248:                     if ($showninc ne '') {
 9249:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 9250:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 9251:                     } else {
 9252:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9253:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9254:                     }
 9255:                 }
 9256:             } elsif ($access eq 'exc') {
 9257:                 my @domexc = ();
 9258:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 9259:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 9260:                         my ($uname,$udom) = split(/:/,$user);
 9261:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9262:                     }
 9263:                 }
 9264:                 my $shownexc = join(', ',@domexc);
 9265:                 if ($shownexc ne '') {
 9266:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 9267:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 9268:                 } else {
 9269:                     $domusage{$role} = &mt('No one in the domain');
 9270:                 }
 9271:             } elsif ($access eq 'none') {
 9272:                 $domusage{$role} = &mt('No one in the domain');
 9273:             } elsif ($access eq 'dh') {
 9274:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 9275:             } elsif ($access eq 'da') {
 9276:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 9277:             } elsif ($access eq 'all') {
 9278:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9279:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9280:             }
 9281:         } else {
 9282:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9283:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9284:         }
 9285:     }
 9286:     return %domusage;
 9287: }
 9288: 
 9289: sub get_domain_customroles {
 9290:     my ($cdom,$confname) = @_;
 9291:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 9292:     my %customroles;
 9293:     foreach my $key (keys(%existing)) {
 9294:         if ($key=~/^rolesdef\_(\w+)$/) {
 9295:             my $rolename = $1;
 9296:             my %privs;
 9297:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 9298:             $customroles{$rolename} = \%privs;
 9299:         }
 9300:     }
 9301:     return %customroles;
 9302: }
 9303: 
 9304: sub role_priv_table {
 9305:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 9306:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 9307:                    (ref($levelscurrent) eq 'HASH'));
 9308:     my %lt=&Apache::lonlocal::texthash (
 9309:                     'crl'  => 'Course Level Privilege',
 9310:                     'def'  => 'Domain Defaults',
 9311:                     'ove'  => 'Override in Course',
 9312:                     'ine'  => 'In effect',
 9313:                     'dis'  => 'Disabled',
 9314:                     'ena'  => 'Enabled',
 9315:                    );
 9316:     if ($crstype eq 'Community') {
 9317:         $lt{'ove'} = 'Override in Community',
 9318:     }
 9319:     my @status = ('Disabled','Enabled');
 9320:     my (%on,%off);
 9321:     if (ref($overridden) eq 'HASH') {
 9322:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 9323:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 9324:         }
 9325:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 9326:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 9327:         }
 9328:     }
 9329:     my $output=&Apache::loncommon::start_data_table().
 9330:                &Apache::loncommon::start_data_table_header_row().
 9331:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 9332:                '</th><th>'.$lt{'ine'}.'</th>'.
 9333:                &Apache::loncommon::end_data_table_header_row();
 9334:     foreach my $priv (sort(keys(%{$full}))) {
 9335:         next unless ($levels->{'course'}{$priv});
 9336:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 9337:         my ($default,$ineffect);
 9338:         if ($levelscurrent->{'course'}{$priv}) {
 9339:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9340:             $ineffect = $default;
 9341:         }
 9342:         my ($customstatus,$checked);
 9343:         $output .= &Apache::loncommon::start_data_table_row().
 9344:                    '<td>'.$privtext.'</td>'.
 9345:                    '<td>'.$default.'</td><td>';
 9346:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 9347:             if ($permission->{'owner'}) {
 9348:                 $checked = ' checked="checked"';
 9349:             }
 9350:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 9351:             $ineffect = $customstatus;
 9352:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 9353:             if ($permission->{'owner'}) {
 9354:                 $checked = ' checked="checked"';
 9355:             }
 9356:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9357:             $ineffect = $customstatus;
 9358:         }
 9359:         if ($permission->{'owner'}) {
 9360:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 9361:         } else {
 9362:             $output .= $customstatus;
 9363:         }
 9364:         $output .= '</td><td>'.$ineffect.'</td>'.
 9365:                    &Apache::loncommon::end_data_table_row();
 9366:     }
 9367:     $output .= &Apache::loncommon::end_data_table();
 9368:     return $output;
 9369: }
 9370: 
 9371: sub get_adhocrole_settings {
 9372:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 9373:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 9374:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 9375:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 9376:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 9377:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 9378:             $settings->{$role}{'access'} = $curraccess;
 9379:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 9380:                 my @status = split(/,/,$rest);
 9381:                 my @currstatus;
 9382:                 foreach my $type (@status) {
 9383:                     if ($type eq 'default') {
 9384:                         push(@currstatus,$type);
 9385:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9386:                         push(@currstatus,$type);
 9387:                     }
 9388:                 }
 9389:                 if (@currstatus) {
 9390:                     $settings->{$role}{$curraccess} = \@currstatus;
 9391:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 9392:                     my @personnel = split(/,/,$rest);
 9393:                     $settings->{$role}{$curraccess} = \@personnel;
 9394:                 }
 9395:             }
 9396:         }
 9397:     }
 9398:     foreach my $role (keys(%{$customroles})) {
 9399:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 9400:             my %currentprivs;
 9401:             if (ref($customroles->{$role}) eq 'HASH') {
 9402:                 if (exists($customroles->{$role}{'course'})) {
 9403:                     my %full=();
 9404:                     my %levels= (
 9405:                                   course => {},
 9406:                                   domain => {},
 9407:                                   system => {},
 9408:                                 );
 9409:                     my %levelscurrent=(
 9410:                                         course => {},
 9411:                                         domain => {},
 9412:                                         system => {},
 9413:                                       );
 9414:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 9415:                     %currentprivs = %{$levelscurrent{'course'}};
 9416:                 }
 9417:             }
 9418:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 9419:                 next if ($item eq '');
 9420:                 my ($rule,$rest) = split(/=/,$item);
 9421:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 9422:                 foreach my $priv (split(/:/,$rest)) {
 9423:                     if ($priv ne '') {
 9424:                         if ($rule eq 'off') {
 9425:                             push(@{$overridden->{$role}{'off'}},$priv);
 9426:                             if ($currentprivs{$priv}) {
 9427:                                 push(@{$settings->{$role}{'off'}},$priv);
 9428:                             }
 9429:                         } else {
 9430:                             push(@{$overridden->{$role}{'on'}},$priv);
 9431:                             unless ($currentprivs{$priv}) {
 9432:                                 push(@{$settings->{$role}{'on'}},$priv);
 9433:                             }
 9434:                         }
 9435:                     }
 9436:                 }
 9437:             }
 9438:         }
 9439:     }
 9440:     return;
 9441: }
 9442: 
 9443: sub update_helpdeskaccess {
 9444:     my ($r,$permission,$brcrum) = @_;
 9445:     my $helpitem = 'Course_Helpdesk_Access';
 9446:     push (@{$brcrum},
 9447:              {href => '/adm/createuser?action=helpdesk',
 9448:               text => 'Helpdesk Access',
 9449:               help => $helpitem},
 9450:              {href => '/adm/createuser?action=helpdesk',
 9451:               text => 'Result',
 9452:               help => $helpitem}
 9453:          );
 9454:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 9455:     my $args = { bread_crumbs           => $brcrum,
 9456:                  bread_crumbs_component => $bread_crumbs_component};
 9457: 
 9458:     # print page header
 9459:     $r->print(&header('',$args));
 9460:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 9461:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 9462:         return;
 9463:     }
 9464:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 9465:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9466:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9467:     my $confname = $cdom.'-domainconfig';
 9468:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 9469:     my $crstype = &Apache::loncommon::course_type();
 9470:     my %customroles = &get_domain_customroles($cdom,$confname);
 9471:     my (%settings,%overridden);
 9472:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 9473:                             $types,\%customroles,\%settings,\%overridden);
 9474:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 9475:     my (%changed,%storehash,@todelete);
 9476: 
 9477:     if (keys(%customroles)) {
 9478:         my (%newsettings,@incrs);
 9479:         foreach my $role (keys(%customroles)) {
 9480:             $newsettings{$role} = {
 9481:                                     access => '',
 9482:                                     status => '',
 9483:                                     exc    => '',
 9484:                                     inc    => '',
 9485:                                     on     => '',
 9486:                                     off    => '',
 9487:                                   };
 9488:             my %current;
 9489:             if (ref($settings{$role}) eq 'HASH') {
 9490:                 %current = %{$settings{$role}};
 9491:             }
 9492:             if (ref($overridden{$role}) eq 'HASH') {
 9493:                 $current{'overridden'} = $overridden{$role};
 9494:             }
 9495:             if ($env{'form.'.$role.'_incrs'}) {
 9496:                 my $access = $env{'form.'.$role.'_access'};
 9497:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 9498:                     push(@incrs,$role);
 9499:                     unless ($current{'access'} eq $access) {
 9500:                         $changed{$role}{'access'} = 1;
 9501:                         $storehash{'internal.adhoc.'.$role} = $access;
 9502:                     }
 9503:                     if ($access eq 'status') {
 9504:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 9505:                         my @stored;
 9506:                         my @shownstatus;
 9507:                         if (ref($types) eq 'ARRAY') {
 9508:                             foreach my $type (sort(@statuses)) {
 9509:                                 if ($type eq 'default') {
 9510:                                     push(@stored,$type);
 9511:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9512:                                     push(@stored,$type);
 9513:                                     push(@shownstatus,$usertypes->{$type});
 9514:                                 }
 9515:                             }
 9516:                             if (grep(/^default$/,@statuses)) {
 9517:                                 push(@shownstatus,$othertitle);
 9518:                             }
 9519:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9520:                         }
 9521:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 9522:                         if (ref($current{'status'}) eq 'ARRAY') {
 9523:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 9524:                             if (@diffs) {
 9525:                                 $changed{$role}{'status'} = 1;
 9526:                             }
 9527:                         } elsif (@stored) {
 9528:                             $changed{$role}{'status'} = 1;
 9529:                         }
 9530:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 9531:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 9532:                         my @newspecstaff;
 9533:                         my @stored;
 9534:                         my @currstaff;
 9535:                         foreach my $person (sort(@personnel)) {
 9536:                             if ($domhelpdesk{$person}) {
 9537:                                 push(@stored,$person);
 9538:                             }
 9539:                         }
 9540:                         if (ref($current{$access}) eq 'ARRAY') {
 9541:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 9542:                             if (@diffs) {
 9543:                                 $changed{$role}{$access} = 1;
 9544:                             }
 9545:                         } elsif (@stored) {
 9546:                             $changed{$role}{$access} = 1;
 9547:                         }
 9548:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9549:                         foreach my $person (@stored) {
 9550:                             my ($uname,$udom) = split(/:/,$person);
 9551:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 9552:                         }
 9553:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 9554:                     }
 9555:                     $newsettings{$role}{'access'} = $access;
 9556:                 }
 9557:             } else {
 9558:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 9559:                     $changed{$role}{'access'} = 1;
 9560:                     $newsettings{$role} = {};
 9561:                     push(@todelete,'internal.adhoc.'.$role);
 9562:                 }
 9563:             }
 9564:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 9565:                 if (ref($current{'overridden'}) eq 'HASH') {
 9566:                     push(@todelete,'internal.adhocpriv.'.$role);
 9567:                 }
 9568:             } else {
 9569:                 my %full=();
 9570:                 my %levels= (
 9571:                              course => {},
 9572:                              domain => {},
 9573:                              system => {},
 9574:                             );
 9575:                 my %levelscurrent=(
 9576:                                    course => {},
 9577:                                    domain => {},
 9578:                                    system => {},
 9579:                                   );
 9580:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9581:                 my (@updatedon,@updatedoff,@override);
 9582:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 9583:                 if (@override) {
 9584:                     foreach my $priv (sort(keys(%full))) {
 9585:                         next unless ($levels{'course'}{$priv});
 9586:                         if (grep(/^\Q$priv\E$/,@override)) {
 9587:                             if ($levelscurrent{'course'}{$priv}) {
 9588:                                 push(@updatedoff,$priv);
 9589:                             } else {
 9590:                                 push(@updatedon,$priv);
 9591:                             }
 9592:                         }
 9593:                     }
 9594:                 }
 9595:                 if (@updatedon) {
 9596:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 9597:                 }
 9598:                 if (@updatedoff) {
 9599:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 9600:                 }
 9601:                 if (ref($current{'overridden'}) eq 'HASH') {
 9602:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 9603:                         if (@updatedon) {
 9604:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 9605:                             if (@diffs) {
 9606:                                 $changed{$role}{'on'} = 1;
 9607:                             }
 9608:                         } else {
 9609:                             $changed{$role}{'on'} = 1;
 9610:                         }
 9611:                     } elsif (@updatedon) {
 9612:                         $changed{$role}{'on'} = 1;
 9613:                     }
 9614:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 9615:                         if (@updatedoff) {
 9616:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 9617:                             if (@diffs) {
 9618:                                 $changed{$role}{'off'} = 1;
 9619:                             }
 9620:                         } else {
 9621:                             $changed{$role}{'off'} = 1;
 9622:                         }
 9623:                     } elsif (@updatedoff) {
 9624:                         $changed{$role}{'off'} = 1;
 9625:                     }
 9626:                 } else {
 9627:                     if (@updatedon) {
 9628:                         $changed{$role}{'on'} = 1;
 9629:                     }
 9630:                     if (@updatedoff) {
 9631:                         $changed{$role}{'off'} = 1;
 9632:                     }
 9633:                 }
 9634:                 if (ref($changed{$role}) eq 'HASH') {
 9635:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 9636:                         my $newpriv;
 9637:                         if (@updatedon) {
 9638:                             $newpriv = 'on='.join(':',@updatedon);
 9639:                         }
 9640:                         if (@updatedoff) {
 9641:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 9642:                         }
 9643:                         if ($newpriv eq '') {
 9644:                             push(@todelete,'internal.adhocpriv.'.$role);
 9645:                         } else {
 9646:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 9647:                         }
 9648:                     }
 9649:                 }
 9650:             }
 9651:         }
 9652:         if (@incrs) {
 9653:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 9654:         } elsif (@todelete) {
 9655:             push(@todelete,'internal.adhocaccess');
 9656:         }
 9657:         if (keys(%changed)) {
 9658:             my ($putres,$delres);
 9659:             if (keys(%storehash)) {
 9660:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 9661:                 my %newenvhash;
 9662:                 foreach my $key (keys(%storehash)) {
 9663:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 9664:                 }
 9665:                 &Apache::lonnet::appenv(\%newenvhash);
 9666:             }
 9667:             if (@todelete) {
 9668:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 9669:                 foreach my $key (@todelete) {
 9670:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 9671:                 }
 9672:             }
 9673:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 9674:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9675:                 my (%domcurrent,%ordered,%description,%domusage);
 9676:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9677:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9678:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9679:                     }
 9680:                 }
 9681:                 my $count = 0;
 9682:                 foreach my $role (sort(keys(%customroles))) {
 9683:                     my ($order,$desc);
 9684:                     if (ref($domcurrent{$role}) eq 'HASH') {
 9685:                         $order = $domcurrent{$role}{'order'};
 9686:                         $desc = $domcurrent{$role}{'desc'};
 9687:                     }
 9688:                     if ($order eq '') {
 9689:                         $order = $count;
 9690:                     }
 9691:                     $ordered{$order} = $role;
 9692:                     if ($desc ne '') {
 9693:                         $description{$role} = $desc;
 9694:                     } else {
 9695:                         $description{$role}= $role;
 9696:                     }
 9697:                     $count++;
 9698:                 }
 9699:                 my @roles_by_num = ();
 9700:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9701:                     push(@roles_by_num,$ordered{$item});
 9702:                 }
 9703:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9704:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 9705:                 $r->print('<ul>');
 9706:                 foreach my $role (@roles_by_num) {
 9707:                     next unless (ref($changed{$role}) eq 'HASH');
 9708:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 9709:                               '<ul>');
 9710:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 9711:                         $r->print('<li>');
 9712:                         if ($env{'form.'.$role.'_incrs'}) {
 9713:                             if ($newsettings{$role}{'access'} eq 'all') {
 9714:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 9715:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 9716:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9717:                                               &Apache::lonnet::plaintext('dh')));
 9718:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 9719:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9720:                                               &Apache::lonnet::plaintext('da')));
 9721:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 9722:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9723:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 9724:                                 if ($newsettings{$role}{'status'}) {
 9725:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 9726:                                     if (split(/,/,$rest) > 1) {
 9727:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 9728:                                                       $newsettings{$role}{'status'}));
 9729:                                     } else {
 9730:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 9731:                                                       $newsettings{$role}{'status'}));
 9732:                                     }
 9733:                                 } else {
 9734:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9735:                                 }
 9736:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 9737:                                 if ($newsettings{$role}{'exc'}) {
 9738:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 9739:                                 } else {
 9740:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9741:                                 }
 9742:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 9743:                                 if ($newsettings{$role}{'inc'}) {
 9744:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 9745:                                 } else {
 9746:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 9747:                                 }
 9748:                             }
 9749:                         } else {
 9750:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 9751:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 9752:                         }
 9753:                         $r->print('</li>');
 9754:                     }
 9755:                     unless ($newsettings{$role}{'access'} eq 'none') {
 9756:                         if ($changed{$role}{'off'}) {
 9757:                             if ($newsettings{$role}{'off'}) {
 9758:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 9759:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 9760:                             } else {
 9761:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 9762:                             }
 9763:                         }
 9764:                         if ($changed{$role}{'on'}) {
 9765:                             if ($newsettings{$role}{'on'}) {
 9766:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 9767:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 9768:                             } else {
 9769:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 9770:                             }
 9771:                         }
 9772:                     }
 9773:                     $r->print('</ul></li>');
 9774:                 }
 9775:                 $r->print('</ul>');
 9776:             }
 9777:         } else {
 9778:             $r->print(&mt('No changes made to helpdesk access settings.'));
 9779:         }
 9780:     }
 9781:     return;
 9782: }
 9783: 
 9784: #-------------------------------------------------- functions for &phase_two
 9785: sub user_search_result {
 9786:     my ($context,$srch) = @_;
 9787:     my %allhomes;
 9788:     my %inst_matches;
 9789:     my %srch_results;
 9790:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 9791:     $srch->{'srchterm'} =~ s/\s+/ /g;
 9792:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 9793:         $response = &mt('Invalid search.');
 9794:     }
 9795:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 9796:         $response = &mt('Invalid search.');
 9797:     }
 9798:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 9799:         $response = &mt('Invalid search.');
 9800:     }
 9801:     if ($srch->{'srchterm'} eq '') {
 9802:         $response = &mt('You must enter a search term.');
 9803:     }
 9804:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 9805:         $response = &mt('Your search term must contain more than just spaces.');
 9806:     }
 9807:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 9808:         if (($srch->{'srchdomain'} eq '') || 
 9809: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 9810:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 9811:         }
 9812:     }
 9813:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 9814:         ($srch->{'srchin'} eq 'alc')) {
 9815:         if ($srch->{'srchby'} eq 'uname') {
 9816:             my $unamecheck = $srch->{'srchterm'};
 9817:             if ($srch->{'srchtype'} eq 'contains') {
 9818:                 if ($unamecheck !~ /^\w/) {
 9819:                     $unamecheck = 'a'.$unamecheck; 
 9820:                 }
 9821:             }
 9822:             if ($unamecheck !~ /^$match_username$/) {
 9823:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 9824:             }
 9825:         }
 9826:     }
 9827:     if ($response ne '') {
 9828:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 9829:     }
 9830:     if ($srch->{'srchin'} eq 'instd') {
 9831:         my $instd_chk = &instdirectorysrch_check($srch);
 9832:         if ($instd_chk ne 'ok') {
 9833:             my $domd_chk = &domdirectorysrch_check($srch);
 9834:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 9835:             if ($domd_chk eq 'ok') {
 9836:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 9837:             }
 9838:             $response .= '<br />';
 9839:         }
 9840:     } else {
 9841:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 9842:             my $domd_chk = &domdirectorysrch_check($srch);
 9843:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 9844:                 my $instd_chk = &instdirectorysrch_check($srch);
 9845:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 9846:                 if ($instd_chk eq 'ok') {
 9847:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 9848:                 }
 9849:                 $response .= '<br />';
 9850:             }
 9851:         }
 9852:     }
 9853:     if ($response ne '') {
 9854:         return ($currstate,$response);
 9855:     }
 9856:     if ($srch->{'srchby'} eq 'uname') {
 9857:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 9858:             if ($env{'form.forcenew'}) {
 9859:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 9860:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9861:                     if ($uhome eq 'no_host') {
 9862:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 9863:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 9864:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 9865:                     } else {
 9866:                         $currstate = 'modify';
 9867:                     }
 9868:                 } else {
 9869:                     $currstate = 'modify';
 9870:                 }
 9871:             } else {
 9872:                 if ($srch->{'srchin'} eq 'dom') {
 9873:                     if ($srch->{'srchtype'} eq 'exact') {
 9874:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9875:                         if ($uhome eq 'no_host') {
 9876:                             ($currstate,$response,$forcenewuser) =
 9877:                                 &build_search_response($context,$srch,%srch_results);
 9878:                         } else {
 9879:                             $currstate = 'modify';
 9880:                             if ($env{'form.action'} eq 'accesslogs') {
 9881:                                 $currstate = 'activity';
 9882:                             }
 9883:                             my $uname = $srch->{'srchterm'};
 9884:                             my $udom = $srch->{'srchdomain'};
 9885:                             $srch_results{$uname.':'.$udom} =
 9886:                                 { &Apache::lonnet::get('environment',
 9887:                                                        ['firstname',
 9888:                                                         'lastname',
 9889:                                                         'permanentemail'],
 9890:                                                          $udom,$uname)
 9891:                                 };
 9892:                         }
 9893:                     } else {
 9894:                         %srch_results = &Apache::lonnet::usersearch($srch);
 9895:                         ($currstate,$response,$forcenewuser) =
 9896:                             &build_search_response($context,$srch,%srch_results);
 9897:                     }
 9898:                 } else {
 9899:                     my $courseusers = &get_courseusers();
 9900:                     if ($srch->{'srchtype'} eq 'exact') {
 9901:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 9902:                             $currstate = 'modify';
 9903:                         } else {
 9904:                             ($currstate,$response,$forcenewuser) =
 9905:                                 &build_search_response($context,$srch,%srch_results);
 9906:                         }
 9907:                     } else {
 9908:                         foreach my $user (keys(%$courseusers)) {
 9909:                             my ($cuname,$cudomain) = split(/:/,$user);
 9910:                             if ($cudomain eq $srch->{'srchdomain'}) {
 9911:                                 my $matched = 0;
 9912:                                 if ($srch->{'srchtype'} eq 'begins') {
 9913:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 9914:                                         $matched = 1;
 9915:                                     }
 9916:                                 } else {
 9917:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 9918:                                         $matched = 1;
 9919:                                     }
 9920:                                 }
 9921:                                 if ($matched) {
 9922:                                     $srch_results{$user} = 
 9923: 					{&Apache::lonnet::get('environment',
 9924: 							     ['firstname',
 9925: 							      'lastname',
 9926: 							      'permanentemail'],
 9927: 							      $cudomain,$cuname)};
 9928:                                 }
 9929:                             }
 9930:                         }
 9931:                         ($currstate,$response,$forcenewuser) =
 9932:                             &build_search_response($context,$srch,%srch_results);
 9933:                     }
 9934:                 }
 9935:             }
 9936:         } elsif ($srch->{'srchin'} eq 'alc') {
 9937:             $currstate = 'query';
 9938:         } elsif ($srch->{'srchin'} eq 'instd') {
 9939:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 9940:             if ($dirsrchres eq 'ok') {
 9941:                 ($currstate,$response,$forcenewuser) = 
 9942:                     &build_search_response($context,$srch,%srch_results);
 9943:             } else {
 9944:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9945:                 $response = '<span class="LC_warning">'.
 9946:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9947:                     '</span><br />'.
 9948:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 9949:                     '<br />'; 
 9950:             }
 9951:         }
 9952:     } else {
 9953:         if ($srch->{'srchin'} eq 'dom') {
 9954:             %srch_results = &Apache::lonnet::usersearch($srch);
 9955:             ($currstate,$response,$forcenewuser) = 
 9956:                 &build_search_response($context,$srch,%srch_results); 
 9957:         } elsif ($srch->{'srchin'} eq 'crs') {
 9958:             my $courseusers = &get_courseusers(); 
 9959:             foreach my $user (keys(%$courseusers)) {
 9960:                 my ($uname,$udom) = split(/:/,$user);
 9961:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 9962:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 9963:                 if ($srch->{'srchby'} eq 'lastname') {
 9964:                     if ((($srch->{'srchtype'} eq 'exact') && 
 9965:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 9966:                         (($srch->{'srchtype'} eq 'begins') &&
 9967:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 9968:                         (($srch->{'srchtype'} eq 'contains') &&
 9969:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 9970:                         $srch_results{$user} = {firstname => $names{'firstname'},
 9971:                                             lastname => $names{'lastname'},
 9972:                                             permanentemail => $emails{'permanentemail'},
 9973:                                            };
 9974:                     }
 9975:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 9976:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 9977:                     $srchlast =~ s/\s+$//;
 9978:                     $srchfirst =~ s/^\s+//;
 9979:                     if ($srch->{'srchtype'} eq 'exact') {
 9980:                         if (($names{'lastname'} eq $srchlast) &&
 9981:                             ($names{'firstname'} eq $srchfirst)) {
 9982:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9983:                                                 lastname => $names{'lastname'},
 9984:                                                 permanentemail => $emails{'permanentemail'},
 9985: 
 9986:                                            };
 9987:                         }
 9988:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 9989:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 9990:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 9991:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9992:                                                 lastname => $names{'lastname'},
 9993:                                                 permanentemail => $emails{'permanentemail'},
 9994:                                                };
 9995:                         }
 9996:                     } else {
 9997:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 9998:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 9999:                             $srch_results{$user} = {firstname => $names{'firstname'},
10000:                                                 lastname => $names{'lastname'},
10001:                                                 permanentemail => $emails{'permanentemail'},
10002:                                                };
10003:                         }
10004:                     }
10005:                 }
10006:             }
10007:             ($currstate,$response,$forcenewuser) = 
10008:                 &build_search_response($context,$srch,%srch_results); 
10009:         } elsif ($srch->{'srchin'} eq 'alc') {
10010:             $currstate = 'query';
10011:         } elsif ($srch->{'srchin'} eq 'instd') {
10012:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
10013:             if ($dirsrchres eq 'ok') {
10014:                 ($currstate,$response,$forcenewuser) = 
10015:                     &build_search_response($context,$srch,%srch_results);
10016:             } else {
10017:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
10018:                 $response = '<span class="LC_warning">'.
10019:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
10020:                     '</span><br />'.
10021:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
10022:                     '<br />';
10023:             }
10024:         }
10025:     }
10026:     return ($currstate,$response,$forcenewuser,\%srch_results);
10027: }
10028: 
10029: sub domdirectorysrch_check {
10030:     my ($srch) = @_;
10031:     my $response;
10032:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10033:                                              ['directorysrch'],$srch->{'srchdomain'});
10034:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10035:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10036:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
10037:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
10038:         }
10039:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
10040:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10041:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
10042:             }
10043:         }
10044:     }
10045:     return 'ok';
10046: }
10047: 
10048: sub instdirectorysrch_check {
10049:     my ($srch) = @_;
10050:     my $can_search = 0;
10051:     my $response;
10052:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10053:                                              ['directorysrch'],$srch->{'srchdomain'});
10054:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10055:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10056:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
10057:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
10058:         }
10059:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
10060:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10061:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
10062:             }
10063:             my @usertypes = split(/:/,$env{'environment.inststatus'});
10064:             if (!@usertypes) {
10065:                 push(@usertypes,'default');
10066:             }
10067:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
10068:                 foreach my $type (@usertypes) {
10069:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
10070:                         $can_search = 1;
10071:                         last;
10072:                     }
10073:                 }
10074:             }
10075:             if (!$can_search) {
10076:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
10077:                 my @longtypes; 
10078:                 foreach my $item (@usertypes) {
10079:                     if (defined($insttypes->{$item})) { 
10080:                         push (@longtypes,$insttypes->{$item});
10081:                     } elsif ($item eq 'default') {
10082:                         push (@longtypes,&mt('other')); 
10083:                     }
10084:                 }
10085:                 my $insttype_str = join(', ',@longtypes); 
10086:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
10087:             }
10088:         } else {
10089:             $can_search = 1;
10090:         }
10091:     } else {
10092:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
10093:     }
10094:     my %longtext = &Apache::lonlocal::texthash (
10095:                        uname     => 'username',
10096:                        lastfirst => 'last name, first name',
10097:                        lastname  => 'last name',
10098:                        contains  => 'contains',
10099:                        exact     => 'as exact match to',
10100:                        begins    => 'begins with',
10101:                    );
10102:     if ($can_search) {
10103:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
10104:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
10105:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
10106:             }
10107:         } else {
10108:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
10109:         }
10110:     }
10111:     if ($can_search) {
10112:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
10113:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
10114:                 return 'ok';
10115:             } else {
10116:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10117:             }
10118:         } else {
10119:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
10120:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
10121:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
10122:                 return 'ok';
10123:             } else {
10124:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10125:             }
10126:         }
10127:     }
10128: }
10129: 
10130: sub get_courseusers {
10131:     my %advhash;
10132:     my $classlist = &Apache::loncoursedata::get_classlist();
10133:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
10134:     foreach my $role (sort(keys(%coursepersonnel))) {
10135:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
10136: 	    if (!exists($classlist->{$user})) {
10137: 		$classlist->{$user} = [];
10138: 	    }
10139:         }
10140:     }
10141:     return $classlist;
10142: }
10143: 
10144: sub build_search_response {
10145:     my ($context,$srch,%srch_results) = @_;
10146:     my ($currstate,$response,$forcenewuser);
10147:     my %names = (
10148:           'uname'     => 'username',
10149:           'lastname'  => 'last name',
10150:           'lastfirst' => 'last name, first name',
10151:           'crs'       => 'this course',
10152:           'dom'       => 'LON-CAPA domain',
10153:           'instd'     => 'the institutional directory for domain',
10154:     );
10155: 
10156:     my %single = (
10157:                    begins   => 'A match',
10158:                    contains => 'A match',
10159:                    exact    => 'An exact match',
10160:                  );
10161:     my %nomatch = (
10162:                    begins   => 'No match',
10163:                    contains => 'No match',
10164:                    exact    => 'No exact match',
10165:                   );
10166:     if (keys(%srch_results) > 1) {
10167:         $currstate = 'select';
10168:     } else {
10169:         if (keys(%srch_results) == 1) {
10170:             if ($env{'form.action'} eq 'accesslogs') {
10171:                 $currstate = 'activity';
10172:             } else {
10173:                 $currstate = 'modify';
10174:             }
10175:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
10176:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10177:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
10178:             }
10179:         } else { # Search has nothing found. Prepare message to user.
10180:             $response = '<span class="LC_warning">';
10181:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10182:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
10183:                                  '<b>'.$srch->{'srchterm'}.'</b>',
10184:                                  &display_domain_info($srch->{'srchdomain'}));
10185:             } else {
10186:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
10187:                                  '<b>'.$srch->{'srchterm'}.'</b>');
10188:             }
10189:             $response .= '</span>';
10190: 
10191:             if ($srch->{'srchin'} ne 'alc') {
10192:                 $forcenewuser = 1;
10193:                 my $cansrchinst = 0; 
10194:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
10195:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
10196:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
10197:                         if ($domconfig{'directorysrch'}{'available'}) {
10198:                             $cansrchinst = 1;
10199:                         } 
10200:                     }
10201:                 }
10202:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
10203:                      ($srch->{'srchby'} eq 'lastname')) &&
10204:                     ($srch->{'srchin'} eq 'dom')) {
10205:                     if ($cansrchinst) {
10206:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
10207:                     }
10208:                 }
10209:                 if ($srch->{'srchin'} eq 'crs') {
10210:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
10211:                 }
10212:             }
10213:             my $createdom = $env{'request.role.domain'};
10214:             if ($context eq 'requestcrs') {
10215:                 if ($env{'form.coursedom'} ne '') {
10216:                     $createdom = $env{'form.coursedom'};
10217:                 }
10218:             }
10219:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
10220:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
10221:                 my $cancreate =
10222:                     &Apache::lonuserutils::can_create_user($createdom,$context);
10223:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
10224:                 if ($cancreate) {
10225:                     my $showdom = &display_domain_info($createdom); 
10226:                     $response .= '<br /><br />'
10227:                                 .'<b>'.&mt('To add a new user:').'</b>'
10228:                                 .'<br />';
10229:                     if ($context eq 'requestcrs') {
10230:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
10231:                     } else {
10232:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
10233:                     }
10234:                     $response .='<ul><li>'
10235:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
10236:                                 .'</li><li>'
10237:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
10238:                                 .'</li><li>'
10239:                                 .&mt('Provide the proposed username')
10240:                                 .'</li><li>'
10241:                                 .&mt("Click 'Search'")
10242:                                 .'</li></ul><br />';
10243:                 } else {
10244:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
10245:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
10246:                         $response .= '<br /><br />';
10247:                         if ($context eq 'requestcrs') {
10248:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
10249:                         } else {
10250:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
10251:                         }
10252:                         $response .= '<br />'
10253:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
10254:                                         ,' <a'.$helplink.'>'
10255:                                         ,'</a>')
10256:                                      .'<br />';
10257:                     }
10258:                 }
10259:             }
10260:         }
10261:     }
10262:     return ($currstate,$response,$forcenewuser);
10263: }
10264: 
10265: sub display_domain_info {
10266:     my ($dom) = @_;
10267:     my $output = $dom;
10268:     if ($dom ne '') { 
10269:         my $domdesc = &Apache::lonnet::domain($dom,'description');
10270:         if ($domdesc ne '') {
10271:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
10272:         }
10273:     }
10274:     return $output;
10275: }
10276: 
10277: sub crumb_utilities {
10278:     my %elements = (
10279:        crtuser => {
10280:            srchterm => 'text',
10281:            srchin => 'selectbox',
10282:            srchby => 'selectbox',
10283:            srchtype => 'selectbox',
10284:            srchdomain => 'selectbox',
10285:        },
10286:        crtusername => {
10287:            srchterm => 'text',
10288:            srchdomain => 'selectbox',
10289:        },
10290:        docustom => {
10291:            rolename => 'selectbox',
10292:            newrolename => 'textbox',
10293:        },
10294:        studentform => {
10295:            srchterm => 'text',
10296:            srchin => 'selectbox',
10297:            srchby => 'selectbox',
10298:            srchtype => 'selectbox',
10299:            srchdomain => 'selectbox',
10300:        },
10301:     );
10302: 
10303:     my $jsback .= qq|
10304: function backPage(formname,prevphase,prevstate) {
10305:     if (typeof prevphase == 'undefined') {
10306:         formname.phase.value = '';
10307:     }
10308:     else {  
10309:         formname.phase.value = prevphase;
10310:     }
10311:     if (typeof prevstate == 'undefined') {
10312:         formname.currstate.value = '';
10313:     }
10314:     else {
10315:         formname.currstate.value = prevstate;
10316:     }
10317:     formname.submit();
10318: }
10319: |;
10320:     return ($jsback,\%elements);
10321: }
10322: 
10323: sub course_level_table {
10324:     my ($inccourses,$showcredits,$defaultcredits) = @_;
10325:     return unless (ref($inccourses) eq 'HASH');
10326:     my $table = '';
10327: # Custom Roles?
10328: 
10329:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10330:     my %lt=&Apache::lonlocal::texthash(
10331:             'exs'  => "Existing sections",
10332:             'new'  => "Define new section",
10333:             'ssd'  => "Set Start Date",
10334:             'sed'  => "Set End Date",
10335:             'crl'  => "Course Level",
10336:             'act'  => "Activate",
10337:             'rol'  => "Role",
10338:             'ext'  => "Extent",
10339:             'grs'  => "Section",
10340:             'crd'  => "Credits",
10341:             'sta'  => "Start",
10342:             'end'  => "End"
10343:     );
10344: 
10345:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
10346: 	my $thiscourse=$protectedcourse;
10347: 	$thiscourse=~s:_:/:g;
10348: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
10349:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
10350: 	my $area=$coursedata{'description'};
10351:         my $crstype=$coursedata{'type'};
10352: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
10353: 	my ($domain,$cnum)=split(/\//,$thiscourse);
10354:         my %sections_count;
10355:         if (defined($env{'request.course.id'})) {
10356:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
10357:                 %sections_count = 
10358: 		    &Apache::loncommon::get_sections($domain,$cnum);
10359:             }
10360:         }
10361:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
10362: 	foreach my $role (@roles) {
10363:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
10364: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
10365:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
10366:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10367:                                             $plrole,\%sections_count,\%lt,
10368:                                             $showcredits,$defaultcredits,$crstype);
10369:             } elsif ($env{'request.course.sec'} ne '') {
10370:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
10371:                                              $env{'request.course.sec'})) {
10372:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10373:                                                 $plrole,\%sections_count,\%lt,
10374:                                                 $showcredits,$defaultcredits,$crstype);
10375:                 }
10376:             }
10377:         }
10378:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
10379:             foreach my $cust (sort(keys(%customroles))) {
10380:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
10381:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
10382:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10383:                                             $cust,\%sections_count,\%lt,
10384:                                             $showcredits,$defaultcredits,$crstype);
10385:             }
10386: 	}
10387:     }
10388:     return '' if ($table eq ''); # return nothing if there is nothing 
10389:                                  # in the table
10390:     my $result;
10391:     if (!$env{'request.course.id'}) {
10392:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
10393:     }
10394:     $result .= 
10395: &Apache::loncommon::start_data_table().
10396: &Apache::loncommon::start_data_table_header_row().
10397: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10398: '<th>'.$lt{'ext'}.'</th><th>'."\n";
10399:     if ($showcredits) {
10400:         $result .= $lt{'crd'}.'</th>';
10401:     }
10402:     $result .=
10403: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
10404: '<th>'.$lt{'end'}.'</th>'.
10405: &Apache::loncommon::end_data_table_header_row().
10406: $table.
10407: &Apache::loncommon::end_data_table();
10408:     return $result;
10409: }
10410: 
10411: sub course_level_row {
10412:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
10413:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
10414:     my $creditem;
10415:     my $row = &Apache::loncommon::start_data_table_row().
10416:               ' <td><input type="checkbox" name="act_'.
10417:               $protectedcourse.'_'.$role.'" /></td>'."\n".
10418:               ' <td>'.$plrole.'</td>'."\n".
10419:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
10420:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
10421:         $row .= 
10422:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
10423:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
10424:     } else {
10425:         $row .= '<td>&nbsp;</td>';
10426:     }
10427:     if (($role eq 'cc') || ($role eq 'co')) {
10428:         $row .= '<td>&nbsp;</td>';
10429:     } elsif ($env{'request.course.sec'} ne '') {
10430:         $row .= ' <td><input type="hidden" value="'.
10431:                 $env{'request.course.sec'}.'" '.
10432:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
10433:                 $env{'request.course.sec'}.'</td>';
10434:     } else {
10435:         if (ref($sections_count) eq 'HASH') {
10436:             my $currsec = 
10437:                 &Apache::lonuserutils::course_sections($sections_count,
10438:                                                        $protectedcourse.'_'.$role);
10439:             $row .= '<td><table class="LC_createuser">'."\n".
10440:                     '<tr class="LC_section_row">'."\n".
10441:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
10442:                        $currsec.'</td>'."\n".
10443:                      ' <td>&nbsp;&nbsp;</td>'."\n".
10444:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
10445:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
10446:                      '" value="" />'.
10447:                      '<input type="hidden" '.
10448:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
10449:                      '</tr></table></td>'."\n";
10450:         } else {
10451:             $row .= '<td><input type="text" size="10" '.
10452:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
10453:         }
10454:     }
10455:     $row .= <<ENDTIMEENTRY;
10456: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
10457: <a href=
10458: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
10459: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
10460: <a href=
10461: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
10462: ENDTIMEENTRY
10463:     $row .= &Apache::loncommon::end_data_table_row();
10464:     return $row;
10465: }
10466: 
10467: sub course_level_dc {
10468:     my ($dcdom,$showcredits) = @_;
10469:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10470:     my @roles = &Apache::lonuserutils::roles_by_context('course');
10471:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
10472:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
10473:                       '<input type="hidden" name="dccourse" value="" />';
10474:     my $courseform=&Apache::loncommon::selectcourse_link
10475:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
10476:     my $credit_elem;
10477:     if ($showcredits) {
10478:         $credit_elem = 'credits';
10479:     }
10480:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
10481:     my %lt=&Apache::lonlocal::texthash(
10482:                     'rol'  => "Role",
10483:                     'grs'  => "Section",
10484:                     'exs'  => "Existing sections",
10485:                     'new'  => "Define new section", 
10486:                     'sta'  => "Start",
10487:                     'end'  => "End",
10488:                     'ssd'  => "Set Start Date",
10489:                     'sed'  => "Set End Date",
10490:                     'scc'  => "Course/Community",
10491:                     'crd'  => "Credits",
10492:                   );
10493:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
10494:                  &Apache::loncommon::start_data_table().
10495:                  &Apache::loncommon::start_data_table_header_row().
10496:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10497:                  '<th>'.$lt{'grs'}.'</th>'."\n";
10498:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
10499:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
10500:                  &Apache::loncommon::end_data_table_header_row();
10501:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
10502:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
10503:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
10504:                      '<td valign="top"><br /><select name="role">'."\n";
10505:     foreach my $role (@roles) {
10506:         my $plrole=&Apache::lonnet::plaintext($role);
10507:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
10508:     }
10509:     if ( keys(%customroles) > 0) {
10510:         foreach my $cust (sort(keys(%customroles))) {
10511:             my $custrole='cr_cr_'.$env{'user.domain'}.
10512:                     '_'.$env{'user.name'}.'_'.$cust;
10513:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
10514:         }
10515:     }
10516:     $otheritems .= '</select></td><td>'.
10517:                      '<table border="0" cellspacing="0" cellpadding="0">'.
10518:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
10519:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
10520:                      '<td>&nbsp;&nbsp;</td>'.
10521:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
10522:                      '<input type="text" name="newsec" value="" />'.
10523:                      '<input type="hidden" name="section" value="" />'.
10524:                      '<input type="hidden" name="groups" value="" />'.
10525:                      '<input type="hidden" name="crstype" value="" /></td>'.
10526:                      '</tr></table></td>'."\n";
10527:     if ($showcredits) {
10528:         $otheritems .= '<td><br />'."\n".
10529:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
10530:     }
10531:     $otheritems .= <<ENDTIMEENTRY;
10532: <td><br /><input type="hidden" name="start" value='' />
10533: <a href=
10534: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
10535: <td><br /><input type="hidden" name="end" value='' />
10536: <a href=
10537: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
10538: ENDTIMEENTRY
10539:     $otheritems .= &Apache::loncommon::end_data_table_row().
10540:                    &Apache::loncommon::end_data_table()."\n";
10541:     return $cb_jscript.$hiddenitems.$header.$otheritems;
10542: }
10543: 
10544: sub update_selfenroll_config {
10545:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
10546:     return unless (ref($currsettings) eq 'HASH');
10547:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
10548:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10549:     my (%changes,%warning);
10550:     my $curr_types;
10551:     my %noedit;
10552:     unless ($context eq 'domain') {
10553:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
10554:     }
10555:     if (ref($row) eq 'ARRAY') {
10556:         foreach my $item (@{$row}) {
10557:             next if ($noedit{$item});
10558:             if ($item eq 'enroll_dates') {
10559:                 my (%currenrolldate,%newenrolldate);
10560:                 foreach my $type ('start','end') {
10561:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
10562:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
10563:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
10564:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
10565:                     }
10566:                 }
10567:             } elsif ($item eq 'access_dates') {
10568:                 my (%currdate,%newdate);
10569:                 foreach my $type ('start','end') {
10570:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
10571:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
10572:                     if ($newdate{$type} ne $currdate{$type}) {
10573:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
10574:                     }
10575:                 }
10576:             } elsif ($item eq 'types') {
10577:                 $curr_types = $currsettings->{'selfenroll_'.$item};
10578:                 if ($env{'form.selfenroll_all'}) {
10579:                     if ($curr_types ne '*') {
10580:                         $changes{'internal.selfenroll_types'} = '*';
10581:                     } else {
10582:                         next;
10583:                     }
10584:                 } else {
10585:                     my %currdoms;
10586:                     my @entries = split(/;/,$curr_types);
10587:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
10588:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
10589:                     my $newnum = 0;
10590:                     my @latesttypes;
10591:                     foreach my $num (@activations) {
10592:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
10593:                         if (@types > 0) {
10594:                             @types = sort(@types);
10595:                             my $typestr = join(',',@types);
10596:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
10597:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10598:                             $currdoms{$typedom} = 1;
10599:                             $newnum ++;
10600:                         }
10601:                     }
10602:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
10603:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
10604:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
10605:                             if (@types > 0) {
10606:                                 @types = sort(@types);
10607:                                 my $typestr = join(',',@types);
10608:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
10609:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
10610:                                 $currdoms{$typedom} = 1;
10611:                                 $newnum ++;
10612:                             }
10613:                         }
10614:                     }
10615:                     if ($env{'form.selfenroll_newdom'} ne '') {
10616:                         my $typedom = $env{'form.selfenroll_newdom'};
10617:                         if ((!defined($currdoms{$typedom})) && 
10618:                             (&Apache::lonnet::domain($typedom) ne '')) {
10619:                             my $typestr;
10620:                             my ($othertitle,$usertypes,$types) = 
10621:                                 &Apache::loncommon::sorted_inst_types($typedom);
10622:                             my $othervalue = 'any';
10623:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
10624:                                 if (@{$types} > 0) {
10625:                                     my @esc_types = map { &escape($_); } @{$types};
10626:                                     $othervalue = 'other';
10627:                                     $typestr = join(',',(@esc_types,$othervalue));
10628:                                 }
10629:                                 $typestr = $othervalue;
10630:                             } else {
10631:                                 $typestr = $othervalue;
10632:                             } 
10633:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10634:                             $newnum ++ ;
10635:                         }
10636:                     }
10637:                     my $selfenroll_types = join(';',@latesttypes);
10638:                     if ($selfenroll_types ne $curr_types) {
10639:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
10640:                     }
10641:                 }
10642:             } elsif ($item eq 'limit') {
10643:                 my $newlimit = $env{'form.selfenroll_limit'};
10644:                 my $newcap = $env{'form.selfenroll_cap'};
10645:                 $newcap =~s/\s+//g;
10646:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10647:                 $currlimit = 'none' if ($currlimit eq '');
10648:                 my $currcap = $currsettings->{'selfenroll_cap'};
10649:                 if ($newlimit ne $currlimit) {
10650:                     if ($newlimit ne 'none') {
10651:                         if ($newcap =~ /^\d+$/) {
10652:                             if ($newcap ne $currcap) {
10653:                                 $changes{'internal.selfenroll_cap'} = $newcap;
10654:                             }
10655:                             $changes{'internal.selfenroll_limit'} = $newlimit;
10656:                         } else {
10657:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10658:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
10659:                         }
10660:                     } elsif ($currcap ne '') {
10661:                         $changes{'internal.selfenroll_cap'} = '';
10662:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
10663:                     }
10664:                 } elsif ($currlimit ne 'none') {
10665:                     if ($newcap =~ /^\d+$/) {
10666:                         if ($newcap ne $currcap) {
10667:                             $changes{'internal.selfenroll_cap'} = $newcap;
10668:                         }
10669:                     } else {
10670:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10671:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
10672:                     }
10673:                 }
10674:             } elsif ($item eq 'approval') {
10675:                 my (@currnotified,@newnotified);
10676:                 my $currapproval = $currsettings->{'selfenroll_approval'};
10677:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
10678:                 if ($currnotifylist ne '') {
10679:                     @currnotified = split(/,/,$currnotifylist);
10680:                     @currnotified = sort(@currnotified);
10681:                 }
10682:                 my $newapproval = $env{'form.selfenroll_approval'};
10683:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
10684:                 @newnotified = sort(@newnotified);
10685:                 if ($newapproval ne $currapproval) {
10686:                     $changes{'internal.selfenroll_approval'} = $newapproval;
10687:                     if (!$newapproval) {
10688:                         if ($currnotifylist ne '') {
10689:                             $changes{'internal.selfenroll_notifylist'} = '';
10690:                         }
10691:                     } else {
10692:                         my @differences =  
10693:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10694:                         if (@differences > 0) {
10695:                             if (@newnotified > 0) {
10696:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10697:                             } else {
10698:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10699:                             }
10700:                         }
10701:                     }
10702:                 } else {
10703:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10704:                     if (@differences > 0) {
10705:                         if (@newnotified > 0) {
10706:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10707:                         } else {
10708:                             $changes{'internal.selfenroll_notifylist'} = '';
10709:                         }
10710:                     }
10711:                 }
10712:             } else {
10713:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
10714:                 my $newval = $env{'form.selfenroll_'.$item};
10715:                 if ($item eq 'section') {
10716:                     $newval = $env{'form.sections'};
10717:                     if (defined($curr_groups{$newval})) {
10718:                         $newval = $curr_val;
10719:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
10720:                                           &mt('Group names and section names must be distinct');
10721:                     } elsif ($newval eq 'all') {
10722:                         $newval = $curr_val;
10723:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
10724:                     }
10725:                     if ($newval eq '') {
10726:                         $newval = 'none';
10727:                     }
10728:                 }
10729:                 if ($newval ne $curr_val) {
10730:                     $changes{'internal.selfenroll_'.$item} = $newval;
10731:                 }
10732:             }
10733:         }
10734:         if (keys(%warning) > 0) {
10735:             foreach my $item (@{$row}) {
10736:                 if (exists($warning{$item})) {
10737:                     $r->print($warning{$item}.'<br />');
10738:                 }
10739:             } 
10740:         }
10741:         if (keys(%changes) > 0) {
10742:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
10743:             if ($putresult eq 'ok') {
10744:                 if ((exists($changes{'internal.selfenroll_types'})) ||
10745:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
10746:                     (exists($changes{'internal.selfenroll_end_date'}))) {
10747:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
10748:                                                                 $cnum,undef,undef,'Course');
10749:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
10750:                     if (ref($crsinfo{$cid}) eq 'HASH') {
10751:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
10752:                             if (exists($changes{'internal.'.$item})) {
10753:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
10754:                             }
10755:                         }
10756:                         my $crsputresult =
10757:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
10758:                                                          $chome,'notime');
10759:                     }
10760:                 }
10761:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
10762:                 foreach my $item (@{$row}) {
10763:                     my $title = $item;
10764:                     if (ref($lt) eq 'HASH') {
10765:                         $title = $lt->{$item};
10766:                     }
10767:                     if ($item eq 'enroll_dates') {
10768:                         foreach my $type ('start','end') {
10769:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
10770:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
10771:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10772:                                           $title,$type,$newdate).'</li>');
10773:                             }
10774:                         }
10775:                     } elsif ($item eq 'access_dates') {
10776:                         foreach my $type ('start','end') {
10777:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
10778:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
10779:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10780:                                           $title,$type,$newdate).'</li>');
10781:                             }
10782:                         }
10783:                     } elsif ($item eq 'limit') {
10784:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
10785:                             (exists($changes{'internal.selfenroll_cap'}))) {
10786:                             my ($newval,$newcap);
10787:                             if ($changes{'internal.selfenroll_cap'} ne '') {
10788:                                 $newcap = $changes{'internal.selfenroll_cap'}
10789:                             } else {
10790:                                 $newcap = $currsettings->{'selfenroll_cap'};
10791:                             }
10792:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
10793:                                 $newval = &mt('No limit');
10794:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
10795:                                      'allstudents') {
10796:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10797:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10798:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10799:                             } else {
10800:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10801:                                 if ($currlimit eq 'allstudents') {
10802:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10803:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10804:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10805:                                 }
10806:                             }
10807:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10808:                         }
10809:                     } elsif ($item eq 'approval') {
10810:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
10811:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
10812:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
10813:                             my ($newval,$newnotify);
10814:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
10815:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
10816:                             } else {   
10817:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
10818:                             }
10819:                             if (exists($changes{'internal.selfenroll_approval'})) {
10820:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
10821:                                     $changes{'internal.selfenroll_approval'} = '0';
10822:                                 }
10823:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
10824:                             } else {
10825:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
10826:                                 if ($currapproval !~ /^[012]$/) {
10827:                                     $currapproval = 0;
10828:                                 }
10829:                                 $newval = $selfdescs{'approval'}{$currapproval};
10830:                             }
10831:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
10832:                             if ($newnotify) {
10833:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
10834:                             } else {
10835:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
10836:                             }
10837:                             $r->print('</li>'."\n");
10838:                         }
10839:                     } else {
10840:                         if (exists($changes{'internal.selfenroll_'.$item})) {
10841:                             my $newval = $changes{'internal.selfenroll_'.$item};
10842:                             if ($item eq 'types') {
10843:                                 if ($newval eq '') {
10844:                                     $newval = &mt('None');
10845:                                 } elsif ($newval eq '*') {
10846:                                     $newval = &mt('Any user in any domain');
10847:                                 }
10848:                             } elsif ($item eq 'registered') {
10849:                                 if ($newval eq '1') {
10850:                                     $newval = &mt('Yes');
10851:                                 } elsif ($newval eq '0') {
10852:                                     $newval = &mt('No');
10853:                                 }
10854:                             }
10855:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10856:                         }
10857:                     }
10858:                 }
10859:                 $r->print('</ul>');
10860:                 if ($env{'course.'.$cid.'.description'} ne '') {
10861:                     my %newenvhash;
10862:                     foreach my $key (keys(%changes)) {
10863:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
10864:                     }
10865:                     &Apache::lonnet::appenv(\%newenvhash);
10866:                 }
10867:             } else {
10868:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
10869:                           &mt('The error was: [_1].',$putresult));
10870:             }
10871:         } else {
10872:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10873:         }
10874:     } else {
10875:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10876:     }
10877:     my $visactions = &cat_visibility($cdom);
10878:     my ($cathash,%cattype);
10879:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
10880:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10881:         $cathash = $domconfig{'coursecategories'}{'cats'};
10882:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
10883:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
10884:     } else {
10885:         $cathash = {};
10886:         $cattype{'auth'} = 'std';
10887:         $cattype{'unauth'} = 'std';
10888:     }
10889:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
10890:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10891:                   '<br />'.
10892:                   '<br />'.$visactions->{'take'}.'<ul>'.
10893:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
10894:                   '</ul>');
10895:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
10896:         if ($currsettings->{'uniquecode'}) {
10897:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
10898:         } else {
10899:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10900:                   '<br />'.
10901:                   '<br />'.$visactions->{'take'}.'<ul>'.
10902:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
10903:                   '</ul><br />');
10904:         }
10905:     } else {
10906:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
10907:         if (ref($visactions) eq 'HASH') {
10908:             if (!$visible) {
10909:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10910:                           '<br />');
10911:                 if (ref($vismsgs) eq 'ARRAY') {
10912:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
10913:                     foreach my $item (@{$vismsgs}) {
10914:                         $r->print('<li>'.$visactions->{$item}.'</li>');
10915:                     }
10916:                     $r->print('</ul>');
10917:                 }
10918:                 $r->print($cansetvis);
10919:             }
10920:         }
10921:     } 
10922:     return;
10923: }
10924: 
10925: #---------------------------------------------- end functions for &phase_two
10926: 
10927: #--------------------------------- functions for &phase_two and &phase_three
10928: 
10929: #--------------------------end of functions for &phase_two and &phase_three
10930: 
10931: 1;
10932: __END__
10933: 
10934: 

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