File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.475: download - view: text, annotated - select for diffs
Thu Feb 29 14:09:30 2024 UTC (3 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Authoring Space defaults which domain coordinator can override for
  individual users.
  - Remove some duplicate definitions and assignments.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.475 2024/02/29 14:09:30 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use Apache::lonviewcoauthors;
   74: use LONCAPA qw(:DEFAULT :match);
   75: use HTML::Entities;
   76: 
   77: my $loginscript; # piece of javascript used in two separate instances
   78: my $authformnop;
   79: my $authformkrb;
   80: my $authformint;
   81: my $authformfsys;
   82: my $authformloc;
   83: my $authformlti;
   84: 
   85: sub initialize_authen_forms {
   86:     my ($dom,$formname,$curr_authtype,$mode,$readonly) = @_;
   87:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   88:     my %param = ( formname => $formname,
   89:                   kerb_def_dom => $krbdefdom,
   90:                   kerb_def_auth => $krbdef,
   91:                   domain => $dom,
   92:                 );
   93:     my %abv_auth = &auth_abbrev();
   94:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix|lti):(.*)$/) {
   95:         my $long_auth = $1;
   96:         my $curr_autharg = $2;
   97:         my %abv_auth = &auth_abbrev();
   98:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   99:         if ($long_auth =~ /^krb(4|5)$/) {
  100:             $param{'curr_kerb_ver'} = $1;
  101:             $param{'curr_autharg'} = $curr_autharg;
  102:         }
  103:         if ($mode eq 'modifyuser') {
  104:             $param{'mode'} = $mode;
  105:         }
  106:     }
  107:     if ($readonly) {
  108:         $param{'readonly'} = 1;
  109:     }
  110:     $loginscript  = &Apache::loncommon::authform_header(%param);
  111:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  112:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  113:     $authformint  = &Apache::loncommon::authform_internal(%param);
  114:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  115:     $authformloc  = &Apache::loncommon::authform_local(%param);
  116:     $authformlti  = &Apache::loncommon::authform_lti(%param);
  117: }
  118: 
  119: sub auth_abbrev {
  120:     my %abv_auth = (
  121:                      krb5      => 'krb',
  122:                      krb4      => 'krb',
  123:                      internal  => 'int',
  124:                      localauth => 'loc',
  125:                      unix      => 'fsys',
  126:                      lti       => 'lti',
  127:                    );
  128:     return %abv_auth;
  129: }
  130: 
  131: # ====================================================
  132: 
  133: sub user_quotas {
  134:     my ($ccuname,$ccdomain,$name) = @_;
  135:     my %lt = &Apache::lonlocal::texthash(
  136:                    'cust'      => "Custom quota",
  137:                    'chqu'      => "Change quota",
  138:     );
  139:     my ($output,$longinsttype);
  140:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  141:     my %titles = &Apache::lonlocal::texthash (
  142:                     portfolio => "Disk space allocated to user's portfolio files",
  143:                     author    => "Disk space allocated to user's Authoring Space",
  144:                  );
  145:     my ($currquota,$quotatype,$inststatus,$defquota) =
  146:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  147:     if ($longinsttype eq '') {
  148:         if ($inststatus ne '') {
  149:             if ($usertypes->{$inststatus} ne '') {
  150:                 $longinsttype = $usertypes->{$inststatus};
  151:             }
  152:         }
  153:     }
  154:     my ($showquota,$custom_on,$custom_off,$defaultinfo,$colspan);
  155:     $custom_on = ' ';
  156:     $custom_off = ' checked="checked" ';
  157:     $colspan = ' colspan="2"';
  158:     if ($quotatype eq 'custom') {
  159:         $custom_on = $custom_off;
  160:         $custom_off = ' ';
  161:         $showquota = $currquota;
  162:         if ($longinsttype eq '') {
  163:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
  164:                               .' MB.',$defquota);
  165:         } else {
  166:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
  167:                                " MB,[_2]as determined by the user's institutional".
  168:                                " affiliation ([_3]).",$defquota,'<br />',$longinsttype);
  169:         }
  170:     } else {
  171:         if ($longinsttype eq '') {
  172:             $defaultinfo = &mt('For this user, the default quota is [_1]'
  173:                               .' MB.',$defquota);
  174:         } else {
  175:             $defaultinfo = &mt("For this user, the default quota of [_1]".
  176:                                " MB,[_2]is determined by the user's institutional".
  177:                                " affiliation ([_3]).",$defquota,'<br />'.$longinsttype);
  178:         }
  179:     }
  180: 
  181:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  182:         $output .= '<tr class="LC_info_row">'."\n".
  183:                    '    <td'.$colspan.'>'.$titles{$name}.'</td>'."\n".
  184:                    '  </tr>'."\n".
  185:                    &Apache::loncommon::start_data_table_row()."\n".
  186:                    '  <td'.$colspan.'><span class="LC_nobreak">'.
  187:                    &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  188:                    $defaultinfo.'</td>'."\n".
  189:                    &Apache::loncommon::end_data_table_row()."\n".
  190:                    &Apache::loncommon::start_data_table_row()."\n".
  191:                    '<td'.$colspan.'><span class="LC_nobreak">'.$lt{'chqu'}.
  192:                    ': <label>'.
  193:                    '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  194:                    'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  195:                    ' /><span class="LC_nobreak">'.
  196:                    &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  197:                    '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  198:                    'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  199:                    ' />'.$lt{'cust'}.':</label>&nbsp;'.
  200:                    '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  201:                    'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  202:                    ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  203:                    &Apache::loncommon::end_data_table_row()."\n";
  204:     }
  205:     return $output;
  206: }
  207: 
  208: sub user_quota_js {
  209:     return  <<"END_SCRIPT";
  210: <script type="text/javascript">
  211: // <![CDATA[
  212: function quota_changes(caller,context) {
  213:     var customoff = document.getElementById('custom_'+context+'quota_off');
  214:     var customon = document.getElementById('custom_'+context+'quota_on');
  215:     var number = document.getElementById(context+'quota');
  216:     if (caller == "custom") {
  217:         if (customoff) {
  218:             if (customoff.checked) {
  219:                 number.value = "";
  220:             }
  221:         }
  222:     }
  223:     if (caller == "quota") {
  224:         if (customon) {
  225:             customon.checked = true;
  226:         }
  227:     }
  228:     return;
  229: }
  230: // ]]>
  231: </script>
  232: END_SCRIPT
  233: 
  234: }
  235: 
  236: sub set_custom_js {
  237:     return  <<"END_SCRIPT";
  238: 
  239: <script type="text/javascript">
  240: // <![CDATA[
  241: function toggleCustom(form,item,name) {
  242:     if (document.getElementById(item)) {
  243:         var divid = document.getElementById(item);
  244:         var radioname = form.elements[name];
  245:         if (radioname) {
  246:             if (radioname.length > 0) {
  247:                 var setvis;
  248:                 for (var i=0; i<radioname.length; i++) {
  249:                     if (radioname[i].checked == true) {
  250:                         if (radioname[i].value == 1) {
  251:                             divid.style.display = 'block';
  252:                             setvis = 1;
  253:                         }
  254:                         break;
  255:                     }
  256:                 }
  257:                 if (!setvis) {
  258:                     divid.style.display = 'none';
  259:                 }
  260:             }
  261:         }
  262:     }
  263:     return;
  264: }
  265: // ]]>
  266: </script>
  267: 
  268: END_SCRIPT
  269: 
  270: }
  271: 
  272: sub build_tools_display {
  273:     my ($ccuname,$ccdomain,$context) = @_;
  274:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  275:         $colspan,$isadv,%domconfig,@defaulteditors,@customeditors,@custommanagers,
  276:         @possmanagers);
  277:     my %lt = &Apache::lonlocal::texthash (
  278:                    'blog'       => "Personal User Blog",
  279:                    'aboutme'    => "Personal Information Page",
  280:                    'webdav'     => "WebDAV access to Authoring Spaces (https)",
  281:                    'editors'    => "Available Editors",
  282:                    'managers'   => "Co-authors who can add/revoke roles",
  283:                    'portfolio'  => "Personal User Portfolio",
  284:                    'portaccess' => "Portfolio Shareable",
  285:                    'timezone'   => "Can set Time Zone",
  286:                    'avai'       => "Available",
  287:                    'cusa'       => "availability",
  288:                    'chse'       => "Change setting",
  289:                    'usde'       => "Use default",
  290:                    'uscu'       => "Use custom",
  291:                    'official'   => 'Can request creation of official courses',
  292:                    'unofficial' => 'Can request creation of unofficial courses',
  293:                    'community'  => 'Can request creation of communities',
  294:                    'textbook'   => 'Can request creation of textbook courses',
  295:                    'placement'  => 'Can request creation of placement tests',
  296:                    'lti'        => 'Can request creation of LTI courses',
  297:                    'requestauthor'  => 'Can request author space',
  298:                    'edit'       => 'Standard editor (Edit)',
  299:                    'xml'        => 'Text editor (EditXML)',
  300:                    'daxe'       => 'Daxe editor (Daxe)',
  301:     );
  302:     $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  303:     if ($context eq 'requestcourses') {
  304:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  305:                       'requestcourses.official','requestcourses.unofficial',
  306:                       'requestcourses.community','requestcourses.textbook',
  307:                       'requestcourses.placement','requestcourses.lti');
  308:         @usertools = ('official','unofficial','community','textbook','placement','lti');
  309:         @options =('norequest','approval','autolimit','validate');
  310:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  311:         %reqtitles = &courserequest_titles();
  312:         %reqdisplay = &courserequest_display();
  313:         %domconfig =
  314:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  315:     } elsif ($context eq 'requestauthor') {
  316:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'requestauthor');
  317:         @usertools = ('requestauthor');
  318:         @options =('norequest','approval','automatic');
  319:         %reqtitles = &requestauthor_titles();
  320:         %reqdisplay = &requestauthor_display();
  321:         %domconfig =
  322:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  323:     } elsif ($context eq 'authordefaults') {
  324:         %domconfig =
  325:             &Apache::lonnet::get_dom('configuration',['quotas','authordefaults'],$ccdomain);
  326:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'tools.webdav',
  327:                                                     'authoreditors','authormanagers',
  328:                                                     'domcoord.author');
  329:         @usertools = ('webdav','editors','managers');
  330:         $colspan = ' colspan="2"';
  331:     } else {
  332:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  333:                           'tools.aboutme','tools.portfolio','tools.blog',
  334:                           'tools.timezone','tools.portaccess');
  335:         @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
  336:         $colspan = ' colspan="2"';
  337:     }
  338:     foreach my $item (@usertools) {
  339:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  340:             $currdisp,$custdisp,$custradio,$onclick,$customsty,$editorsty);
  341:         $cust_off = 'checked="checked" ';
  342:         $tool_on = 'checked="checked" ';
  343:         unless (($context eq 'authordefaults') && ($item ne 'webdav')) {
  344:             $curr_access =
  345:                 &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  346:                                                   $context,\%userenv,'',
  347:                                                   {'is_adv' => $isadv});
  348:         }
  349:         if ($context eq 'requestauthor') {
  350:             if ($userenv{$context} ne '') {
  351:                 $cust_on = ' checked="checked" ';
  352:                 $cust_off = '';
  353:             }
  354:         } elsif ($context eq 'authordefaults') {
  355:             if ($item eq 'editors') {
  356:                 if ($userenv{'author'.$item} ne '') {
  357:                     $cust_on = ' checked="checked" ';
  358:                     $cust_off = '';
  359:                 }
  360:             } elsif ($item eq 'webdav') {
  361:                 if ($userenv{'tools.'.$item} ne '') {
  362:                     $cust_on = ' checked="checked" ';
  363:                     $cust_off = '';
  364:                 }
  365:             }
  366:         } elsif ($userenv{$context.'.'.$item} ne '') {
  367:             $cust_on = ' checked="checked" ';
  368:             $cust_off = '';
  369:         }
  370:         if ($context eq 'requestcourses') {
  371:             if ($userenv{$context.'.'.$item} eq '') {
  372:                 $custom_access = &mt('Currently from default setting.');
  373:                 $customsty = ' style="display:none;"';
  374:             } else {
  375:                 $custom_access = &mt('Currently from custom setting.');
  376:                 $customsty = ' style="display:block;"';
  377:             }
  378:         } elsif ($context eq 'requestauthor') {
  379:             if ($userenv{$context} eq '') {
  380:                 $custom_access = &mt('Currently from default setting.');
  381:                 $customsty = ' style="display:none;"';
  382:             } else {
  383:                 $custom_access = &mt('Currently from custom setting.');
  384:                 $customsty = ' style="display:block;"';
  385:             }
  386:         } elsif ($item eq 'editors') {
  387:             if ($userenv{'author'.$item} eq '') {
  388:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
  389:                     @defaulteditors = @{$domconfig{'authordefaults'}{'editors'}};
  390:                 } else {
  391:                     @defaulteditors = ('edit','xml');
  392:                 }
  393:                 $custom_access = &mt('Can use: [_1]',
  394:                                                join(', ', map { $lt{$_} } @defaulteditors));
  395:                 $editorsty = ' style="display:none;"';
  396:             } else {
  397:                 $custom_access = &mt('Currently from custom setting.');
  398:                 foreach my $editor (split(/,/,$userenv{'author'.$item})) {
  399:                     if ($editor =~ /^(edit|daxe|xml)$/) {
  400:                         push(@customeditors,$editor);
  401:                     }
  402:                 }
  403:                 if (@customeditors) {
  404:                     if (@customeditors > 1) {
  405:                         $custom_access .= '<br /><span>';
  406:                     } else {
  407:                         $custom_access .= ' <span class="LC_nobreak">';
  408:                     }
  409:                     $custom_access .= &mt('Can use: [_1]',
  410:                                           join(', ', map { $lt{$_} } @customeditors)).
  411:                                       '</span>';
  412:                 } else {
  413:                     $custom_access .= ' '.&mt('No available editors');
  414:                 }
  415:                 $editorsty = ' style="display:block;"';
  416:             }
  417:         } elsif ($item eq 'managers') {
  418:             my %ca_roles = &Apache::lonnet::get_my_roles($ccuname,$ccdomain,undef,
  419:                                                          ['active','future'],['ca']);
  420:             if (keys(%ca_roles)) {
  421:                 foreach my $entry (sort(keys(%ca_roles))) {
  422:                     if ($entry =~ /^($match_username\:$match_domain):ca$/) {
  423:                         my $user = $1;
  424:                         unless ($user eq "$ccuname:$ccdomain") {
  425:                             push(@possmanagers,$user);
  426:                         }
  427:                     }
  428:                 }
  429:             }
  430:             if ($userenv{'author'.$item} eq '') {
  431:                 $custom_access = &mt('Currently author manages co-author roles');
  432:             } else {
  433:                 if (keys(%ca_roles)) {
  434:                     foreach my $user (split(/,/,$userenv{'author'.$item})) {
  435:                         if ($user =~ /^($match_username):($match_domain)$/) {
  436:                             if (exists($ca_roles{$user.':ca'})) {
  437:                                 unless ($user eq "$ccuname:$ccdomain") {
  438:                                     push(@custommanagers,$user);
  439:                                 }
  440:                             }
  441:                         }
  442:                     }
  443:                 }
  444:                 if (@custommanagers) {
  445:                     $custom_access = &mt('Co-authors who manage co-author roles: [_1]',
  446:                                          join(', ',@custommanagers));
  447:                 } else {
  448:                     $custom_access = &mt('Currently author manages co-author roles');
  449:                 }
  450:             }
  451:         } else {
  452:             my $current = $userenv{$context.'.'.$item};
  453:             if ($item eq 'webdav') {
  454:                 $current = $userenv{'tools.webdav'};
  455:             }
  456:             if ($current eq '') {
  457:                 $custom_access =
  458:                     &mt('Availability determined currently from default setting.');
  459:                 if (!$curr_access) {
  460:                     $tool_off = 'checked="checked" ';
  461:                     $tool_on = '';
  462:                 }
  463:                 $customsty = ' style="display:none;"';
  464:             } else {
  465:                 $custom_access =
  466:                     &mt('Availability determined currently from custom setting.');
  467:                 if ($current == 0) {
  468:                     $tool_off = 'checked="checked" ';
  469:                     $tool_on = '';
  470:                 }
  471:                 $customsty = ' style="display:block;"';
  472:             }
  473:         }
  474:         $output .= '  <tr class="LC_info_row">'."\n".
  475:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  476:                    '  </tr>'."\n".
  477:                    &Apache::loncommon::start_data_table_row()."\n";
  478:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  479:             my ($curroption,$currlimit);
  480:             my $envkey = $context.'.'.$item;
  481:             if ($context eq 'requestauthor') {
  482:                 $envkey = $context;
  483:             }
  484:             if ($userenv{$envkey} ne '') {
  485:                 $curroption = $userenv{$envkey};
  486:             } else {
  487:                 my (@inststatuses);
  488:                 if ($context eq 'requestcourses') {
  489:                     $curroption =
  490:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  491:                                                                       $isadv,$ccdomain,$item,
  492:                                                                       \@inststatuses,\%domconfig);
  493:                 } else {
  494:                      $curroption = 
  495:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  496:                                                                        $isadv,$ccdomain,undef,
  497:                                                                        \@inststatuses,\%domconfig);
  498:                 }
  499:             }
  500:             if (!$curroption) {
  501:                 $curroption = 'norequest';
  502:             }
  503:             my $name = 'crsreq_'.$item;
  504:             if ($context eq 'requestauthor') {
  505:                 $name = $item;
  506:             }
  507:             $onclick = ' onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');"';
  508:             if ($curroption =~ /^autolimit=(\d*)$/) {
  509:                 $currlimit = $1;
  510:                 if ($currlimit eq '') {
  511:                     $currdisp = &mt('Yes, automatic creation');
  512:                 } else {
  513:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  514:                 }
  515:             } else {
  516:                 $currdisp = $reqdisplay{$curroption};
  517:             }
  518:             $custdisp = '<fieldset id="customtext_'.$item.'"'.$customsty.'>';
  519:             foreach my $option (@options) {
  520:                 my $val = $option;
  521:                 if ($option eq 'norequest') {
  522:                     $val = 0;
  523:                 }
  524:                 if ($option eq 'validate') {
  525:                     my $canvalidate = 0;
  526:                     if (ref($validations{$item}) eq 'HASH') {
  527:                         if ($validations{$item}{'_custom_'}) {
  528:                             $canvalidate = 1;
  529:                         }
  530:                     }
  531:                     next if (!$canvalidate);
  532:                 }
  533:                 my $checked = '';
  534:                 if ($option eq $curroption) {
  535:                     $checked = ' checked="checked"';
  536:                 } elsif ($option eq 'autolimit') {
  537:                     if ($curroption =~ /^autolimit/) {
  538:                         $checked = ' checked="checked"';
  539:                     }
  540:                 }
  541:                 if ($option eq 'autolimit') {
  542:                     $custdisp .= '<br />';
  543:                 }
  544:                 $custdisp .= '<span class="LC_nobreak"><label>'.
  545:                              '<input type="radio" name="'.$name.'" '.
  546:                              'value="'.$val.'"'.$checked.' />'.
  547:                              $reqtitles{$option}.'</label>&nbsp;';
  548:                 if ($option eq 'autolimit') {
  549:                     $custdisp .= '<input type="text" name="'.$name.
  550:                                  '_limit" size="1" '.
  551:                                  'value="'.$currlimit.'" />&nbsp;'.
  552:                                  $reqtitles{'unlimited'}.'</span>';
  553:                 } else {
  554:                     $custdisp .= '</span>';
  555:                 }
  556:                 $custdisp .= ' ';
  557:             }
  558:             $custdisp .= '</fieldset>';
  559:             $custradio = '<br />'.$custdisp;
  560:         } elsif ($item eq 'editors') {
  561:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  562:                        &Apache::loncommon::end_data_table_row()."\n";
  563:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  564:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  565:                           '<td'.$colspan.'><span class="LC_nobreak">'.
  566:                           $lt{'chse'}.': <label>'.
  567:                           '<input type="radio" name="custom'.$item.'" value="0" '.
  568:                           $cust_off.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  569:                           $lt{'usde'}.'</label>'.('&nbsp;' x3).
  570:                           '<label><input type="radio" name="custom'.$item.'" value="1" '.
  571:                           $cust_on.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  572:                           $lt{'uscu'}.'</label></span><br />'.
  573:                           '<fieldset id="customtext_'.$item.'"'.$editorsty.'>';
  574:                 foreach my $editor ('edit','xml','daxe') {
  575:                     my $checked;
  576:                     if ($userenv{'author'.$item} eq '') {
  577:                         if (grep(/^\Q$editor\E$/,@defaulteditors)) {
  578:                             $checked = ' checked="checked"';
  579:                         }
  580:                     } elsif (grep(/^\Q$editor\E$/,@customeditors)) {
  581:                         $checked = ' checked="checked"';
  582:                     }
  583:                     $output .= '<span style="LC_nobreak"><label>'.
  584:                                '<input type="checkbox" name="custom_editor" '.
  585:                                'value="'.$editor.'"'.$checked.' />'.
  586:                                $lt{$editor}.'</label></span> ';
  587:                 }
  588:                 $output .= '</fieldset></td>'.
  589:                            &Apache::loncommon::end_data_table_row()."\n";
  590:             }
  591:         } elsif ($item eq 'managers') {
  592:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  593:                        &Apache::loncommon::end_data_table_row()."\n";
  594:             unless ((&Apache::lonnet::allowed('udp',$ccdomain)) ||
  595:                     (($userenv{'domcoord.author'} eq 'blocked') &&
  596:                      (($env{'user.name'} ne $ccuname) || ($env{'user.domain'} ne $ccdomain)))) {
  597:                 $output .=
  598:                     &Apache::loncommon::start_data_table_row()."\n".
  599:                     '<td'.$colspan.'>';
  600:                 if (@possmanagers) {
  601:                     $output .= &mt('Select manager(s)').': ';
  602:                     foreach my $user (@possmanagers) {
  603:                         my $checked;
  604:                         if (grep(/^\Q$user\E$/,@custommanagers)) {
  605:                             $checked = ' checked="checked"';
  606:                         }
  607:                         $output .= '<span style="LC_nobreak"><label>'.
  608:                                    '<input type="checkbox" name="custommanagers" '.
  609:                                    'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
  610:                                    $user.'</label></span> ';
  611:                     }
  612:                 } else {
  613:                     $output .= &mt('No co-author roles assignable as manager');
  614:                 }
  615:                 $output .= '</td>'.
  616:                            &Apache::loncommon::end_data_table_row()."\n";
  617:             }
  618:         } else {
  619:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  620:             my $name = $context.'_'.$item;
  621:             $onclick = 'onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');" ';
  622:             $custdisp = '<span class="LC_nobreak"><label>'.
  623:                         '<input type="radio" name="'.$name.'"'.
  624:                         ' value="1" '.$tool_on.$onclick.'/>'.&mt('On').'</label>&nbsp;<label>'.
  625:                         '<input type="radio" name="'.$name.'" value="0" '.
  626:                         $tool_off.$onclick.'/>'.&mt('Off').'</label></span>';
  627:             $custradio = '<span id="customtext_'.$item.'"'.$customsty.' class="LC_nobreak">'.
  628:                          '--'.$lt{'cusa'}.':&nbsp;'.$custdisp.'</span>';
  629:         }
  630:         unless (($item eq 'editors') || ($item eq 'managers')) {
  631:             $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  632:                        $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  633:                        &Apache::loncommon::end_data_table_row()."\n";
  634:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  635:                 $output .=
  636:                    &Apache::loncommon::start_data_table_row()."\n".
  637:                    '<td><span class="LC_nobreak">'.
  638:                    $lt{'chse'}.': <label>'.
  639:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  640:                    $cust_off.$onclick.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  641:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  642:                    $cust_on.$onclick.'/>'.$lt{'uscu'}.'</label></span>';
  643:                 if ($colspan) {
  644:                     $output .= '</td><td>';
  645:                 }
  646:                 $output .= $custradio.'</td>'.
  647:                            &Apache::loncommon::end_data_table_row()."\n";
  648:             }
  649:         }
  650:     }
  651:     return $output;
  652: }
  653: 
  654: sub coursereq_externaluser {
  655:     my ($ccuname,$ccdomain,$cdom) = @_;
  656:     my (@usertools,@options,%validations,%userenv,$output);
  657:     my %lt = &Apache::lonlocal::texthash (
  658:                    'official'   => 'Can request creation of official courses',
  659:                    'unofficial' => 'Can request creation of unofficial courses',
  660:                    'community'  => 'Can request creation of communities',
  661:                    'textbook'   => 'Can request creation of textbook courses',
  662:                    'placement'  => 'Can request creation of placement tests',
  663:     );
  664: 
  665:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  666:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  667:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  668:                       'reqcrsotherdom.placement');
  669:     @usertools = ('official','unofficial','community','textbook','placement');
  670:     @options = ('approval','validate','autolimit');
  671:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  672:     my $optregex = join('|',@options);
  673:     my %reqtitles = &courserequest_titles();
  674:     foreach my $item (@usertools) {
  675:         my ($curroption,$currlimit,$tooloff);
  676:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  677:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  678:             foreach my $req (@curr) {
  679:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  680:                     $curroption = $1;
  681:                     $currlimit = $2;
  682:                     last;
  683:                 }
  684:             }
  685:             if (!$curroption) {
  686:                 $curroption = 'norequest';
  687:                 $tooloff = ' checked="checked"';
  688:             }
  689:         } else {
  690:             $curroption = 'norequest';
  691:             $tooloff = ' checked="checked"';
  692:         }
  693:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  694:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  695:                   '<table><tr><td valign="top">'."\n".
  696:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  697:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  698:                   '</label></td>';
  699:         foreach my $option (@options) {
  700:             if ($option eq 'validate') {
  701:                 my $canvalidate = 0;
  702:                 if (ref($validations{$item}) eq 'HASH') {
  703:                     if ($validations{$item}{'_external_'}) {
  704:                         $canvalidate = 1;
  705:                     }
  706:                 }
  707:                 next if (!$canvalidate);
  708:             }
  709:             my $checked = '';
  710:             if ($option eq $curroption) {
  711:                 $checked = ' checked="checked"';
  712:             }
  713:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  714:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  715:                        '" value="'.$option.'"'.$checked.' />'.
  716:                        $reqtitles{$option}.'</label>';
  717:             if ($option eq 'autolimit') {
  718:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  719:                            $item.'_limit" size="1" '.
  720:                            'value="'.$currlimit.'" /></span>'.
  721:                            '<br />'.$reqtitles{'unlimited'};
  722:             } else {
  723:                 $output .= '</span>';
  724:             }
  725:             $output .= '</td>';
  726:         }
  727:         $output .= '</td></tr></table></td>'."\n".
  728:                    &Apache::loncommon::end_data_table_row()."\n";
  729:     }
  730:     return $output;
  731: }
  732: 
  733: sub domainrole_req {
  734:     my ($ccuname,$ccdomain) = @_;
  735:     return '<br /><h3>'.
  736:            &mt('Can Request Assignment of Domain Roles?').
  737:            '</h3>'."\n".
  738:            &Apache::loncommon::start_data_table().
  739:            &build_tools_display($ccuname,$ccdomain,
  740:                                 'requestauthor').
  741:            &Apache::loncommon::end_data_table();
  742: }
  743: 
  744: sub authoring_defaults {
  745:     my ($ccuname,$ccdomain) = @_;
  746:     return '<br /><h3>'.
  747:            &mt('Authoring Space defaults (if role assigned)').
  748:            '</h3>'."\n".
  749:            &Apache::loncommon::start_data_table().
  750:            &build_tools_display($ccuname,$ccdomain,
  751:                                 'authordefaults').
  752:            &user_quotas($ccuname,$ccdomain,'author').
  753:            &Apache::loncommon::end_data_table();
  754: }
  755: 
  756: sub courserequest_titles {
  757:     my %titles = &Apache::lonlocal::texthash (
  758:                                    official   => 'Official',
  759:                                    unofficial => 'Unofficial',
  760:                                    community  => 'Communities',
  761:                                    textbook   => 'Textbook',
  762:                                    placement  => 'Placement Tests',
  763:                                    lti        => 'LTI Provider',
  764:                                    norequest  => 'Not allowed',
  765:                                    approval   => 'Approval by Dom. Coord.',
  766:                                    validate   => 'With validation',
  767:                                    autolimit  => 'Numerical limit',
  768:                                    unlimited  => '(blank for unlimited)',
  769:                  );
  770:     return %titles;
  771: }
  772: 
  773: sub courserequest_display {
  774:     my %titles = &Apache::lonlocal::texthash (
  775:                                    approval   => 'Yes, need approval',
  776:                                    validate   => 'Yes, with validation',
  777:                                    norequest  => 'No',
  778:    );
  779:    return %titles;
  780: }
  781: 
  782: sub requestauthor_titles {
  783:     my %titles = &Apache::lonlocal::texthash (
  784:                                    norequest  => 'Not allowed',
  785:                                    approval   => 'Approval by Dom. Coord.',
  786:                                    automatic  => 'Automatic approval',
  787:                  );
  788:     return %titles;
  789: 
  790: }
  791: 
  792: sub requestauthor_display {
  793:     my %titles = &Apache::lonlocal::texthash (
  794:                                    approval   => 'Yes, need approval',
  795:                                    automatic  => 'Yes, automatic approval',
  796:                                    norequest  => 'No',
  797:    );
  798:    return %titles;
  799: }
  800: 
  801: sub requestchange_display {
  802:     my %titles = &Apache::lonlocal::texthash (
  803:                                    approval   => "availability set to 'on' (approval required)", 
  804:                                    automatic  => "availability set to 'on' (automatic approval)",
  805:                                    norequest  => "availability set to 'off'",
  806:    );
  807:    return %titles;
  808: }
  809: 
  810: sub curr_requestauthor {
  811:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  812:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  813:     if ($uname eq '' || $udom eq '') {
  814:         $uname = $env{'user.name'};
  815:         $udom = $env{'user.domain'};
  816:         $isadv = $env{'user.adv'};
  817:     }
  818:     my (%userenv,%settings,$val);
  819:     my @options = ('automatic','approval');
  820:     %userenv =
  821:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  822:     if ($userenv{'requestauthor'}) {
  823:         $val = $userenv{'requestauthor'};
  824:         @{$inststatuses} = ('_custom_');
  825:     } else {
  826:         my %alltasks;
  827:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  828:             %settings = %{$domconfig->{'requestauthor'}};
  829:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  830:                 $val = $settings{'_LC_adv'};
  831:                 @{$inststatuses} = ('_LC_adv_');
  832:             } else {
  833:                 if ($userenv{'inststatus'} ne '') {
  834:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  835:                 } else {
  836:                     @{$inststatuses} = ('default');
  837:                 }
  838:                 foreach my $status (@{$inststatuses}) {
  839:                     if (exists($settings{$status})) {
  840:                         my $value = $settings{$status};
  841:                         next unless ($value);
  842:                         unless (exists($alltasks{$value})) {
  843:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  844:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  845:                                     push(@{$alltasks{$value}},$status);
  846:                                 }
  847:                             } else {
  848:                                 @{$alltasks{$value}} = ($status);
  849:                             }
  850:                         }
  851:                     }
  852:                 }
  853:                 foreach my $option (@options) {
  854:                     if ($alltasks{$option}) {
  855:                         $val = $option;
  856:                         last;
  857:                     }
  858:                 }
  859:             }
  860:         }
  861:     }
  862:     return $val;
  863: }
  864: 
  865: # =================================================================== Phase one
  866: 
  867: sub print_username_entry_form {
  868:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  869:         $permission) = @_;
  870:     my $defdom=$env{'request.role.domain'};
  871:     my $formtoset = 'crtuser';
  872:     if (exists($env{'form.startrolename'})) {
  873:         $formtoset = 'docustom';
  874:         $env{'form.rolename'} = $env{'form.startrolename'};
  875:     } elsif ($env{'form.origform'} eq 'crtusername') {
  876:         $formtoset =  $env{'form.origform'};
  877:     }
  878: 
  879:     my ($jsback,$elements) = &crumb_utilities();
  880: 
  881:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  882:         '<script type="text/javascript">'."\n".
  883:         '// <![CDATA['."\n".
  884:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  885:         '// ]]>'."\n".
  886:         '</script>'."\n";
  887: 
  888:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  889:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  890:         && (&Apache::lonnet::allowed('mcr','/'))) {
  891:         $jscript .= &customrole_javascript();
  892:     }
  893:     my $helpitem = 'Course_Change_Privileges';
  894:     if ($env{'form.action'} eq 'custom') {
  895:         if ($context eq 'course') {
  896:             $helpitem = 'Course_Editing_Custom_Roles';
  897:         } elsif ($context eq 'domain') {
  898:             $helpitem = 'Domain_Editing_Custom_Roles';
  899:         }
  900:     } elsif ($env{'form.action'} eq 'singlestudent') {
  901:         $helpitem = 'Course_Add_Student';
  902:     } elsif ($env{'form.action'} eq 'accesslogs') {
  903:         $helpitem = 'Domain_User_Access_Logs';
  904:     } elsif ($context eq 'author') {
  905:         $helpitem = 'Author_Change_Privileges';
  906:     } elsif ($context eq 'domain') {
  907:         if ($permission->{'cusr'}) {
  908:             $helpitem = 'Domain_Change_Privileges';
  909:         } elsif ($permission->{'view'}) {
  910:             $helpitem = 'Domain_View_Privileges';
  911:         } else {
  912:             undef($helpitem);
  913:         }
  914:     }
  915:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  916:     if ($env{'form.action'} eq 'custom') {
  917:         push(@{$brcrum},
  918:                  {href=>"javascript:backPage(document.crtuser)",       
  919:                   text=>"Pick custom role",
  920:                   help => $helpitem,}
  921:                  );
  922:     } else {
  923:         push (@{$brcrum},
  924:                   {href => "javascript:backPage(document.crtuser)",
  925:                    text => $breadcrumb_text{'search'},
  926:                    help => $helpitem,
  927:                    faq  => 282,
  928:                    bug  => 'Instructor Interface',}
  929:                   );
  930:     }
  931:     my %loaditems = (
  932:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  933:                     );
  934:     my $args = {bread_crumbs           => $brcrum,
  935:                 bread_crumbs_component => 'User Management',
  936:                 add_entries            => \%loaditems,};
  937:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  938: 
  939:     my %lt=&Apache::lonlocal::texthash(
  940:                     'srst' => 'Search for a user and enroll as a student',
  941:                     'srme' => 'Search for a user and enroll as a member',
  942:                     'srad' => 'Search for a user and modify/add user information or roles',
  943:                     'srvu' => 'Search for a user and view user information and roles',
  944:                     'srva' => 'Search for a user and view access log information',
  945: 		    'usr'  => "Username",
  946:                     'dom'  => "Domain",
  947:                     'ecrp' => "Define or Edit Custom Role",
  948:                     'nr'   => "role name",
  949:                     'cre'  => "Next",
  950: 				       );
  951: 
  952:     if ($env{'form.action'} eq 'custom') {
  953:         if (&Apache::lonnet::allowed('mcr','/')) {
  954:             my $newroletext = &mt('Define new custom role:');
  955:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  956:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  957:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  958:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  959:                       &Apache::loncommon::start_data_table().
  960:                       &Apache::loncommon::start_data_table_row().
  961:                       '<td>');
  962:             if (keys(%existingroles) > 0) {
  963:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  964:             } else {
  965:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  966:             }
  967:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  968:                       &Apache::loncommon::end_data_table_row());
  969:             if (keys(%existingroles) > 0) {
  970:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  971:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  972:                           &mt('View/Modify existing role:').'</b></label></td>'.
  973:                           '<td align="center"><br />'.
  974:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  975:                           '<option value="" selected="selected">'.
  976:                           &mt('Select'));
  977:                 foreach my $role (sort(keys(%existingroles))) {
  978:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  979:                 }
  980:                 $r->print('</select>'.
  981:                           '</td>'.
  982:                           &Apache::loncommon::end_data_table_row());
  983:             }
  984:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  985:                       '<input name="customeditor" type="submit" value="'.
  986:                       $lt{'cre'}.'" /></p>'.
  987:                       '</form>');
  988:         }
  989:     } else {
  990:         my $actiontext = $lt{'srad'};
  991:         my $fixeddom;
  992:         if ($env{'form.action'} eq 'singlestudent') {
  993:             if ($crstype eq 'Community') {
  994:                 $actiontext = $lt{'srme'};
  995:             } else {
  996:                 $actiontext = $lt{'srst'};
  997:             }
  998:         } elsif ($env{'form.action'} eq 'accesslogs') {
  999:             $actiontext = $lt{'srva'};
 1000:             $fixeddom = 1;
 1001:         } elsif (($env{'form.action'} eq 'singleuser') &&
 1002:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
 1003:             $actiontext = $lt{'srvu'};
 1004:             $fixeddom = 1;
 1005:         }
 1006:         $r->print("<h3>$actiontext</h3>");
 1007:         if ($env{'form.origform'} ne 'crtusername') {
 1008:             if ($response) {
 1009:                $r->print("\n<div>$response</div>".
 1010:                          '<br clear="all" />');
 1011:             }
 1012:         }
 1013:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
 1014:     }
 1015: }
 1016: 
 1017: sub customrole_javascript {
 1018:     my $js = <<"END";
 1019: <script type="text/javascript">
 1020: // <![CDATA[
 1021: 
 1022: function setCustomFields() {
 1023:     if (document.docustom.customroleaction.length > 0) {
 1024:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1025:             if (document.docustom.customroleaction[i].checked) {
 1026:                 if (document.docustom.customroleaction[i].value == 'new') {
 1027:                     document.docustom.rolename.selectedIndex = 0;
 1028:                 } else {
 1029:                     document.docustom.newrolename.value = '';
 1030:                 }
 1031:             }
 1032:         }
 1033:     }
 1034:     return;
 1035: }
 1036: 
 1037: function setCustomAction(caller) {
 1038:     if (document.docustom.customroleaction.length > 0) {
 1039:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1040:             if (document.docustom.customroleaction[i].value == caller) {
 1041:                 document.docustom.customroleaction[i].checked = true;
 1042:             }
 1043:         }
 1044:     }
 1045:     setCustomFields();
 1046:     return;
 1047: }
 1048: 
 1049: // ]]>
 1050: </script>
 1051: END
 1052:     return $js;
 1053: }
 1054: 
 1055: sub entry_form {
 1056:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
 1057:     my ($usertype,$inexact);
 1058:     if (ref($srch) eq 'HASH') {
 1059:         if (($srch->{'srchin'} eq 'dom') &&
 1060:             ($srch->{'srchby'} eq 'uname') &&
 1061:             ($srch->{'srchtype'} eq 'exact') &&
 1062:             ($srch->{'srchdomain'} ne '') &&
 1063:             ($srch->{'srchterm'} ne '')) {
 1064:             my (%curr_rules,%got_rules);
 1065:             my ($rules,$ruleorder) =
 1066:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
 1067:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
 1068:         } else {
 1069:             $inexact = 1;
 1070:         }
 1071:     }
 1072:     my ($cancreate,$noinstd);
 1073:     if ($env{'form.action'} eq 'accesslogs') {
 1074:         $noinstd = 1;
 1075:     } else {
 1076:         $cancreate =
 1077:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
 1078:     }
 1079:     my ($userpicker,$cansearch) = 
 1080:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
 1081:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
 1082:     my $srchbutton = &mt('Search');
 1083:     if ($env{'form.action'} eq 'singlestudent') {
 1084:         $srchbutton = &mt('Search and Enroll');
 1085:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1086:         $srchbutton = &mt('Search');
 1087:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
 1088:         $srchbutton = &mt('Search or Add New User');
 1089:     }
 1090:     my $output;
 1091:     if ($cansearch) {
 1092:         $output = <<"ENDBLOCK";
 1093: <form action="/adm/createuser" method="post" name="crtuser">
 1094: <input type="hidden" name="action" value="$env{'form.action'}" />
 1095: <input type="hidden" name="phase" value="get_user_info" />
 1096: $userpicker
 1097: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 1098: </form>
 1099: ENDBLOCK
 1100:     } else {
 1101:         $output = '<p>'.$userpicker.'</p>';
 1102:     }
 1103:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
 1104:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1105:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
 1106:         my $defdom=$env{'request.role.domain'};
 1107:         my ($trusted,$untrusted);
 1108:         if ($context eq 'course') {
 1109:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
 1110:         } elsif ($context eq 'author') {
 1111:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
 1112:         } elsif ($context eq 'domain') {
 1113:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
 1114:         }
 1115:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
 1116:         my %lt=&Apache::lonlocal::texthash(
 1117:                   'enro' => 'Enroll one student',
 1118:                   'enrm' => 'Enroll one member',
 1119:                   'admo' => 'Add/modify a single user',
 1120:                   'crea' => 'create new user if required',
 1121:                   'uskn' => "username is known",
 1122:                   'crnu' => 'Create a new user',
 1123:                   'usr'  => 'Username',
 1124:                   'dom'  => 'in domain',
 1125:                   'enrl' => 'Enroll',
 1126:                   'cram'  => 'Create/Modify user',
 1127:         );
 1128:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
 1129:         my ($title,$buttontext,$showresponse);
 1130:         if ($env{'form.action'} eq 'singlestudent') {
 1131:             if ($crstype eq 'Community') {
 1132:                 $title = $lt{'enrm'};
 1133:             } else {
 1134:                 $title = $lt{'enro'};
 1135:             }
 1136:             $buttontext = $lt{'enrl'};
 1137:         } else {
 1138:             $title = $lt{'admo'};
 1139:             $buttontext = $lt{'cram'};
 1140:         }
 1141:         if ($cancreate) {
 1142:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
 1143:         } else {
 1144:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
 1145:         }
 1146:         if ($env{'form.origform'} eq 'crtusername') {
 1147:             $showresponse = $responsemsg;
 1148:         }
 1149:         $output .= <<"ENDDOCUMENT";
 1150: <br />
 1151: <form action="/adm/createuser" method="post" name="crtusername">
 1152: <input type="hidden" name="action" value="$env{'form.action'}" />
 1153: <input type="hidden" name="phase" value="createnewuser" />
 1154: <input type="hidden" name="srchtype" value="exact" />
 1155: <input type="hidden" name="srchby" value="uname" />
 1156: <input type="hidden" name="srchin" value="dom" />
 1157: <input type="hidden" name="forcenewuser" value="1" />
 1158: <input type="hidden" name="origform" value="crtusername" />
 1159: <h3>$title</h3>
 1160: $showresponse
 1161: <table>
 1162:  <tr>
 1163:   <td>$lt{'usr'}:</td>
 1164:   <td><input type="text" size="15" name="srchterm" /></td>
 1165:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
 1166:   <td>&nbsp;$sellink&nbsp;</td>
 1167:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
 1168:  </tr>
 1169: </table>
 1170: </form>
 1171: ENDDOCUMENT
 1172:     }
 1173:     return $output;
 1174: }
 1175: 
 1176: sub user_modification_js {
 1177:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1178:     
 1179:     return <<END;
 1180: <script type="text/javascript" language="Javascript">
 1181: // <![CDATA[
 1182: 
 1183:     $pjump_def
 1184:     $dc_setcourse_code
 1185: 
 1186:     function dateset() {
 1187:         eval("document.cu."+document.cu.pres_marker.value+
 1188:             ".value=document.cu.pres_value.value");
 1189:         modalWindow.close();
 1190:     }
 1191: 
 1192:     $nondc_setsection_code
 1193: // ]]>
 1194: </script>
 1195: END
 1196: }
 1197: 
 1198: # =================================================================== Phase two
 1199: sub print_user_selection_page {
 1200:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1201:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1202:     my $sortby = $env{'form.sortby'};
 1203: 
 1204:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1205:         $sortby = 'lastname';
 1206:     }
 1207: 
 1208:     my ($jsback,$elements) = &crumb_utilities();
 1209: 
 1210:     my $jscript = (<<ENDSCRIPT);
 1211: <script type="text/javascript">
 1212: // <![CDATA[
 1213: function pickuser(uname,udom) {
 1214:     document.usersrchform.seluname.value=uname;
 1215:     document.usersrchform.seludom.value=udom;
 1216:     document.usersrchform.phase.value="userpicked";
 1217:     document.usersrchform.submit();
 1218: }
 1219: 
 1220: $jsback
 1221: // ]]>
 1222: </script>
 1223: ENDSCRIPT
 1224: 
 1225:     my %lt=&Apache::lonlocal::texthash(
 1226:                                        'usrch'          => "User Search to add/modify roles",
 1227:                                        'stusrch'        => "User Search to enroll student",
 1228:                                        'memsrch'        => "User Search to enroll member",
 1229:                                        'srcva'          => "Search for a user and view access log information",
 1230:                                        'usrvu'          => "User Search to view user roles",
 1231:                                        'usel'           => "Select a user to add/modify roles",
 1232:                                        'suvr'           => "Select a user to view roles",
 1233:                                        'stusel'         => "Select a user to enroll as a student",
 1234:                                        'memsel'         => "Select a user to enroll as a member",
 1235:                                        'vacsel'         => "Select a user to view access log",
 1236:                                        'username'       => "username",
 1237:                                        'domain'         => "domain",
 1238:                                        'lastname'       => "last name",
 1239:                                        'firstname'      => "first name",
 1240:                                        'permanentemail' => "permanent e-mail",
 1241:                                       );
 1242:     if ($context eq 'requestcrs') {
 1243:         $r->print('<div>');
 1244:     } else {
 1245:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1246:         my $helpitem;
 1247:         if ($env{'form.action'} eq 'singleuser') {
 1248:             $helpitem = 'Course_Change_Privileges';
 1249:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1250:             $helpitem = 'Course_Add_Student';
 1251:         } elsif ($context eq 'author') {
 1252:             $helpitem = 'Author_Change_Privileges';
 1253:         } elsif ($context eq 'domain') {
 1254:             $helpitem = 'Domain_Change_Privileges';
 1255:         }
 1256:         push (@{$brcrum},
 1257:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1258:                    text => $breadcrumb_text{'search'},
 1259:                    faq  => 282,
 1260:                    bug  => 'Instructor Interface',},
 1261:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1262:                    text => $breadcrumb_text{'userpicked'},
 1263:                    faq  => 282,
 1264:                    bug  => 'Instructor Interface',
 1265:                    help => $helpitem}
 1266:                   );
 1267:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1268:         if ($env{'form.action'} eq 'singleuser') {
 1269:             my $readonly;
 1270:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1271:                 $readonly = 1;
 1272:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1273:             } else {
 1274:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1275:             }
 1276:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1277:             if ($readonly) {
 1278:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1279:             } else {
 1280:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1281:             }
 1282:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1283:             $r->print($jscript."<b>");
 1284:             if ($crstype eq 'Community') {
 1285:                 $r->print($lt{'memsrch'});
 1286:             } else {
 1287:                 $r->print($lt{'stusrch'});
 1288:             }
 1289:             $r->print("</b><br />");
 1290:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1291:             $r->print('</form><h3>');
 1292:             if ($crstype eq 'Community') {
 1293:                 $r->print($lt{'memsel'});
 1294:             } else {
 1295:                 $r->print($lt{'stusel'});
 1296:             }
 1297:             $r->print('</h3>');
 1298:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1299:             $r->print("<b>$lt{'srcva'}</b><br />");
 1300:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1301:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1302:         }
 1303:     }
 1304:     $r->print('<form name="usersrchform" method="post" action="">'.
 1305:               &Apache::loncommon::start_data_table()."\n".
 1306:               &Apache::loncommon::start_data_table_header_row()."\n".
 1307:               ' <th> </th>'."\n");
 1308:     foreach my $field (@fields) {
 1309:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1310:                   "'".$field."'".';document.usersrchform.submit();">'.
 1311:                   $lt{$field}.'</a></th>'."\n");
 1312:     }
 1313:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1314: 
 1315:     my @sorted_users = sort {
 1316:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1317:             ||
 1318:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1319:             ||
 1320:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1321: 	    ||
 1322: 	lc($a) cmp lc($b)
 1323:         } (keys(%$srch_results));
 1324: 
 1325:     foreach my $user (@sorted_users) {
 1326:         my ($uname,$udom) = split(/:/,$user);
 1327:         my $onclick;
 1328:         if ($context eq 'requestcrs') {
 1329:             $onclick =
 1330:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1331:                                                "'$srch_results->{$user}->{firstname}',".
 1332:                                                "'$srch_results->{$user}->{lastname}',".
 1333:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1334:         } else {
 1335:             $onclick =
 1336:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1337:         }
 1338:         $r->print(&Apache::loncommon::start_data_table_row().
 1339:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1340:                   $onclick.' /></td>'.
 1341:                   '<td><tt>'.$uname.'</tt></td>'.
 1342:                   '<td><tt>'.$udom.'</tt></td>');
 1343:         foreach my $field ('lastname','firstname','permanentemail') {
 1344:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1345:         }
 1346:         $r->print(&Apache::loncommon::end_data_table_row());
 1347:     }
 1348:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1349:     if (ref($srcharray) eq 'ARRAY') {
 1350:         foreach my $item (@{$srcharray}) {
 1351:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1352:         }
 1353:     }
 1354:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1355:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1356:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1357:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1358:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1359:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1360:     if ($context eq 'requestcrs') {
 1361:         $r->print($opener_elements.'</form></div>');
 1362:     } else {
 1363:         $r->print($response.'</form>');
 1364:     }
 1365: }
 1366: 
 1367: sub print_user_query_page {
 1368:     my ($r,$caller,$brcrum) = @_;
 1369: # FIXME - this is for a network-wide name search (similar to catalog search)
 1370: # To use frames with similar behavior to catalog/portfolio search.
 1371: # To be implemented. 
 1372:     return;
 1373: }
 1374: 
 1375: sub print_user_modification_page {
 1376:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1377:         $brcrum,$showcredits) = @_;
 1378:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1379:         my $usermsg = &mt('No username and/or domain provided.');
 1380:         $env{'form.phase'} = '';
 1381: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1382:                                    $permission);
 1383:         return;
 1384:     }
 1385:     my ($form,$formname);
 1386:     if ($env{'form.action'} eq 'singlestudent') {
 1387:         $form = 'document.enrollstudent';
 1388:         $formname = 'enrollstudent';
 1389:     } else {
 1390:         $form = 'document.cu';
 1391:         $formname = 'cu';
 1392:     }
 1393:     my %abv_auth = &auth_abbrev();
 1394:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1395:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1396:     if ($uhome eq 'no_host') {
 1397:         my $usertype;
 1398:         my ($rules,$ruleorder) =
 1399:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1400:             $usertype =
 1401:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1402:                                                       \%curr_rules,\%got_rules);
 1403:         my $cancreate =
 1404:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1405:                                                    $usertype);
 1406:         if (!$cancreate) {
 1407:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1408:             my %usertypetext = (
 1409:                 official   => 'institutional',
 1410:                 unofficial => 'non-institutional',
 1411:             );
 1412:             my $response;
 1413:             if ($env{'form.origform'} eq 'crtusername') {
 1414:                 $response = '<span class="LC_warning">'.
 1415:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1416:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1417:                             '</span><br />';
 1418:             }
 1419:             $response .= '<p class="LC_warning">'
 1420:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1421:                         .' ';
 1422:             if ($context eq 'domain') {
 1423:                 $response .= &mt('Please contact a [_1] for assistance.',
 1424:                                  &Apache::lonnet::plaintext('dc'));
 1425:             } else {
 1426:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1427:                                 ,'<a href="'.$helplink.'">','</a>');
 1428:             }
 1429:             $response .= '</p><br />';
 1430:             $env{'form.phase'} = '';
 1431:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1432:                                        $permission);
 1433:             return;
 1434:         }
 1435:         $newuser = 1;
 1436:         my $checkhash;
 1437:         my $checks = { 'username' => 1 };
 1438:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1439:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1440:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1441:         if (ref($alerts{'username'}) eq 'HASH') {
 1442:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1443:                 my $domdesc =
 1444:                     &Apache::lonnet::domain($ccdomain,'description');
 1445:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1446:                     my $userchkmsg;
 1447:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1448:                         $userchkmsg = 
 1449:                             &Apache::loncommon::instrule_disallow_msg('username',
 1450:                                                                  $domdesc,1).
 1451:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1452:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1453:                             'username');
 1454:                     }
 1455:                     $env{'form.phase'} = '';
 1456:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1457:                                                $permission);
 1458:                     return;
 1459:                 }
 1460:             }
 1461:         }
 1462:     } else {
 1463:         $newuser = 0;
 1464:     }
 1465:     if ($response) {
 1466:         $response = '<br />'.$response;
 1467:     }
 1468: 
 1469:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1470:     my $dc_setcourse_code = '';
 1471:     my $nondc_setsection_code = '';                                        
 1472:     my %loaditem;
 1473: 
 1474:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1475: 
 1476:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1477:                                     $crstype,$groupslist,$newuser,
 1478:                                     $formname,\%loaditem,$permission);
 1479:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1480:     my $helpitem = 'Course_Change_Privileges';
 1481:     if ($env{'form.action'} eq 'singlestudent') {
 1482:         $helpitem = 'Course_Add_Student';
 1483:     } elsif ($context eq 'author') {
 1484:         $helpitem = 'Author_Change_Privileges';
 1485:     } elsif ($context eq 'domain') {
 1486:         $helpitem = 'Domain_Change_Privileges';
 1487:         $js .= &set_custom_js();
 1488:     }
 1489:     push (@{$brcrum},
 1490:         {href => "javascript:backPage($form)",
 1491:          text => $breadcrumb_text{'search'},
 1492:          faq  => 282,
 1493:          bug  => 'Instructor Interface',});
 1494:     if ($env{'form.phase'} eq 'userpicked') {
 1495:        push(@{$brcrum},
 1496:               {href => "javascript:backPage($form,'get_user_info','select')",
 1497:                text => $breadcrumb_text{'userpicked'},
 1498:                faq  => 282,
 1499:                bug  => 'Instructor Interface',});
 1500:     }
 1501:     push(@{$brcrum},
 1502:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1503:              text => $breadcrumb_text{'modify'},
 1504:              faq  => 282,
 1505:              bug  => 'Instructor Interface',
 1506:              help => $helpitem});
 1507:     my $args = {'add_entries'           => \%loaditem,
 1508:                 'bread_crumbs'          => $brcrum,
 1509:                 'bread_crumbs_component' => 'User Management'};
 1510:     if ($env{'form.popup'}) {
 1511:         $args->{'no_nav_bar'} = 1;
 1512:     }
 1513:     if (($context eq 'domain') && ($env{'request.role.domain'} eq $ccdomain)) {
 1514:         my @toggles;
 1515:         if (&Apache::lonnet::allowed('cau',$ccdomain)) {
 1516:             my ($isadv,$isauthor) =
 1517:                 &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1518:             unless ($isauthor) {
 1519:                 push(@toggles,'requestauthor');
 1520:             }
 1521:             push(@toggles,('webdav','editors'));
 1522:         }
 1523:         if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1524:             push(@toggles,('aboutme','blog','portfolio','portaccess','timezone'));
 1525:         }
 1526:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1527:             push(@toggles,('official','unofficial','community','textbook','placement','lti'));
 1528:         }
 1529:         if (@toggles) {
 1530:             my $onload;
 1531:             foreach my $item (@toggles) {
 1532:                 $onload .= "toggleCustom(document.cu,'customtext_$item','custom$item');";
 1533:             }
 1534:             $args->{'add_entries'} = {
 1535:                                        'onload' => $onload,
 1536:                                      };
 1537:         }
 1538:     }
 1539:     my $start_page =
 1540:         &Apache::loncommon::start_page('User Management',$js,$args);
 1541: 
 1542:     my $forminfo =<<"ENDFORMINFO";
 1543: <form action="/adm/createuser" method="post" name="$formname">
 1544: <input type="hidden" name="phase" value="update_user_data" />
 1545: <input type="hidden" name="ccuname" value="$ccuname" />
 1546: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1547: <input type="hidden" name="pres_value"  value="" />
 1548: <input type="hidden" name="pres_type"   value="" />
 1549: <input type="hidden" name="pres_marker" value="" />
 1550: ENDFORMINFO
 1551:     my (%inccourses,$roledom,$defaultcredits);
 1552:     if ($context eq 'course') {
 1553:         $inccourses{$env{'request.course.id'}}=1;
 1554:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1555:         if ($showcredits) {
 1556:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1557:         }
 1558:     } elsif ($context eq 'author') {
 1559:         $roledom = $env{'request.role.domain'};
 1560:     } elsif ($context eq 'domain') {
 1561:         foreach my $key (keys(%env)) {
 1562:             $roledom = $env{'request.role.domain'};
 1563:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1564:                 $inccourses{$1.'_'.$2}=1;
 1565:             }
 1566:         }
 1567:     } else {
 1568:         foreach my $key (keys(%env)) {
 1569: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1570: 	        $inccourses{$1.'_'.$2}=1;
 1571:             }
 1572:         }
 1573:     }
 1574:     my $title = '';
 1575:     my $need_quota_js;
 1576:     if ($newuser) {
 1577:         my ($portfolioform,$domroleform);
 1578:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1579:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1580:             # Current user has quota or user tools modification privileges
 1581:             $portfolioform = '<br /><h3>'.
 1582:                              &mt('User Tools').
 1583:                              '</h3>'."\n".
 1584:                              &Apache::loncommon::start_data_table();
 1585:             if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1586:                 $portfolioform .= &build_tools_display($ccuname,$ccdomain,'tools');
 1587:             }
 1588:             if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1589:                 $portfolioform .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1590:                 $need_quota_js = 1;
 1591:             }
 1592:             $portfolioform .= &Apache::loncommon::end_data_table();
 1593:         }
 1594:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1595:             ($ccdomain eq $env{'request.role.domain'})) {
 1596:             $domroleform = &domainrole_req($ccuname,$ccdomain).
 1597:                            &authoring_defaults($ccuname,$ccdomain);
 1598:             $need_quota_js = 1;
 1599:         }
 1600:         my $readonly;
 1601:         unless ($permission->{'cusr'}) {
 1602:             $readonly = 1;
 1603:         }
 1604:         &initialize_authen_forms($ccdomain,$formname,'','',$readonly);
 1605:         my %lt=&Apache::lonlocal::texthash(
 1606:                 'lg'             => 'Login Data',
 1607:                 'hs'             => "Home Server",
 1608:         );
 1609: 	$r->print(<<ENDTITLE);
 1610: $start_page
 1611: $response
 1612: $forminfo
 1613: <script type="text/javascript" language="Javascript">
 1614: // <![CDATA[
 1615: $loginscript
 1616: // ]]>
 1617: </script>
 1618: <input type='hidden' name='makeuser' value='1' />
 1619: ENDTITLE
 1620:         if ($env{'form.action'} eq 'singlestudent') {
 1621:             if ($crstype eq 'Community') {
 1622:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1623:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1624:             } else {
 1625:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1626:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1627:             }
 1628:         } else {
 1629:                 $title = &mt('Create New User [_1] in domain [_2]',
 1630:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1631:         }
 1632:         $r->print('<h2>'.$title.'</h2>'."\n");
 1633:         $r->print('<div class="LC_left_float">');
 1634:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1635:                                          $inst_results{$ccuname.':'.$ccdomain},$readonly));
 1636:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1637:         my ($home_server_pick,$numlib) = 
 1638:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1639:                                                       'default','hide');
 1640:         if ($numlib > 1) {
 1641:             $r->print("
 1642: <br />
 1643: $lt{'hs'}: $home_server_pick
 1644: <br />");
 1645:         } else {
 1646:             $r->print($home_server_pick);
 1647:         }
 1648:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1649:             $r->print('<br /><h3>'.
 1650:                       &mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1651:                       &Apache::loncommon::start_data_table().
 1652:                       &build_tools_display($ccuname,$ccdomain,
 1653:                                            'requestcourses').
 1654:                       &Apache::loncommon::end_data_table());
 1655:         }
 1656:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1657:                   $lt{'lg'}.'</h3>');
 1658:         my ($fixedauth,$varauth,$authmsg); 
 1659:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1660:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1661:             my ($rules,$ruleorder) = 
 1662:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1663:             if (ref($rules) eq 'HASH') {
 1664:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1665:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1666:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1667:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1668:                     } else { 
 1669:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1670:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1671:                         if ($authtype =~ /^krb(4|5)$/) {
 1672:                             my $ver = $1;
 1673:                             if ($authparm ne '') {
 1674:                                 $fixedauth = <<"KERB"; 
 1675: <input type="hidden" name="login" value="krb" />
 1676: <input type="hidden" name="krbver" value="$ver" />
 1677: <input type="hidden" name="krbarg" value="$authparm" />
 1678: KERB
 1679:                             }
 1680:                         } else {
 1681:                             $fixedauth = 
 1682: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1683:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1684:                                 $fixedauth .=    
 1685: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1686:                             } else {
 1687:                                 if ($authtype eq 'int') {
 1688:                                     $varauth = '<br />'.
 1689: &mt('[_1] Internally authenticated (with initial password [_2])','','<input type="password" size="10" name="intarg" value="" />')."<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 1690:                                 } elsif ($authtype eq 'loc') {
 1691:                                     $varauth = '<br />'.
 1692: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1693:                                 } else {
 1694:                                     $varauth =
 1695: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1696:                                 }
 1697:                             }
 1698:                         }
 1699:                     }
 1700:                 } else {
 1701:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1702:                 }
 1703:             }
 1704:             if ($authmsg) {
 1705:                 $r->print(<<ENDAUTH);
 1706: $fixedauth
 1707: $authmsg
 1708: $varauth
 1709: ENDAUTH
 1710:             }
 1711:         } else {
 1712:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1713:         }
 1714:         $r->print($portfolioform.$domroleform);
 1715:         if ($env{'form.action'} eq 'singlestudent') {
 1716:             $r->print(&date_sections_select($context,$newuser,$formname,
 1717:                                             $permission,$crstype,$ccuname,
 1718:                                             $ccdomain,$showcredits));
 1719:         }
 1720:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1721:     } else { # user already exists
 1722: 	$r->print($start_page.$forminfo);
 1723:         if ($env{'form.action'} eq 'singlestudent') {
 1724:             if ($crstype eq 'Community') {
 1725:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1726:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1727:             } else {
 1728:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1729:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1730:             }
 1731:         } else {
 1732:             if ($permission->{'cusr'}) {
 1733:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1734:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1735:             } else {
 1736:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1737:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1738:             }
 1739:         }
 1740:         $r->print('<h2>'.$title.'</h2>'."\n");
 1741:         $r->print('<div class="LC_left_float">');
 1742:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1743:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1744:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1745:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1746:             $r->print('<br /><h3>'.&mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1747:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1748:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1749:                 $r->print(&Apache::loncommon::start_data_table());
 1750:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1751:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1752:                 } else {
 1753:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1754:                                                       $env{'request.role.domain'}));
 1755:                 }
 1756:                 $r->print(&Apache::loncommon::end_data_table());
 1757:             } else {
 1758:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1759:                               &Apache::lonnet::domain($ccdomain,'description')));
 1760:             }
 1761:         }
 1762:         $r->print('</div>');
 1763:         my @order = ('auth','quota','tools','requestauthor','authordefaults');
 1764:         my %user_text;
 1765:         my ($isadv,$isauthor) = 
 1766:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1767:         if (((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1768:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1769:             ($env{'request.role.domain'} eq $ccdomain)) {
 1770:             if (!$isauthor) {
 1771:                 $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1772:             }
 1773:             $user_text{'authordefaults'} = &authoring_defaults($ccuname,$ccdomain);
 1774:             if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1775:                 $need_quota_js = 1;
 1776:             }
 1777:         }
 1778:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1779:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1780:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1781:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1782:             $user_text{'quota'} = '<br /><h3>'.&mt('User Tools').'</h3>'."\n".
 1783:                                   &Apache::loncommon::start_data_table();
 1784:             if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1785:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1786:                 $user_text{'quota'} .= &build_tools_display($ccuname,$ccdomain,'tools');
 1787:             }
 1788:             # Current user has quota modification privileges
 1789:             if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1790:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1791:                 $user_text{'quota'} .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1792:                 $need_quota_js = 1;
 1793:             }
 1794:             $user_text{'quota'} .= &Apache::loncommon::end_data_table();
 1795:         }
 1796:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1797:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1798:                 my %lt=&Apache::lonlocal::texthash(
 1799:                     'dska'  => "Disk quotas for user's portfolio",
 1800:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1801:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1802:                 );
 1803:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1804: <h3>$lt{'dska'}</h3>
 1805: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1806: ENDNOPORTPRIV
 1807:             }
 1808:         }
 1809:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1810:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1811:                 my %lt=&Apache::lonlocal::texthash(
 1812:                     'utav'  => "User Tools Availability",
 1813:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, Personal Information Page, or Time Zone settings for this user.",
 1814:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1815:                 );
 1816:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1817: <h3>$lt{'utav'}</h3>
 1818: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1819: ENDNOTOOLSPRIV
 1820:             }
 1821:         }
 1822:         my $gotdiv = 0; 
 1823:         foreach my $item (@order) {
 1824:             if ($user_text{$item} ne '') {
 1825:                 unless ($gotdiv) {
 1826:                     $r->print('<div class="LC_left_float">');
 1827:                     $gotdiv = 1;
 1828:                 }
 1829:                 $r->print('<br />'.$user_text{$item});
 1830:             }
 1831:         }
 1832:         if ($env{'form.action'} eq 'singlestudent') {
 1833:             unless ($gotdiv) {
 1834:                 $r->print('<div class="LC_left_float">');
 1835:             }
 1836:             my $credits;
 1837:             if ($showcredits) {
 1838:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1839:                 if ($credits eq '') {
 1840:                     $credits = $defaultcredits;
 1841:                 }
 1842:             }
 1843:             $r->print(&date_sections_select($context,$newuser,$formname,
 1844:                                             $permission,$crstype,$ccuname,
 1845:                                             $ccdomain,$showcredits));
 1846:         }
 1847:         if ($gotdiv) {
 1848:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1849:         }
 1850:         my $statuses;
 1851:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1852:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1853:             $statuses = ['active'];
 1854:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1855:                  ($env{'request.course.sec'} &&
 1856:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1857:             $statuses = ['active'];
 1858:         }
 1859:         if ($env{'form.action'} ne 'singlestudent') {
 1860:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1861:                                     $roledom,$crstype,$showcredits,$statuses);
 1862:         }
 1863:     } ## End of new user/old user logic
 1864:     if ($env{'form.action'} eq 'singlestudent') {
 1865:         my $btntxt;
 1866:         if ($crstype eq 'Community') {
 1867:             $btntxt = &mt('Enroll Member');
 1868:         } else {
 1869:             $btntxt = &mt('Enroll Student');
 1870:         }
 1871:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1872:     } elsif ($permission->{'cusr'}) {
 1873:         $r->print('<div class="LC_left_float">'.
 1874:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1875:         my $addrolesdisplay = 0;
 1876:         if ($context eq 'domain' || $context eq 'author') {
 1877:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1878:         }
 1879:         if ($context eq 'domain') {
 1880:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1881:             if (!$addrolesdisplay) {
 1882:                 $addrolesdisplay = $add_domainroles;
 1883:             }
 1884:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1885:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1886:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1887:         } elsif ($context eq 'author') {
 1888:             if ($addrolesdisplay) {
 1889:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1890:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1891:                 if ($newuser) {
 1892:                     $r->print(' onclick="auth_check()" \>'."\n");
 1893:                 } else {
 1894:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1895:                 }
 1896:             } else {
 1897:                 $r->print('</fieldset></div>'.
 1898:                           '<div class="LC_clear_float_footer"></div>'.
 1899:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1900:                           &mt('Back to previous page').'</a>');
 1901:             }
 1902:         } else {
 1903:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1904:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1905:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1906:         }
 1907:     }
 1908:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1909:     $r->print('<input type="hidden" name="currstate" value="" />');
 1910:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1911:     if ($need_quota_js) {
 1912:         $r->print(&user_quota_js());
 1913:     }
 1914:     return;
 1915: }
 1916: 
 1917: sub singleuser_breadcrumb {
 1918:     my ($crstype,$context,$domain) = @_;
 1919:     my %breadcrumb_text;
 1920:     if ($env{'form.action'} eq 'singlestudent') {
 1921:         if ($crstype eq 'Community') {
 1922:             $breadcrumb_text{'search'} = 'Enroll a member';
 1923:         } else {
 1924:             $breadcrumb_text{'search'} = 'Enroll a student';
 1925:         }
 1926:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1927:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1928:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1929:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1930:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1931:         $breadcrumb_text{'activity'} = 'Activity';
 1932:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1933:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1934:         $breadcrumb_text{'search'} = "View user's roles";
 1935:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1936:         $breadcrumb_text{'modify'} = 'User roles';
 1937:     } else {
 1938:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1939:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1940:         $breadcrumb_text{'modify'} = 'Set user role';
 1941:     }
 1942:     return %breadcrumb_text;
 1943: }
 1944: 
 1945: sub date_sections_select {
 1946:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1947:         $showcredits) = @_;
 1948:     my $credits;
 1949:     if ($showcredits) {
 1950:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1951:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1952:         if ($credits eq '') {
 1953:             $credits = $defaultcredits;
 1954:         }
 1955:     }
 1956:     my $cid = $env{'request.course.id'};
 1957:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1958:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1959:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1960:                                                   undef,$formname,$permission);
 1961:     my $rowtitle = 'Section';
 1962:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1963:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1964:                                               $permission,$context,'',$crstype,
 1965:                                               $showcredits,$credits);
 1966:     my $output = $date_table.$secbox;
 1967:     return $output;
 1968: }
 1969: 
 1970: sub validation_javascript {
 1971:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1972:         $loaditem,$permission) = @_;
 1973:     my $dc_setcourse_code = '';
 1974:     my $nondc_setsection_code = '';
 1975:     if ($context eq 'domain') {
 1976:         if ((ref($permission) eq 'HASH') && ($permission->{'cusr'})) {
 1977:             my $dcdom = $env{'request.role.domain'};
 1978:             $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1979:             $dc_setcourse_code =
 1980:                 &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1981:         }
 1982:     } else {
 1983:         my $checkauth; 
 1984:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1985:             $checkauth = 1;
 1986:         }
 1987:         if ($context eq 'course') {
 1988:             $nondc_setsection_code =
 1989:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1990:                                                               undef,$checkauth,
 1991:                                                               $crstype);
 1992:         }
 1993:         if ($checkauth) {
 1994:             $nondc_setsection_code .= 
 1995:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1996:         }
 1997:     }
 1998:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1999:                                    $nondc_setsection_code,$groupslist);
 2000:     my ($jsback,$elements) = &crumb_utilities();
 2001:     $js .= "\n".
 2002:            '<script type="text/javascript">'."\n".
 2003:            '// <![CDATA['."\n".
 2004:            $jsback."\n".
 2005:            '// ]]>'."\n".
 2006:            '</script>'."\n";
 2007:     return $js;
 2008: }
 2009: 
 2010: sub display_existing_roles {
 2011:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 2012:         $showcredits,$statuses) = @_;
 2013:     my $now=time;
 2014:     my $showall = 1;
 2015:     my ($showexpired,$showactive);
 2016:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 2017:         $showall = 0;
 2018:         if (grep(/^expired$/,@{$statuses})) {
 2019:             $showexpired = 1;
 2020:         }
 2021:         if (grep(/^active$/,@{$statuses})) {
 2022:             $showactive = 1;
 2023:         }
 2024:         if ($showexpired && $showactive) {
 2025:             $showall = 1;
 2026:         }
 2027:     }
 2028:     my %lt=&Apache::lonlocal::texthash(
 2029:                     'rer'  => "Existing Roles",
 2030:                     'rev'  => "Revoke",
 2031:                     'del'  => "Delete",
 2032:                     'ren'  => "Re-Enable",
 2033:                     'rol'  => "Role",
 2034:                     'ext'  => "Extent",
 2035:                     'crd'  => "Credits",
 2036:                     'sta'  => "Start",
 2037:                     'end'  => "End",
 2038:                                        );
 2039:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 2040:     if ($context eq 'course' || $context eq 'author') {
 2041:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 2042:         my %roleshash = 
 2043:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 2044:                               ['active','previous','future'],\@roles,$roledom,1);
 2045:         foreach my $key (keys(%roleshash)) {
 2046:             my ($start,$end) = split(':',$roleshash{$key});
 2047:             next if ($start eq '-1' || $end eq '-1');
 2048:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 2049:             if ($context eq 'course') {
 2050:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 2051:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 2052:             } elsif ($context eq 'author') {
 2053:                 if ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2054:                     my ($audom,$auname) = ($1,$2);
 2055:                     next unless (($rnum eq $auname) && ($rdom eq $audom));
 2056:                 } else {
 2057:                     next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 2058:                 }
 2059:             }
 2060:             my ($newkey,$newvalue,$newrole);
 2061:             $newkey = '/'.$rdom.'/'.$rnum;
 2062:             if ($sec ne '') {
 2063:                 $newkey .= '/'.$sec;
 2064:             }
 2065:             $newvalue = $role;
 2066:             if ($role =~ /^cr/) {
 2067:                 $newrole = 'cr';
 2068:             } else {
 2069:                 $newrole = $role;
 2070:             }
 2071:             $newkey .= '_'.$newrole;
 2072:             if ($start ne '' && $end ne '') {
 2073:                 $newvalue .= '_'.$end.'_'.$start;
 2074:             } elsif ($end ne '') {
 2075:                 $newvalue .= '_'.$end;
 2076:             }
 2077:             $rolesdump{$newkey} = $newvalue;
 2078:         }
 2079:     } else {
 2080:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 2081:     }
 2082:     # Build up table of user roles to allow revocation and re-enabling of roles.
 2083:     my ($tmp) = keys(%rolesdump);
 2084:     return if ($tmp =~ /^(con_lost|error)/i);
 2085:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 2086:                                 my $b1=join('_',(split('_',$b))[1,0]);
 2087:                                 return $a1 cmp $b1;
 2088:                             } keys(%rolesdump)) {
 2089:         next if ($area =~ /^rolesdef/);
 2090:         my $envkey=$area;
 2091:         my $role = $rolesdump{$area};
 2092:         my $thisrole=$area;
 2093:         $area =~ s/\_\w\w$//;
 2094:         my ($role_code,$role_end_time,$role_start_time) =
 2095:             split(/_/,$role);
 2096:         my $active=1;
 2097:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 2098:         if ($active) {
 2099:             next unless($showall || $showactive);
 2100:         } else {
 2101:             next unless($showall || $showexpired);
 2102:         }
 2103: # Is this a custom role? Get role owner and title.
 2104:         my ($croleudom,$croleuname,$croletitle)=
 2105:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 2106:         my $allowed=0;
 2107:         my $delallowed=0;
 2108:         my $sortkey=$role_code;
 2109:         my $class='Unknown';
 2110:         my $credits='';
 2111:         my $csec;
 2112:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 2113:             $class='Course';
 2114:             my ($coursedom,$coursedir) = ($1,$2);
 2115:             my $cid = $1.'_'.$2;
 2116:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 2117:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 2118:             my %coursedata=
 2119:                 &Apache::lonnet::coursedescription($cid);
 2120:             if ($coursedir =~ /^$match_community$/) {
 2121:                 $class='Community';
 2122:             }
 2123:             $sortkey.="\0$coursedom";
 2124:             my $carea;
 2125:             if (defined($coursedata{'description'})) {
 2126:                 $carea=$coursedata{'description'}.
 2127:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 2128:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 2129:                 $sortkey.="\0".$coursedata{'description'};
 2130:             } else {
 2131:                 if ($class eq 'Community') {
 2132:                     $carea=&mt('Unavailable community').': '.$area;
 2133:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 2134:                 } else {
 2135:                     $carea=&mt('Unavailable course').': '.$area;
 2136:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 2137:                 }
 2138:             }
 2139:             $sortkey.="\0$coursedir";
 2140:             $inccourses->{$cid}=1;
 2141:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 2142:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 2143:                 $credits =
 2144:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 2145:                                       $coursedom,$coursedir);
 2146:                 if ($credits eq '') {
 2147:                     $credits = $defaultcredits;
 2148:                 }
 2149:             }
 2150:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 2151:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2152:                 $allowed=1;
 2153:             }
 2154:             unless ($allowed) {
 2155:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 2156:                 if ($isowner) {
 2157:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 2158:                         $allowed = 1;
 2159:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 2160:                         $allowed = 1;
 2161:                     }
 2162:                 }
 2163:             } 
 2164:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 2165:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 2166:                 $delallowed=1;
 2167:             }
 2168: # - custom role. Needs more info, too
 2169:             if ($croletitle) {
 2170:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 2171:                     $allowed=1;
 2172:                     $thisrole.='.'.$role_code;
 2173:                 }
 2174:             }
 2175:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 2176:                 $csec = $2;
 2177:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 2178:                 $sortkey.="\0$csec";
 2179:                 if (!$allowed) {
 2180:                     if ($env{'request.course.sec'} eq $csec) {
 2181:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 2182:                             $allowed = 1;
 2183:                         }
 2184:                     }
 2185:                 }
 2186:             }
 2187:             $area=$carea;
 2188:         } else {
 2189:             $sortkey.="\0".$area;
 2190:             # Determine if current user is able to revoke privileges
 2191:             if ($area=~m{^/($match_domain)/}) {
 2192:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 2193:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2194:                    $allowed=1;
 2195:                 }
 2196:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 2197:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 2198:                     ($role_code ne 'dc')) {
 2199:                     $delallowed=1;
 2200:                 }
 2201:             } else {
 2202:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 2203:                     $allowed=1;
 2204:                 }
 2205:             }
 2206:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 2207:                 $class='Authoring Space';
 2208:             } elsif ($role_code eq 'su') {
 2209:                 $class='System';
 2210:             } else {
 2211:                 $class='Domain';
 2212:             }
 2213:         }
 2214:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 2215:             $area=~m{/($match_domain)/($match_username)};
 2216:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 2217:                 $allowed=1;
 2218:             } elsif (&Apache::lonuserutils::coauthorpriv($2,$1)) {
 2219:                 $allowed=1;
 2220:             } else {
 2221:                 $allowed=0;
 2222:             }
 2223:         }
 2224:         my $row = '';
 2225:         if ($showall) {
 2226:             $row.= '<td>';
 2227:             if (($active) && ($allowed)) {
 2228:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 2229:             } else {
 2230:                 if ($active) {
 2231:                     $row.='&nbsp;';
 2232:                 } else {
 2233:                     $row.=&mt('expired or revoked');
 2234:                 }
 2235:             }
 2236:             $row.='</td><td>';
 2237:             if ($allowed && !$active) {
 2238:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 2239:             } else {
 2240:                 $row.='&nbsp;';
 2241:             }
 2242:             $row.='</td><td>';
 2243:             if ($delallowed) {
 2244:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 2245:             } else {
 2246:                 $row.='&nbsp;';
 2247:             }
 2248:             $row.= '</td>';
 2249:         }
 2250:         my $plaintext='';
 2251:         if (!$croletitle) {
 2252:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2253:             if (($showcredits) && ($credits ne '')) {
 2254:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2255:                               '<span class="LC_fontsize_small">'.
 2256:                               &mt('Credits: [_1]',$credits).
 2257:                               '</span></span>';
 2258:             }
 2259:         } else {
 2260:             $plaintext=
 2261:                 &mt('Custom role [_1][_2]defined by [_3]',
 2262:                         '"'.$croletitle.'"',
 2263:                         '<br />',
 2264:                         $croleuname.':'.$croleudom);
 2265:         }
 2266:         $row.= '<td>'.$plaintext.'</td>'.
 2267:                '<td>'.$area.'</td>'.
 2268:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2269:                                             : '&nbsp;' ).'</td>'.
 2270:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2271:                                             : '&nbsp;' ).'</td>';
 2272:         $sortrole{$sortkey}=$envkey;
 2273:         $roletext{$envkey}=$row;
 2274:         $roleclass{$envkey}=$class;
 2275:         if ($allowed) {
 2276:             $rolepriv{$envkey}='edit';
 2277:         } else {
 2278:             if ($context eq 'domain') {
 2279:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2280:                     ($envkey=~m{^/$ccdomain/})) {
 2281:                     $rolepriv{$envkey}='view';
 2282:                 }
 2283:             } elsif ($context eq 'course') {
 2284:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2285:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2286:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2287:                     $rolepriv{$envkey}='view';
 2288:                 }
 2289:             }
 2290:         }
 2291:     } # end of foreach        (table building loop)
 2292: 
 2293:     my $rolesdisplay = 0;
 2294:     my %output = ();
 2295:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2296:         $output{$type} = '';
 2297:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2298:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2299:                  $output{$type}.=
 2300:                       &Apache::loncommon::start_data_table_row().
 2301:                       $roletext{$sortrole{$which}}.
 2302:                       &Apache::loncommon::end_data_table_row();
 2303:             }
 2304:         }
 2305:         unless($output{$type} eq '') {
 2306:             $output{$type} = '<tr class="LC_info_row">'.
 2307:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2308:                       $output{$type};
 2309:             $rolesdisplay = 1;
 2310:         }
 2311:     }
 2312:     if ($rolesdisplay == 1) {
 2313:         my $contextrole='';
 2314:         if ($env{'request.course.id'}) {
 2315:             if (&Apache::loncommon::course_type() eq 'Community') {
 2316:                 $contextrole = &mt('Existing Roles in this Community');
 2317:             } else {
 2318:                 $contextrole = &mt('Existing Roles in this Course');
 2319:             }
 2320:         } elsif ($env{'request.role'} =~ /^au\./) {
 2321:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2322:         } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)/$}) {
 2323:             $contextrole = &mt('Existing Co-Author Roles in [_1] Authoring Space',
 2324:                                '<i>'.$1.'_'.$2.'</i>');
 2325:         } else {
 2326:             if ($showall) {
 2327:                 $contextrole = &mt('Existing Roles in this Domain');
 2328:             } elsif ($showactive) {
 2329:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2330:             } elsif ($showexpired) {
 2331:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2332:             }
 2333:         }
 2334:         $r->print('<div class="LC_left_float">'.
 2335: '<fieldset><legend>'.$contextrole.'</legend>'.
 2336: &Apache::loncommon::start_data_table("LC_createuser").
 2337: &Apache::loncommon::start_data_table_header_row());
 2338:         if ($showall) {
 2339:             $r->print(
 2340: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2341:             );
 2342:         } elsif ($showexpired) {
 2343:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2344:         }
 2345:         $r->print(
 2346: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2347: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2348: &Apache::loncommon::end_data_table_header_row());
 2349:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2350:             if ($output{$type}) {
 2351:                 $r->print($output{$type}."\n");
 2352:             }
 2353:         }
 2354:         $r->print(&Apache::loncommon::end_data_table().
 2355:                   '</fieldset></div>');
 2356:     }
 2357:     return;
 2358: }
 2359: 
 2360: sub new_coauthor_roles {
 2361:     my ($r,$ccuname,$ccdomain) = @_;
 2362:     my $addrolesdisplay = 0;
 2363:     #
 2364:     # Co-Author
 2365:     #
 2366:     my ($cuname,$cudom);
 2367:     if (($env{'request.role'} eq "au./$env{'user.domain'}/") ||
 2368:         ($env{'request.role'} eq "dc./$env{'user.domain'}/")) {
 2369:         $cuname=$env{'user.name'};
 2370:         $cudom=$env{'request.role.domain'};
 2371:         # No sense in assigning co-author role to yourself
 2372:         if ((&Apache::lonuserutils::authorpriv($cuname,$cudom)) &&
 2373:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2374:             $addrolesdisplay = 1;
 2375:         }
 2376:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2377:         ($cudom,$cuname) = ($1,$2);
 2378:         if ((&Apache::lonuserutils::coauthorpriv($cuname,$cudom)) &&
 2379:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain) &&
 2380:             ($cudom ne $ccdomain || $cuname ne $ccuname)) {
 2381:             $addrolesdisplay = 1;
 2382:         }
 2383:     }
 2384:     if ($addrolesdisplay) {
 2385:         my %lt=&Apache::lonlocal::texthash(
 2386:                     'cs'   => "Authoring Space",
 2387:                     'act'  => "Activate",
 2388:                     'rol'  => "Role",
 2389:                     'ext'  => "Extent",
 2390:                     'sta'  => "Start",
 2391:                     'end'  => "End",
 2392:                     'cau'  => "Co-Author",
 2393:                     'caa'  => "Assistant Co-Author",
 2394:                     'ssd'  => "Set Start Date",
 2395:                     'sed'  => "Set End Date"
 2396:                                        );
 2397:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2398:                   &Apache::loncommon::start_data_table()."\n".
 2399:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2400:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2401:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2402:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2403:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2404:                   &Apache::loncommon::start_data_table_row().'
 2405:            <td>
 2406:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2407:            </td>
 2408:            <td>'.$lt{'cau'}.'</td>
 2409:            <td>'.$cudom.'_'.$cuname.'</td>
 2410:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2411:              <a href=
 2412: "javascript:pjump('."'date_start','Start Date Co-Author',document.cu.start_$cudom\_$cuname\_ca.value,'start_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2413: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2414: <a href=
 2415: "javascript:pjump('."'date_end','End Date Co-Author',document.cu.end_$cudom\_$cuname\_ca.value,'end_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
 2416:               &Apache::loncommon::end_data_table_row()."\n".
 2417:               &Apache::loncommon::start_data_table_row()."\n".
 2418: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2419: <td>'.$lt{'caa'}.'</td>
 2420: <td>'.$cudom.'_'.$cuname.'</td>
 2421: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2422: <a href=
 2423: "javascript:pjump('."'date_start','Start Date Assistant Co-Author',document.cu.start_$cudom\_$cuname\_aa.value,'start_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2424: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2425: <a href=
 2426: "javascript:pjump('."'date_end','End Date Assistant Co-Author',document.cu.end_$cudom\_$cuname\_aa.value,'end_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
 2427:              &Apache::loncommon::end_data_table_row()."\n".
 2428:              &Apache::loncommon::end_data_table());
 2429:     } elsif ($env{'request.role'} =~ /^au\./) {
 2430:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2431:                                                 $env{'request.role.domain'}))) {
 2432:             $r->print('<span class="LC_error">'.
 2433:                       &mt('You do not have privileges to assign co-author roles.').
 2434:                       '</span>');
 2435:         } elsif (($env{'user.name'} eq $ccuname) &&
 2436:              ($env{'user.domain'} eq $ccdomain)) {
 2437:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2438:         }
 2439:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2440:         if (!(&Apache::lonuserutils::coauthorpriv($2,$1))) {
 2441:             $r->print('<span class="LC_error">'.
 2442:                       &mt('You do not have privileges to assign co-author roles.').
 2443:                       '</span>');
 2444:         } elsif (($env{'user.name'} eq $ccuname) &&
 2445:              ($env{'user.domain'} eq $ccdomain)) {
 2446:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in an author area in Authoring Space in which you already have a co-author role is not permitted'));
 2447:         } elsif (($cudom eq $ccdomain) && ($cuname eq $ccuname)) {
 2448:             $r->print(&mt("Assigning a co-author or assistant co-author role to an Authoring Space's author is not permitted"));
 2449:         }
 2450:     }
 2451:     return $addrolesdisplay;;
 2452: }
 2453: 
 2454: sub new_domain_roles {
 2455:     my ($r,$ccdomain) = @_;
 2456:     my $addrolesdisplay = 0;
 2457:     #
 2458:     # Domain level
 2459:     #
 2460:     my $num_domain_level = 0;
 2461:     my $domaintext =
 2462:     '<h4>'.&mt('Domain Level').'</h4>'.
 2463:     &Apache::loncommon::start_data_table().
 2464:     &Apache::loncommon::start_data_table_header_row().
 2465:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2466:     &mt('Extent').'</th>'.
 2467:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2468:     &Apache::loncommon::end_data_table_header_row();
 2469:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2470:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2471:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2472:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2473:         foreach my $role (@allroles) {
 2474:             next if ($role eq 'ad');
 2475:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2476:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2477:                if ($role eq 'dc') {
 2478:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2479:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2480:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2481:                        next unless ($uintdom eq $intdom);
 2482:                    }
 2483:                }
 2484:                my $plrole=&Apache::lonnet::plaintext($role);
 2485:                my %lt=&Apache::lonlocal::texthash(
 2486:                     'ssd'  => "Set Start Date",
 2487:                     'sed'  => "Set End Date"
 2488:                                        );
 2489:                $num_domain_level ++;
 2490:                $domaintext .=
 2491: &Apache::loncommon::start_data_table_row().
 2492: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2493: <td>'.$plrole.'</td>
 2494: <td>'.$thisdomain.'</td>
 2495: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2496: <a href=
 2497: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2498: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2499: <a href=
 2500: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2501: &Apache::loncommon::end_data_table_row();
 2502:             }
 2503:         }
 2504:     }
 2505:     $domaintext.= &Apache::loncommon::end_data_table();
 2506:     if ($num_domain_level > 0) {
 2507:         $r->print($domaintext);
 2508:         $addrolesdisplay = 1;
 2509:     }
 2510:     return $addrolesdisplay;
 2511: }
 2512: 
 2513: sub user_authentication {
 2514:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2515:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2516:     my $outcome;
 2517:     my %lt=&Apache::lonlocal::texthash(
 2518:                    'err'   => "ERROR",
 2519:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2520:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2521:                    'sldb'  => "Please specify login data below",
 2522:                    'ld'    => "Login Data"
 2523:     );
 2524:     # Check for a bad authentication type
 2525:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2526:         # bad authentication scheme
 2527:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2528:             &initialize_authen_forms($ccdomain,$formname);
 2529: 
 2530:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2531:             $outcome = <<ENDBADAUTH;
 2532: <script type="text/javascript" language="Javascript">
 2533: // <![CDATA[
 2534: $loginscript
 2535: // ]]>
 2536: </script>
 2537: <span class="LC_error">$lt{'err'}:
 2538: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2539: <h3>$lt{'ld'}</h3>
 2540: $choices
 2541: ENDBADAUTH
 2542:         } else {
 2543:             # This user is not allowed to modify the user's
 2544:             # authentication scheme, so just notify them of the problem
 2545:             $outcome = <<ENDBADAUTH;
 2546: <span class="LC_error"> $lt{'err'}: 
 2547: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2548: </span>
 2549: ENDBADAUTH
 2550:         }
 2551:     } else { # Authentication type is valid
 2552:         
 2553:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2554:         my ($authformcurrent,$can_modify,@authform_others) =
 2555:             &modify_login_block($ccdomain,$currentauth);
 2556:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2557:             # Current user has login modification privileges
 2558:             $outcome =
 2559:                        '<script type="text/javascript" language="Javascript">'."\n".
 2560:                        '// <![CDATA['."\n".
 2561:                        $loginscript."\n".
 2562:                        '// ]]>'."\n".
 2563:                        '</script>'."\n".
 2564:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2565:                        &Apache::loncommon::start_data_table().
 2566:                        &Apache::loncommon::start_data_table_row().
 2567:                        '<td>'.$authformnop;
 2568:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2569:                 $outcome .= '</td>'."\n".
 2570:                             &Apache::loncommon::end_data_table_row().
 2571:                             &Apache::loncommon::start_data_table_row().
 2572:                             '<td>'.$authformcurrent.'</td>'.
 2573:                             &Apache::loncommon::end_data_table_row()."\n";
 2574:             } else {
 2575:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2576:                             &Apache::loncommon::end_data_table_row()."\n";
 2577:             }
 2578:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2579:                 foreach my $item (@authform_others) { 
 2580:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2581:                                 '<td>'.$item.'</td>'.
 2582:                                 &Apache::loncommon::end_data_table_row()."\n";
 2583:                 }
 2584:             }
 2585:             $outcome .= &Apache::loncommon::end_data_table();
 2586:         } else {
 2587:             if (($currentauth =~ /^internal:/) &&
 2588:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2589:                 $outcome = <<"ENDJS";
 2590: <script type="text/javascript">
 2591: // <![CDATA[
 2592: function togglePwd(form) {
 2593:     if (form.newintpwd.length) {
 2594:         if (document.getElementById('LC_ownersetpwd')) {
 2595:             for (var i=0; i<form.newintpwd.length; i++) {
 2596:                 if (form.newintpwd[i].checked) {
 2597:                     if (form.newintpwd[i].value == 1) {
 2598:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2599:                     } else {
 2600:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2601:                     }
 2602:                 }
 2603:             }
 2604:         }
 2605:     }
 2606: }
 2607: // ]]>
 2608: </script>
 2609: ENDJS
 2610: 
 2611:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2612:                             &Apache::loncommon::start_data_table().
 2613:                             &Apache::loncommon::start_data_table_row().
 2614:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2615:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2616:                             &mt('No').'</label>'.('&nbsp;'x2).
 2617:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2618:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2619:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2620:                             '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }" />'.&mt('Visible input').'</label></div></td>'.
 2621:                             &Apache::loncommon::end_data_table_row().
 2622:                             &Apache::loncommon::end_data_table();
 2623:             }
 2624:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2625:                 # Current user has rights to view domain preferences for user's domain
 2626:                 my $result;
 2627:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2628:                     my ($krbver,$krbrealm) = ($1,$2);
 2629:                     if ($krbrealm eq '') {
 2630:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2631:                     } else {
 2632:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2633:                                       $krbrealm,$krbver);
 2634:                     }
 2635:                 } elsif ($currentauth =~ /^internal:/) {
 2636:                     $result = &mt('Currently internally authenticated.');
 2637:                 } elsif ($currentauth =~ /^localauth:/) {
 2638:                     $result = &mt('Currently using local (institutional) authentication.');
 2639:                 } elsif ($currentauth =~ /^unix:/) {
 2640:                     $result = &mt('Currently Filesystem Authenticated.');
 2641:                 } elsif ($currentauth =~ /^lti:/) {
 2642:                     $result = &mt('Currently LTI authenticated.');
 2643:                 }
 2644:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2645:                            &Apache::loncommon::start_data_table().
 2646:                            &Apache::loncommon::start_data_table_row().
 2647:                            '<td>'.$result.'</td>'.
 2648:                            &Apache::loncommon::end_data_table_row()."\n".
 2649:                            &Apache::loncommon::end_data_table();
 2650:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2651:                 my %lt=&Apache::lonlocal::texthash(
 2652:                            'ccld'  => "Change Current Login Data",
 2653:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2654:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2655:                 );
 2656:                 $outcome .= <<ENDNOPRIV;
 2657: <h3>$lt{'ccld'}</h3>
 2658: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2659: <input type="hidden" name="login" value="nochange" />
 2660: ENDNOPRIV
 2661:             }
 2662:         }
 2663:     }  ## End of "check for bad authentication type" logic
 2664:     return $outcome;
 2665: }
 2666: 
 2667: sub modify_login_block {
 2668:     my ($dom,$currentauth) = @_;
 2669:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2670:     my ($authnum,%can_assign) =
 2671:         &Apache::loncommon::get_assignable_auth($dom);
 2672:     my ($authformcurrent,@authform_others,$show_override_msg);
 2673:     if ($currentauth=~/^krb(4|5):/) {
 2674:         $authformcurrent=$authformkrb;
 2675:         if ($can_assign{'int'}) {
 2676:             push(@authform_others,$authformint);
 2677:         }
 2678:         if ($can_assign{'loc'}) {
 2679:             push(@authform_others,$authformloc);
 2680:         }
 2681:         if ($can_assign{'lti'}) {
 2682:             push(@authform_others,$authformlti);
 2683:         }
 2684:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2685:             $show_override_msg = 1;
 2686:         }
 2687:     } elsif ($currentauth=~/^internal:/) {
 2688:         $authformcurrent=$authformint;
 2689:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2690:             push(@authform_others,$authformkrb);
 2691:         }
 2692:         if ($can_assign{'loc'}) {
 2693:             push(@authform_others,$authformloc);
 2694:         }
 2695:         if ($can_assign{'lti'}) {
 2696:             push(@authform_others,$authformlti);
 2697:         }
 2698:         if ($can_assign{'int'}) {
 2699:             $show_override_msg = 1;
 2700:         }
 2701:     } elsif ($currentauth=~/^unix:/) {
 2702:         $authformcurrent=$authformfsys;
 2703:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2704:             push(@authform_others,$authformkrb);
 2705:         }
 2706:         if ($can_assign{'int'}) {
 2707:             push(@authform_others,$authformint);
 2708:         }
 2709:         if ($can_assign{'loc'}) {
 2710:             push(@authform_others,$authformloc);
 2711:         }
 2712:         if ($can_assign{'lti'}) {
 2713:             push(@authform_others,$authformlti);
 2714:         }
 2715:         if ($can_assign{'fsys'}) {
 2716:             $show_override_msg = 1;
 2717:         }
 2718:     } elsif ($currentauth=~/^localauth:/) {
 2719:         $authformcurrent=$authformloc;
 2720:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2721:             push(@authform_others,$authformkrb);
 2722:         }
 2723:         if ($can_assign{'int'}) {
 2724:             push(@authform_others,$authformint);
 2725:         }
 2726:         if ($can_assign{'lti'}) {
 2727:             push(@authform_others,$authformlti);
 2728:         }
 2729:         if ($can_assign{'loc'}) {
 2730:             $show_override_msg = 1;
 2731:         }
 2732:     } elsif ($currentauth=~/^lti:/) {
 2733:         $authformcurrent=$authformlti;
 2734:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2735:             push(@authform_others,$authformkrb);
 2736:         }
 2737:         if ($can_assign{'int'}) {
 2738:             push(@authform_others,$authformint);
 2739:         }
 2740:         if ($can_assign{'loc'}) {
 2741:             push(@authform_others,$authformloc);
 2742:         }
 2743:     }
 2744:     if ($show_override_msg) {
 2745:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2746:                            '</td></tr>'."\n".
 2747:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2748:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2749:                            '<td align="right"><span class="LC_cusr_emph">'.
 2750:                             &mt('will override current values').
 2751:                             '</span></td></tr></table>';
 2752:     }
 2753:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2754: }
 2755: 
 2756: sub personal_data_display {
 2757:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$readonly,$rolesarray,$now,
 2758:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2759:     my ($output,%userenv,%canmodify,%canmodify_status,$disabled);
 2760:     my @userinfo = ('firstname','middlename','lastname','generation',
 2761:                     'permanentemail','id');
 2762:     my $rowcount = 0;
 2763:     my $editable = 0;
 2764:     my %textboxsize = (
 2765:                        firstname      => '15',
 2766:                        middlename     => '15',
 2767:                        lastname       => '15',
 2768:                        generation     => '5',
 2769:                        permanentemail => '25',
 2770:                        id             => '15',
 2771:                       );
 2772: 
 2773:     my %lt=&Apache::lonlocal::texthash(
 2774:                 'pd'             => "Personal Data",
 2775:                 'firstname'      => "First Name",
 2776:                 'middlename'     => "Middle Name",
 2777:                 'lastname'       => "Last Name",
 2778:                 'generation'     => "Generation",
 2779:                 'permanentemail' => "Permanent e-mail address",
 2780:                 'id'             => "Student/Employee ID",
 2781:                 'lg'             => "Login Data",
 2782:                 'inststatus'     => "Affiliation",
 2783:                 'email'          => 'E-mail address',
 2784:                 'valid'          => 'Validation',
 2785:                 'username'       => 'Username',
 2786:     );
 2787: 
 2788:     %canmodify_status =
 2789:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2790:                                                    ['inststatus'],$rolesarray);
 2791:     if (!$newuser) {
 2792:         # Get the users information
 2793:         %userenv = &Apache::lonnet::get('environment',
 2794:                    ['firstname','middlename','lastname','generation',
 2795:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2796:         %canmodify =
 2797:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2798:                                                        \@userinfo,$rolesarray);
 2799:     } elsif ($context eq 'selfcreate') {
 2800:         if ($newuser eq 'email') {
 2801:             if (ref($emailusername) eq 'HASH') {
 2802:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2803:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2804:                     @userinfo = ();
 2805:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2806:                         foreach my $field (@{$infofields}) { 
 2807:                             if ($emailusername->{$usertype}->{$field}) {
 2808:                                 push(@userinfo,$field);
 2809:                                 $canmodify{$field} = 1;
 2810:                                 unless ($textboxsize{$field}) {
 2811:                                     $textboxsize{$field} = 25;
 2812:                                 }
 2813:                                 unless ($lt{$field}) {
 2814:                                     $lt{$field} = $infotitles->{$field};
 2815:                                 }
 2816:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2817:                                     $lt{$field} .= '<b>*</b>';
 2818:                                 }
 2819:                             }
 2820:                         }
 2821:                     }
 2822:                 }
 2823:             }
 2824:         } else {
 2825:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2826:                                                $inst_results,$rolesarray);
 2827:         }
 2828:     } elsif ($readonly) {
 2829:         $disabled = ' disabled="disabled"';
 2830:     }
 2831: 
 2832:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2833:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2834:               &Apache::lonhtmlcommon::start_pick_box();
 2835:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2836:         my $size = 25;
 2837:         if ($condition) {
 2838:             if ($condition =~ /^\@[^\@]+$/) {
 2839:                 $size = 10;
 2840:             } else {
 2841:                 undef($condition);
 2842:             }
 2843:         } 
 2844:         if ($excluded) {
 2845:             unless ($excluded =~ /^\@[^\@]+$/) {
 2846:                 undef($condition);
 2847:             }
 2848:         }
 2849:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2850:                                                      'LC_oddrow_value')."\n".
 2851:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2852:         if ($condition) {
 2853:             $output .= $condition;
 2854:         } elsif ($excluded) {
 2855:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2856:                                                                      $excluded).'</span>';
 2857:         }
 2858:         if ($usernameset eq 'first') {
 2859:             $output .= '<br /><span style="font-size: smaller">';
 2860:             if ($condition) {
 2861:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2862:                                       $condition);
 2863:             } else {
 2864:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2865:             }
 2866:             $output .= '</span>';
 2867:         }
 2868:         $rowcount ++;
 2869:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2870:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2871:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2872:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2873:                                                     'LC_pick_box_title',
 2874:                                                     'LC_oddrow_value')."\n".
 2875:                    $upassone."\n".
 2876:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2877:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2878:                                                      'LC_pick_box_title',
 2879:                                                      'LC_oddrow_value')."\n".
 2880:                    $upasstwo.
 2881:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2882:         if ($usernameset eq 'free') {
 2883:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2884:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2885:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2886:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2887:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2888:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2889:                        &mt('No').'</label></span>'."\n".
 2890:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2891:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2892:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2893:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2894:             $rowcount ++;
 2895:         }
 2896:     }
 2897:     foreach my $item (@userinfo) {
 2898:         my $rowtitle = $lt{$item};
 2899:         my $hiderow = 0;
 2900:         if ($item eq 'generation') {
 2901:             $rowtitle = $genhelp.$rowtitle;
 2902:         }
 2903:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2904:         if ($newuser) {
 2905:             if (ref($inst_results) eq 'HASH') {
 2906:                 if ($inst_results->{$item} ne '') {
 2907:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2908:                 } else {
 2909:                     if ($context eq 'selfcreate') {
 2910:                         if ($canmodify{$item}) {
 2911:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2912:                             $editable ++;
 2913:                         } else {
 2914:                             $hiderow = 1;
 2915:                         }
 2916:                     } else {
 2917:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2918:                     }
 2919:                 }
 2920:             } else {
 2921:                 if ($context eq 'selfcreate') {
 2922:                     if ($canmodify{$item}) {
 2923:                         if ($newuser eq 'email') {
 2924:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2925:                         } else {
 2926:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2927:                         }
 2928:                         $editable ++;
 2929:                     } else {
 2930:                         $hiderow = 1;
 2931:                     }
 2932:                 } else {
 2933:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2934:                 }
 2935:             }
 2936:         } else {
 2937:             if ($canmodify{$item}) {
 2938:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2939:                 if (($item eq 'id') && (!$newuser)) {
 2940:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2941:                 }
 2942:             } else {
 2943:                 $row .= $userenv{$item};
 2944:             }
 2945:         }
 2946:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2947:         if (!$hiderow) {
 2948:             $output .= $row;
 2949:             $rowcount ++;
 2950:         }
 2951:     }
 2952:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2953:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2954:         if (ref($types) eq 'ARRAY') {
 2955:             if (@{$types} > 0) {
 2956:                 my ($hiderow,$shown);
 2957:                 if ($canmodify_status{'inststatus'}) {
 2958:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2959:                 } else {
 2960:                     if ($userenv{'inststatus'} eq '') {
 2961:                         $hiderow = 1;
 2962:                     } else {
 2963:                         my @showitems;
 2964:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2965:                             if (exists($usertypes->{$item})) {
 2966:                                 push(@showitems,$usertypes->{$item});
 2967:                             } else {
 2968:                                 push(@showitems,$item);
 2969:                             }
 2970:                         }
 2971:                         if (@showitems) {
 2972:                             $shown = join(', ',@showitems);
 2973:                         } else {
 2974:                             $hiderow = 1;
 2975:                         }
 2976:                     }
 2977:                 }
 2978:                 if (!$hiderow) {
 2979:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2980:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2981:                     if ($context eq 'selfcreate') {
 2982:                         $rowcount ++;
 2983:                     }
 2984:                     $output .= $row;
 2985:                 }
 2986:             }
 2987:         }
 2988:     }
 2989:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2990:         if ($captchaform) {
 2991:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2992:                                                          'LC_pick_box_title')."\n".
 2993:                        $captchaform."\n".'<br /><br />'.
 2994:                        &Apache::lonhtmlcommon::row_closure(1); 
 2995:             $rowcount ++;
 2996:         }
 2997:         if ($showsubmit) {
 2998:             my $submit_text = &mt('Create account');
 2999:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 3000:                        '<br /><input type="submit" name="createaccount" value="'.
 3001:                        $submit_text.'" />';
 3002:             if ($usertype ne '') {
 3003:                 $output .= '<input type="hidden" name="type" value="'.
 3004:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 3005:             }
 3006:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 3007:         }
 3008:     }
 3009:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 3010:     if (wantarray) {
 3011:         if ($context eq 'selfcreate') {
 3012:             return($output,$rowcount,$editable);
 3013:         } else {
 3014:             return $output;
 3015:         }
 3016:     } else {
 3017:         return $output;
 3018:     }
 3019: }
 3020: 
 3021: sub pick_inst_statuses {
 3022:     my ($curr,$usertypes,$types) = @_;
 3023:     my ($output,$rem,@currtypes);
 3024:     if ($curr ne '') {
 3025:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 3026:     }
 3027:     my $numinrow = 2;
 3028:     if (ref($types) eq 'ARRAY') {
 3029:         $output = '<table>';
 3030:         my $lastcolspan; 
 3031:         for (my $i=0; $i<@{$types}; $i++) {
 3032:             if (defined($usertypes->{$types->[$i]})) {
 3033:                 my $rem = $i%($numinrow);
 3034:                 if ($rem == 0) {
 3035:                     if ($i<@{$types}-1) {
 3036:                         if ($i > 0) { 
 3037:                             $output .= '</tr>';
 3038:                         }
 3039:                         $output .= '<tr>';
 3040:                     }
 3041:                 } elsif ($i==@{$types}-1) {
 3042:                     my $colsleft = $numinrow - $rem;
 3043:                     if ($colsleft > 1) {
 3044:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 3045:                     }
 3046:                 }
 3047:                 my $check = ' ';
 3048:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 3049:                     $check = ' checked="checked" ';
 3050:                 }
 3051:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 3052:                            '<span class="LC_nobreak"><label>'.
 3053:                            '<input type="checkbox" name="inststatus" '.
 3054:                            'value="'.$types->[$i].'"'.$check.'/>'.
 3055:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 3056:             }
 3057:         }
 3058:         $output .= '</tr></table>';
 3059:     }
 3060:     return $output;
 3061: }
 3062: 
 3063: sub selfcreate_canmodify {
 3064:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 3065:     if (ref($inst_results) eq 'HASH') {
 3066:         my @inststatuses = &get_inststatuses($inst_results);
 3067:         if (@inststatuses == 0) {
 3068:             @inststatuses = ('default');
 3069:         }
 3070:         $rolesarray = \@inststatuses;
 3071:     }
 3072:     my %canmodify =
 3073:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 3074:                                                    $rolesarray);
 3075:     return %canmodify;
 3076: }
 3077: 
 3078: sub get_inststatuses {
 3079:     my ($insthashref) = @_;
 3080:     my @inststatuses = ();
 3081:     if (ref($insthashref) eq 'HASH') {
 3082:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 3083:             @inststatuses = @{$insthashref->{'inststatus'}};
 3084:         }
 3085:     }
 3086:     return @inststatuses;
 3087: }
 3088: 
 3089: # ================================================================= Phase Three
 3090: sub update_user_data {
 3091:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 3092:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 3093:                                           $env{'form.ccdomain'});
 3094:     # Error messages
 3095:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 3096:     my $end       = '</span><br /><br />';
 3097:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 3098:                     "'$env{'form.prevphase'}','modify')".'" />'.
 3099:                     &mt('Return to previous page').'</a>'.
 3100:                     &Apache::loncommon::end_page();
 3101:     my $now = time;
 3102:     my $title;
 3103:     if (exists($env{'form.makeuser'})) {
 3104: 	$title='Set Privileges for New User';
 3105:     } else {
 3106:         $title='Modify User Privileges';
 3107:     }
 3108:     my $newuser = 0;
 3109:     my ($jsback,$elements) = &crumb_utilities();
 3110:     my $jscript = '<script type="text/javascript">'."\n".
 3111:                   '// <![CDATA['."\n".
 3112:                   $jsback."\n".
 3113:                   '// ]]>'."\n".
 3114:                   '</script>'."\n";
 3115:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 3116:     push (@{$brcrum},
 3117:              {href => "javascript:backPage(document.userupdate)",
 3118:               text => $breadcrumb_text{'search'},
 3119:               faq  => 282,
 3120:               bug  => 'Instructor Interface',}
 3121:              );
 3122:     if ($env{'form.prevphase'} eq 'userpicked') {
 3123:         push(@{$brcrum},
 3124:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 3125:                 text => $breadcrumb_text{'userpicked'},
 3126:                 faq  => 282,
 3127:                 bug  => 'Instructor Interface',});
 3128:     }
 3129:     my $helpitem = 'Course_Change_Privileges';
 3130:     if ($env{'form.action'} eq 'singlestudent') {
 3131:         $helpitem = 'Course_Add_Student';
 3132:     } elsif ($context eq 'author') {
 3133:         $helpitem = 'Author_Change_Privileges';
 3134:     } elsif ($context eq 'domain') {
 3135:         $helpitem = 'Domain_Change_Privileges';
 3136:     }
 3137:     push(@{$brcrum}, 
 3138:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 3139:              text => $breadcrumb_text{'modify'},
 3140:              faq  => 282,
 3141:              bug  => 'Instructor Interface',},
 3142:             {href => "/adm/createuser",
 3143:              text => "Result",
 3144:              faq  => 282,
 3145:              bug  => 'Instructor Interface',
 3146:              help => $helpitem});
 3147:     my $args = {bread_crumbs          => $brcrum,
 3148:                 bread_crumbs_component => 'User Management'};
 3149:     if ($env{'form.popup'}) {
 3150:         $args->{'no_nav_bar'} = 1;
 3151:     }
 3152:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 3153:     $r->print(&update_result_form($uhome));
 3154:     # Check Inputs
 3155:     if (! $env{'form.ccuname'} ) {
 3156: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 3157: 	return;
 3158:     }
 3159:     if (  $env{'form.ccuname'} ne 
 3160: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 3161: 	$r->print($error.&mt('Invalid login name.').'  '.
 3162: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 3163: 		  $end.$rtnlink);
 3164: 	return;
 3165:     }
 3166:     if (! $env{'form.ccdomain'}       ) {
 3167: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 3168: 	return;
 3169:     }
 3170:     if (  $env{'form.ccdomain'} ne
 3171: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 3172: 	$r->print($error.&mt('Invalid domain name.').'  '.
 3173: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 3174: 		  $end.$rtnlink);
 3175: 	return;
 3176:     }
 3177:     if ($uhome eq 'no_host') {
 3178:         $newuser = 1;
 3179:     }
 3180:     if (! exists($env{'form.makeuser'})) {
 3181:         # Modifying an existing user, so check the validity of the name
 3182:         if ($uhome eq 'no_host') {
 3183:             $r->print(
 3184:                 $error
 3185:                .'<p class="LC_error">'
 3186:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 3187:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 3188:                .'</p>');
 3189:             return;
 3190:         }
 3191:     }
 3192:     # Determine authentication method and password for the user being modified
 3193:     my $amode='';
 3194:     my $genpwd='';
 3195:     if ($env{'form.login'} eq 'krb') {
 3196: 	$amode='krb';
 3197: 	$amode.=$env{'form.krbver'};
 3198: 	$genpwd=$env{'form.krbarg'};
 3199:     } elsif ($env{'form.login'} eq 'int') {
 3200: 	$amode='internal';
 3201: 	$genpwd=$env{'form.intarg'};
 3202:     } elsif ($env{'form.login'} eq 'fsys') {
 3203: 	$amode='unix';
 3204: 	$genpwd=$env{'form.fsysarg'};
 3205:     } elsif ($env{'form.login'} eq 'loc') {
 3206: 	$amode='localauth';
 3207: 	$genpwd=$env{'form.locarg'};
 3208: 	$genpwd=" " if (!$genpwd);
 3209:     } elsif ($env{'form.login'} eq 'lti') {
 3210:         $amode='lti';
 3211:         $genpwd=" ";
 3212:     } elsif (($env{'form.login'} eq 'nochange') ||
 3213:              ($env{'form.login'} eq ''        )) { 
 3214:         # There is no need to tell the user we did not change what they
 3215:         # did not ask us to change.
 3216:         # If they are creating a new user but have not specified login
 3217:         # information this will be caught below.
 3218:     } else {
 3219:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 3220:             return;
 3221:     }
 3222: 
 3223:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 3224:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 3225:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 3226:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 3227: 
 3228:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 3229:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3230:     my @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
 3231:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 3232:     my @requestauthor = ('requestauthor');
 3233:     my @authordefaults = ('webdav','editors');
 3234:     my ($othertitle,$usertypes,$types) = 
 3235:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 3236:     my %canmodify_status =
 3237:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 3238:                                                    ['inststatus']);
 3239:     if ($env{'form.makeuser'}) {
 3240: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 3241:         # Check for the authentication mode and password
 3242:         if (! $amode || ! $genpwd) {
 3243: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 3244: 	    return;
 3245: 	}
 3246:         # Determine desired host
 3247:         my $desiredhost = $env{'form.hserver'};
 3248:         if (lc($desiredhost) eq 'default') {
 3249:             $desiredhost = undef;
 3250:         } else {
 3251:             my %home_servers = 
 3252: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 3253:             if (! exists($home_servers{$desiredhost})) {
 3254:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 3255:                 return;
 3256:             }
 3257:         }
 3258:         # Check ID format
 3259:         my %checkhash;
 3260:         my %checks = ('id' => 1);
 3261:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 3262:             'newuser' => $newuser, 
 3263:             'id' => $env{'form.cid'},
 3264:         );
 3265:         if ($env{'form.cid'} ne '') {
 3266:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 3267:                                           \%rulematch,\%inst_results,\%curr_rules);
 3268:             if (ref($alerts{'id'}) eq 'HASH') {
 3269:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3270:                     my $domdesc =
 3271:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 3272:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 3273:                         my $userchkmsg;
 3274:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 3275:                             $userchkmsg  = 
 3276:                                 &Apache::loncommon::instrule_disallow_msg('id',
 3277:                                                                     $domdesc,1).
 3278:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 3279:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 3280:                         }
 3281:                         $r->print($error.&mt('Invalid ID format').$end.
 3282:                                   $userchkmsg.$rtnlink);
 3283:                         return;
 3284:                     }
 3285:                 }
 3286:             }
 3287:         }
 3288:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 3289: 	# Call modifyuser
 3290: 	my $result = &Apache::lonnet::modifyuser
 3291: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 3292:              $amode,$genpwd,$env{'form.cfirstname'},
 3293:              $env{'form.cmiddlename'},$env{'form.clastname'},
 3294:              $env{'form.cgeneration'},undef,$desiredhost,
 3295:              $env{'form.cpermanentemail'});
 3296: 	$r->print(&mt('Generating user').': '.$result);
 3297:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 3298:                                                $env{'form.ccdomain'});
 3299:         my (%changeHash,%newcustom,%changed,%changedinfo);
 3300:         if ($uhome ne 'no_host') {
 3301:             if ($context eq 'domain') {
 3302:                 foreach my $name ('portfolio','author') {
 3303:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3304:                         if ($env{'form.'.$name.'quota'} eq '') {
 3305:                             $newcustom{$name.'quota'} = 0;
 3306:                         } else {
 3307:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 3308:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 3309:                         }
 3310:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 3311:                             $changed{$name.'quota'} = 1;
 3312:                         }
 3313:                     }
 3314:                 }
 3315:                 foreach my $item (@usertools) {
 3316:                     if ($env{'form.custom'.$item} == 1) {
 3317:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3318:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3319:                                                      \%changeHash,'tools');
 3320:                     }
 3321:                 }
 3322:                 foreach my $item (@requestcourses) {
 3323:                     if ($env{'form.custom'.$item} == 1) {
 3324:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3325:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3326:                             $newcustom{$item} .= '=';
 3327:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3328:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3329:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3330:                             }
 3331:                         }
 3332:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3333:                                                       \%changeHash,'requestcourses');
 3334:                     }
 3335:                 }
 3336:                 if ($env{'form.customrequestauthor'} == 1) {
 3337:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3338:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3339:                                                     $newcustom{'requestauthor'},
 3340:                                                     \%changeHash,'requestauthor');
 3341:                 }
 3342:                 if ($env{'form.customeditors'} == 1) {
 3343:                     my @editors;
 3344:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 3345:                     if (@posseditors) {
 3346:                         foreach my $editor (@posseditors) {
 3347:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 3348:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 3349:                                     push(@editors,$editor);
 3350:                                 }
 3351:                             }
 3352:                         }
 3353:                     }
 3354:                     if (@editors) {
 3355:                         @editors = sort(@editors);
 3356:                         $changed{'editors'} = &tool_admin('editors',join(',',@editors),
 3357:                                                           \%changeHash,'authordefaults');
 3358:                     }
 3359:                 }
 3360:                 if ($env{'form.customwebdav'} == 1) {
 3361:                     $newcustom{'webdav'} = $env{'form.authordefaults_webdav'};
 3362:                     $changed{'webdav'} = &tool_admin('webdav',$newcustom{'webdav'},
 3363:                                                   \%changeHash,'authordefaults');
 3364:                 }
 3365:             }
 3366:             if ($canmodify_status{'inststatus'}) {
 3367:                 if (exists($env{'form.inststatus'})) {
 3368:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3369:                     if (@inststatuses > 0) {
 3370:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3371:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3372:                     }
 3373:                 }
 3374:             }
 3375:             if (keys(%changed)) {
 3376:                 foreach my $item (@userinfo) {
 3377:                     $changeHash{$item}  = $env{'form.c'.$item};
 3378:                 }
 3379:                 my $chgresult =
 3380:                      &Apache::lonnet::put('environment',\%changeHash,
 3381:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3382:             }
 3383:         }
 3384:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3385:                   &Apache::lonnet::hostname($uhome));
 3386:     } elsif (($env{'form.login'} ne 'nochange') &&
 3387:              ($env{'form.login'} ne ''        )) {
 3388: 	# Modify user privileges
 3389:         if (! $amode || ! $genpwd) {
 3390: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3391: 	    return;
 3392: 	}
 3393: 	# Only allow authentication modification if the person has authority
 3394: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3395: 	    $r->print('Modifying authentication: '.
 3396:                       &Apache::lonnet::modifyuserauth(
 3397: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3398:                        $amode,$genpwd));
 3399:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3400: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3401: 	} else {
 3402: 	    # Okay, this is a non-fatal error.
 3403: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3404: 	}
 3405:     } elsif (($env{'form.intarg'} ne '') &&
 3406:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3407:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3408:         $r->print('Modifying authentication: '.
 3409:                   &Apache::lonnet::modifyuserauth(
 3410:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3411:                   'internal',$env{'form.intarg'}));
 3412:     }
 3413:     $r->rflush(); # Finish display of header before time consuming actions start
 3414:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3415:     ##
 3416:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3417:     if ($context eq 'course') {
 3418:         ($cnum,$cdom) =
 3419:             &Apache::lonuserutils::get_course_identity();
 3420:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3421:         if ($showcredits) {
 3422:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3423:         }
 3424:     }
 3425:     if (! $env{'form.makeuser'} ) {
 3426:         # Check for need to change
 3427:         my %userenv = &Apache::lonnet::get
 3428:             ('environment',['firstname','middlename','lastname','generation',
 3429:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3430:              'tools.aboutme','tools.blog','tools.webdav',
 3431:              'tools.portfolio','tools.timezone','tools.portaccess',
 3432:              'authormanagers','authoreditors','requestauthor',
 3433:              'requestcourses.official','requestcourses.unofficial',
 3434:              'requestcourses.community','requestcourses.textbook',
 3435:              'requestcourses.placement','requestcourses.lti',
 3436:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3437:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3438:              'reqcrsotherdom.placement','domcoord.author'],
 3439:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3440:         my ($tmp) = keys(%userenv);
 3441:         if ($tmp =~ /^(con_lost|error)/i) { 
 3442:             %userenv = ();
 3443:         }
 3444:         unless (($userenv{'domcoord.author'} eq 'blocked') &&
 3445:                 (($env{'user.name'} ne $env{'form.ccuname'}) ||
 3446:                  ($env{'user.domain'} ne $env{'form.ccdomain'}))) {
 3447:             push(@authordefaults,'managers');
 3448:         }
 3449:         my $no_forceid_alert;
 3450:         # Check to see if user information can be changed
 3451:         my %domconfig =
 3452:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3453:                                      $env{'form.ccdomain'});
 3454:         my @statuses = ('active','future');
 3455:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3456:         my ($auname,$audom);
 3457:         if ($context eq 'author') {
 3458:             $auname = $env{'user.name'};
 3459:             $audom = $env{'user.domain'};     
 3460:         }
 3461:         foreach my $item (keys(%roles)) {
 3462:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3463:             if ($context eq 'course') {
 3464:                 if ($cnum ne '' && $cdom ne '') {
 3465:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3466:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3467:                             push(@userroles,$role);
 3468:                         }
 3469:                     }
 3470:                 }
 3471:             } elsif ($context eq 'author') {
 3472:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3473:                     if (!grep(/^\Q$role\E$/,@userroles)) {
 3474:                         push(@userroles,$role);
 3475:                     }
 3476:                 }
 3477:             }
 3478:         }
 3479:         if ($env{'form.action'} eq 'singlestudent') {
 3480:             if (!grep(/^st$/,@userroles)) {
 3481:                 push(@userroles,'st');
 3482:             }
 3483:         } else {
 3484:             # Check for course or co-author roles being activated or re-enabled
 3485:             if ($context eq 'author' || $context eq 'course') {
 3486:                 foreach my $key (keys(%env)) {
 3487:                     if ($context eq 'author') {
 3488:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3489:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3490:                                 push(@userroles,$1);
 3491:                             }
 3492:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3493:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3494:                                 push(@userroles,$1);
 3495:                             }
 3496:                         }
 3497:                     } elsif ($context eq 'course') {
 3498:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3499:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3500:                                 push(@userroles,$1);
 3501:                             }
 3502:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3503:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3504:                                 push(@userroles,$1);
 3505:                             }
 3506:                         }
 3507:                     }
 3508:                 }
 3509:             }
 3510:         }
 3511:         #Check to see if we can change personal data for the user 
 3512:         my (@mod_disallowed,@longroles);
 3513:         foreach my $role (@userroles) {
 3514:             if ($role eq 'cr') {
 3515:                 push(@longroles,'Custom');
 3516:             } else {
 3517:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3518:             }
 3519:         }
 3520:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3521:         foreach my $item (@userinfo) {
 3522:             # Strip leading and trailing whitespace
 3523:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3524:             if (!$canmodify{$item}) {
 3525:                 if (defined($env{'form.c'.$item})) {
 3526:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3527:                         push(@mod_disallowed,$item);
 3528:                     }
 3529:                 }
 3530:                 $env{'form.c'.$item} = $userenv{$item};
 3531:             }
 3532:         }
 3533:         # Check to see if we can change the Student/Employee ID
 3534:         my $forceid = $env{'form.forceid'};
 3535:         my $recurseid = $env{'form.recurseid'};
 3536:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3537:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3538:                                             $env{'form.ccuname'});
 3539:         if (($uidhash{$env{'form.ccuname'}}) && 
 3540:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3541:             (!$forceid)) {
 3542:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3543:                 $env{'form.cid'} = $userenv{'id'};
 3544:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3545:                                    .'<br />'
 3546:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3547:                                    .'<br />'."\n";
 3548:             }
 3549:         }
 3550:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3551:             my $checkhash;
 3552:             my $checks = { 'id' => 1 };
 3553:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3554:                    { 'newuser' => $newuser,
 3555:                      'id'  => $env{'form.cid'}, 
 3556:                    };
 3557:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3558:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3559:             if (ref($alerts{'id'}) eq 'HASH') {
 3560:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3561:                    $env{'form.cid'} = $userenv{'id'};
 3562:                 }
 3563:             }
 3564:         }
 3565:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3566:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3567:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3568:             %oldsettingstatus,%newsettingstatus);
 3569:         @disporder = ('inststatus');
 3570:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3571:             push(@disporder,('requestcourses','requestauthor','authordefaults'));
 3572:         } else {
 3573:             push(@disporder,'reqcrsotherdom');
 3574:         }
 3575:         push(@disporder,('quota','tools'));
 3576:         $oldinststatus = $userenv{'inststatus'};
 3577:         foreach my $name ('portfolio','author') {
 3578:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3579:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3580:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3581:         }
 3582:         my %canshow;
 3583:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3584:             $canshow{'quota'} = 1;
 3585:         }
 3586:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3587:             $canshow{'tools'} = 1;
 3588:         }
 3589:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3590:             $canshow{'requestcourses'} = 1;
 3591:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3592:             $canshow{'reqcrsotherdom'} = 1;
 3593:         }
 3594:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3595:             $canshow{'inststatus'} = 1;
 3596:         }
 3597:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3598:             $canshow{'requestauthor'} = 1;
 3599:             $canshow{'authordefaults'} = 1;
 3600:         }
 3601:         my (%changeHash,%changed);
 3602:         if ($oldinststatus eq '') {
 3603:             $oldsettings{'inststatus'} = $othertitle; 
 3604:         } else {
 3605:             if (ref($usertypes) eq 'HASH') {
 3606:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3607:             } else {
 3608:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3609:             }
 3610:         }
 3611:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3612:         if ($canmodify_status{'inststatus'}) {
 3613:             $canshow{'inststatus'} = 1;
 3614:             if (exists($env{'form.inststatus'})) {
 3615:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3616:                 if (@inststatuses > 0) {
 3617:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3618:                     $changeHash{'inststatus'} = $newinststatus;
 3619:                     if ($newinststatus ne $oldinststatus) {
 3620:                         $changed{'inststatus'} = $newinststatus;
 3621:                         foreach my $name ('portfolio','author') {
 3622:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3623:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3624:                         }
 3625:                     }
 3626:                     if (ref($usertypes) eq 'HASH') {
 3627:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3628:                     } else {
 3629:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3630:                     }
 3631:                 }
 3632:             } else {
 3633:                 $newinststatus = '';
 3634:                 $changeHash{'inststatus'} = $newinststatus;
 3635:                 $newsettings{'inststatus'} = $othertitle;
 3636:                 if ($newinststatus ne $oldinststatus) {
 3637:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3638:                     foreach my $name ('portfolio','author') {
 3639:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3640:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3641:                     }
 3642:                 }
 3643:             }
 3644:         } elsif ($context ne 'selfcreate') {
 3645:             $canshow{'inststatus'} = 1;
 3646:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3647:         }
 3648:         foreach my $name ('portfolio','author') {
 3649:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3650:         }
 3651:         if ($context eq 'domain') {
 3652:             foreach my $name ('portfolio','author') {
 3653:                 if ($userenv{$name.'quota'} ne '') {
 3654:                     $oldquota{$name} = $userenv{$name.'quota'};
 3655:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3656:                         if ($env{'form.'.$name.'quota'} eq '') {
 3657:                             $newquota{$name} = 0;
 3658:                         } else {
 3659:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3660:                             $newquota{$name} =~ s/[^\d\.]//g;
 3661:                         }
 3662:                         if ($newquota{$name} != $oldquota{$name}) {
 3663:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3664:                                 $changed{$name.'quota'} = 1;
 3665:                             }
 3666:                         }
 3667:                     } else {
 3668:                         if (&quota_admin('',\%changeHash,$name)) {
 3669:                             $changed{$name.'quota'} = 1;
 3670:                             $newquota{$name} = $newdefquota{$name};
 3671:                             $newisdefault{$name} = 1;
 3672:                         }
 3673:                     }
 3674:                 } else {
 3675:                     $oldisdefault{$name} = 1;
 3676:                     $oldquota{$name} = $olddefquota{$name};
 3677:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3678:                         if ($env{'form.'.$name.'quota'} eq '') {
 3679:                             $newquota{$name} = 0;
 3680:                         } else {
 3681:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3682:                             $newquota{$name} =~ s/[^\d\.]//g;
 3683:                         }
 3684:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3685:                             $changed{$name.'quota'} = 1;
 3686:                         }
 3687:                     } else {
 3688:                         $newquota{$name} = $newdefquota{$name};
 3689:                         $newisdefault{$name} = 1;
 3690:                     }
 3691:                 }
 3692:                 if ($oldisdefault{$name}) {
 3693:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3694:                 }  else {
 3695:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3696:                 }
 3697:                 if ($newisdefault{$name}) {
 3698:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3699:                 } else {
 3700:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3701:                 }
 3702:             }
 3703:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3704:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3705:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3706:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3707:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3708:                 my ($isadv,$isauthor) =
 3709:                     &Apache::lonnet::is_advanced_user($env{'form.ccdomain'},$env{'form.ccuname'});
 3710:                 unless ($isauthor) {
 3711:                     &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3712:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3713:                 }
 3714:                 &tool_changes('authordefaults',\@authordefaults,\%oldsettings,\%oldsettingstext,
 3715:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3716:             } else {
 3717:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3718:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3719:             }
 3720:         }
 3721:         foreach my $item (@userinfo) {
 3722:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3723:                 $namechanged{$item} = 1;
 3724:             }
 3725:         }
 3726:         foreach my $name ('portfolio','author') {
 3727:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3728:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3729:         }
 3730:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3731:             my ($chgresult,$namechgresult);
 3732:             if (keys(%changed) > 0) {
 3733:                 $chgresult =
 3734:                     &Apache::lonnet::put('environment',\%changeHash,
 3735:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3736:                 if ($chgresult eq 'ok') {
 3737:                     my ($ca_mgr_del,%ca_mgr_add);
 3738:                     if ($changed{'managers'}) {
 3739:                         my (@adds,@dels);
 3740:                         if ($changeHash{'authormanagers'} eq '') {
 3741:                             @dels = split(/,/,$userenv{'authormanagers'});
 3742:                         } elsif ($userenv{'authormanagers'} eq '') {
 3743:                             @adds = split(/,/,$changeHash{'authormanagers'});
 3744:                         } else {
 3745:                             my @old = split(/,/,$userenv{'authormanagers'});
 3746:                             my @new = split(/,/,$changeHash{'authormanagers'});
 3747:                             my @diffs = &Apache::loncommon::compare_arrays(\@old,\@new);
 3748:                             if (@diffs) {
 3749:                                 foreach my $user (@diffs) {
 3750:                                     if (grep(/^\Q$user\E$/,@old)) {
 3751:                                         push(@dels,$user);
 3752:                                     } elsif (grep(/^\Q$user\E$/,@new)) {
 3753:                                         push(@adds,$user);
 3754:                                     }
 3755:                                 }
 3756:                             }
 3757:                         }
 3758:                         my $key = "internal.manager./$env{'form.ccdomain'}/$env{'form.ccuname'}";
 3759:                         if (@dels) {
 3760:                             foreach my $user (@dels) {
 3761:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3762:                                     &Apache::lonnet::del('environment',[$key],$2,$1);
 3763:                                 }
 3764:                             }
 3765:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3766:                             if (grep(/^\Q$curruser\E$/,@dels)) {
 3767:                                 $ca_mgr_del = $key;
 3768:                             }
 3769:                         }
 3770:                         if (@adds) {
 3771:                             foreach my $user (@adds) {
 3772:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3773:                                     &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 3774:                                 }
 3775:                             }
 3776:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3777:                             if (grep(/^\Q$curruser\E$/,@adds)) {
 3778:                                 $ca_mgr_add{$key} = 1;
 3779:                             }
 3780:                         }
 3781:                     }
 3782:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3783:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3784:                         my (%newenvhash,$got_domdefs,%domdefaults,$got_userenv,
 3785:                             %userenv);
 3786:                         my @fromenv = keys(%changed);
 3787:                         push(@fromenv,'inststatus');
 3788:                         foreach my $key (keys(%changed)) {
 3789:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3790:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3791:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3792:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3793:                                     $changeHash{'requestcourses.'.$key};
 3794:                                 if ($changeHash{'requestcourses.'.$key}) {
 3795:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3796:                                 } else {
 3797:                                     unless ($got_domdefs) {
 3798:                                         %domdefaults =
 3799:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3800:                                         $got_domdefs = 1;
 3801:                                     }
 3802:                                     unless ($got_userenv) {
 3803:                                         %userenv =
 3804:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3805:                                                                              $env{'user.name'},@fromenv);
 3806:                                         $got_userenv = 1;
 3807:                                     }
 3808:                                     $newenvhash{'environment.canrequest.'.$key} =
 3809:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3810:                                             $key,'reload','requestcourses',\%userenv,\%domdefaults);
 3811:                                 }
 3812:                             } elsif ($key eq 'requestauthor') {
 3813:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3814:                                 if ($changeHash{$key}) {
 3815:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3816:                                 } else {
 3817:                                     unless ($got_domdefs) {
 3818:                                         %domdefaults =
 3819:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3820:                                         $got_domdefs = 1;
 3821:                                     }
 3822:                                     unless ($got_userenv) {
 3823:                                         %userenv =
 3824:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3825:                                                                              $env{'user.name'},@fromenv);
 3826:                                         $got_userenv = 1;
 3827:                                     }
 3828:                                     $newenvhash{'environment.canrequest.author'} =
 3829:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3830:                                             $key,'reload','requestauthor',\%userenv,\%domdefaults);
 3831:                                 }
 3832:                             } elsif ($key eq 'editors') {
 3833:                                 $newenvhash{'environment.author'.$key} = $changeHash{'author'.$key};
 3834:                                 if ($env{'form.customeditors'}) {
 3835:                                     $newenvhash{'environment.editors'} = $changeHash{'author'.$key};
 3836:                                 } else {
 3837:                                     unless ($got_domdefs) {
 3838:                                         %domdefaults =
 3839:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3840:                                         $got_domdefs = 1;
 3841:                                     }
 3842:                                     if ($domdefaults{'editors'} ne '') {
 3843:                                         $newenvhash{'environment.editors'} = $domdefaults{'editors'};
 3844:                                     } else {
 3845:                                         $newenvhash{'environment.editors'} = 'edit,xml';
 3846:                                     }
 3847:                                 }
 3848:                             } elsif ($key ne 'quota') {
 3849:                                 $newenvhash{'environment.tools.'.$key} = 
 3850:                                     $changeHash{'tools.'.$key};
 3851:                                 if ($changeHash{'tools.'.$key} ne '') {
 3852:                                     $newenvhash{'environment.availabletools.'.$key} =
 3853:                                         $changeHash{'tools.'.$key};
 3854:                                 } else {
 3855:                                     unless ($got_domdefs) {
 3856:                                         %domdefaults =
 3857:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3858:                                         $got_domdefs = 1;
 3859:                                     }
 3860:                                     unless ($got_userenv) {
 3861:                                         %userenv =
 3862:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3863:                                                                              $env{'user.name'},@fromenv);
 3864:                                         $got_userenv = 1;
 3865:                                     }
 3866:                                     $newenvhash{'environment.availabletools.'.$key} =
 3867:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3868:                                             $key,'reload','tools',\%userenv,\%domdefaults);
 3869:                                 }
 3870:                             }
 3871:                         }
 3872:                         if (keys(%newenvhash)) {
 3873:                             &Apache::lonnet::appenv(\%newenvhash);
 3874:                         }
 3875:                     } else {
 3876:                         if ($ca_mgr_del) {
 3877:                             &Apache::lonnet::delenv($ca_mgr_del);
 3878:                         }
 3879:                         if (keys(%ca_mgr_add)) {
 3880:                             &Apache::lonnet::appenv(\%ca_mgr_add);
 3881:                         }
 3882:                     }
 3883:                     if ($changed{'aboutme'}) {
 3884:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3885:                                                                      $env{'form.ccdomain'});
 3886:                     }
 3887:                 }
 3888:             }
 3889:             if (keys(%namechanged) > 0) {
 3890:                 foreach my $field (@userinfo) {
 3891:                     $changeHash{$field}  = $env{'form.c'.$field};
 3892:                 }
 3893: # Make the change
 3894:                 $namechgresult =
 3895:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3896:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3897:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3898:                         $changeHash{'lastname'},$changeHash{'generation'},
 3899:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3900:                 %userupdate = (
 3901:                                lastname   => $env{'form.clastname'},
 3902:                                middlename => $env{'form.cmiddlename'},
 3903:                                firstname  => $env{'form.cfirstname'},
 3904:                                generation => $env{'form.cgeneration'},
 3905:                                id         => $env{'form.cid'},
 3906:                              );
 3907:             }
 3908:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3909:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3910:             # Tell the user we changed the name
 3911:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3912:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3913:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3914:                                   \%newsettingstext);
 3915:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3916:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3917:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3918:                     if (($recurseid) &&
 3919:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3920:                         my $idresult = 
 3921:                             &Apache::lonuserutils::propagate_id_change(
 3922:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3923:                                 \%userupdate);
 3924:                         $r->print('<br />'.$idresult.'<br />');
 3925:                     }
 3926:                 }
 3927:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3928:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3929:                     my %newenvhash;
 3930:                     foreach my $key (keys(%changeHash)) {
 3931:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3932:                     }
 3933:                     &Apache::lonnet::appenv(\%newenvhash);
 3934:                 }
 3935:             } else { # error occurred
 3936:                 $r->print(
 3937:                     '<p class="LC_error">'
 3938:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3939:                             '"'.$env{'form.ccuname'}.'"',
 3940:                             '"'.$env{'form.ccdomain'}.'"')
 3941:                    .'</p>');
 3942:             }
 3943:         } else { # End of if ($env ... ) logic
 3944:             # They did not want to change the users name, quota, tool availability,
 3945:             # or ability to request creation of courses, 
 3946:             # but we can still tell them what the name and quota and availabilities are  
 3947:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3948:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3949:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3950:         }
 3951:         if (@mod_disallowed) {
 3952:             my ($rolestr,$contextname);
 3953:             if (@longroles > 0) {
 3954:                 $rolestr = join(', ',@longroles);
 3955:             } else {
 3956:                 $rolestr = &mt('No roles');
 3957:             }
 3958:             if ($context eq 'course') {
 3959:                 $contextname = 'course';
 3960:             } elsif ($context eq 'author') {
 3961:                 $contextname = 'co-author';
 3962:             }
 3963:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3964:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3965:             foreach my $field (@mod_disallowed) {
 3966:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3967:             }
 3968:             $r->print('</ul>');
 3969:             if (@mod_disallowed == 1) {
 3970:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3971:             } else {
 3972:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3973:             }
 3974:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3975:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3976:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3977:                          ,'<a href="'.$helplink.'">','</a>')
 3978:                       .'<br />');
 3979:         }
 3980:         $r->print('<span class="LC_warning">'
 3981:                   .$no_forceid_alert
 3982:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3983:                   .'</span>');
 3984:     }
 3985:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3986:     if ($env{'form.action'} eq 'singlestudent') {
 3987:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3988:                                $crstype,$showcredits,$defaultcredits);
 3989:         my $linktext = ($crstype eq 'Community' ?
 3990:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3991:         $r->print(
 3992:             &Apache::lonhtmlcommon::actionbox([
 3993:                 '<a href="javascript:backPage(document.userupdate)">'
 3994:                .($crstype eq 'Community' ? 
 3995:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3996:                .'</a>']));
 3997:     } else {
 3998:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3999:         if (keys(%namechanged) > 0) {
 4000:             if ($context eq 'course') {
 4001:                 if (@userroles > 0) {
 4002:                     if ((@rolechanges == 0) || 
 4003:                         (!(grep(/^st$/,@rolechanges)))) {
 4004:                         if (grep(/^st$/,@userroles)) {
 4005:                             my $classlistupdated =
 4006:                                 &Apache::lonuserutils::update_classlist($cdom,
 4007:                                               $cnum,$env{'form.ccdomain'},
 4008:                                        $env{'form.ccuname'},\%userupdate);
 4009:                         }
 4010:                     }
 4011:                 }
 4012:             }
 4013:         }
 4014:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 4015:                                                      $env{'form.ccdomain'});
 4016:         if ($env{'form.popup'}) {
 4017:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 4018:         } else {
 4019:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 4020:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 4021:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 4022:         }
 4023:     }
 4024: }
 4025: 
 4026: sub display_userinfo {
 4027:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 4028:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 4029:         $newsetting,$newsettingtext) = @_;
 4030:     return unless (ref($order) eq 'ARRAY' &&
 4031:                    ref($canshow) eq 'HASH' && 
 4032:                    ref($requestcourses) eq 'ARRAY' && 
 4033:                    ref($requestauthor) eq 'ARRAY' &&
 4034:                    ref($usertools) eq 'ARRAY' && 
 4035:                    ref($userenv) eq 'HASH' &&
 4036:                    ref($changedhash) eq 'HASH' &&
 4037:                    ref($oldsetting) eq 'HASH' &&
 4038:                    ref($oldsettingtext) eq 'HASH' &&
 4039:                    ref($newsetting) eq 'HASH' &&
 4040:                    ref($newsettingtext) eq 'HASH');
 4041:     my %lt=&Apache::lonlocal::texthash(
 4042:          'ui'             => 'User Information',
 4043:          'uic'            => 'User Information Changed',
 4044:          'firstname'      => 'First Name',
 4045:          'middlename'     => 'Middle Name',
 4046:          'lastname'       => 'Last Name',
 4047:          'generation'     => 'Generation',
 4048:          'id'             => 'Student/Employee ID',
 4049:          'permanentemail' => 'Permanent e-mail address',
 4050:          'portfolioquota' => 'Disk space allocated to portfolio files',
 4051:          'authorquota'    => 'Disk space allocated to Authoring Space',
 4052:          'blog'           => 'Blog Availability',
 4053:          'webdav'         => 'WebDAV Availability',
 4054:          'aboutme'        => 'Personal Information Page Availability',
 4055:          'portfolio'      => 'Portfolio Availability',
 4056:          'portaccess'     => 'Portfolio Shareable',
 4057:          'timezone'       => 'Can set own Time Zone',
 4058:          'official'       => 'Can Request Official Courses',
 4059:          'unofficial'     => 'Can Request Unofficial Courses',
 4060:          'community'      => 'Can Request Communities',
 4061:          'textbook'       => 'Can Request Textbook Courses',
 4062:          'placement'      => 'Can Request Placement Tests',
 4063:          'lti'            => 'Can Request LTI Courses',
 4064:          'requestauthor'  => 'Can Request Author Role',
 4065:          'inststatus'     => "Affiliation",
 4066:          'prvs'           => 'Previous Value:',
 4067:          'chto'           => 'Changed To:',
 4068:          'editors'        => "Available Editors in Authoring Space",
 4069:          'managers'       => "Co-authors who can add/revoke roles",
 4070:          'edit'           => 'Standard editor (Edit)',
 4071:          'xml'            => 'Text editor (EditXML)',
 4072:          'daxe'           => 'Daxe editor (Daxe)',
 4073:     );
 4074:     if ($changed) {
 4075:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 4076:                 &Apache::loncommon::start_data_table().
 4077:                 &Apache::loncommon::start_data_table_header_row());
 4078:         $r->print("<th>&nbsp;</th>\n");
 4079:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 4080:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 4081:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4082:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 4083: 
 4084:         foreach my $item (@userinfo) {
 4085:             my $value = $env{'form.c'.$item};
 4086:             #show changes only:
 4087:             unless ($value eq $userenv->{$item}){
 4088:                 $r->print(&Apache::loncommon::start_data_table_row());
 4089:                 $r->print("<td>$lt{$item}</td>\n");
 4090:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 4091:                 $r->print("<td>$value </td>\n");
 4092:                 $r->print(&Apache::loncommon::end_data_table_row());
 4093:             }
 4094:         }
 4095:         foreach my $entry (@{$order}) {
 4096:             if ($canshow->{$entry}) {
 4097:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') ||
 4098:                     ($entry eq 'requestauthor') || ($entry eq 'authordefaults')) {
 4099:                     my @items;
 4100:                     if ($entry eq 'requestauthor') {
 4101:                         @items = ($entry);
 4102:                     } elsif ($entry eq 'authordefaults') {
 4103:                         @items = ('webdav','managers','editors');
 4104:                     } else {
 4105:                         @items = @{$requestcourses};
 4106:                     }
 4107:                     foreach my $item (@items) {
 4108:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 4109:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 4110:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 4111:                             $r->print("<td>$lt{$item}</td><td>\n");
 4112:                             unless ($item eq 'managers') {
 4113:                                 $r->print($oldsetting->{$item});
 4114:                             }
 4115:                             if ($oldsettingtext->{$item}) {
 4116:                                 if ($oldsetting->{$item}) {
 4117:                                     unless ($item eq 'managers') {
 4118:                                         $r->print(' -- ');
 4119:                                     }
 4120:                                 }
 4121:                                 $r->print($oldsettingtext->{$item});
 4122:                             }
 4123:                             $r->print("</td>\n<td>");
 4124:                             unless ($item eq 'managers') {
 4125:                                 $r->print($newsetting->{$item});
 4126:                             }
 4127:                             if ($newsettingtext->{$item}) {
 4128:                                 if ($newsetting->{$item}) {
 4129:                                     unless ($item eq 'managers') {
 4130:                                         $r->print(' -- ');
 4131:                                     }
 4132:                                 }
 4133:                                 $r->print($newsettingtext->{$item});
 4134:                             }
 4135:                             $r->print("</td>\n");
 4136:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4137:                         }
 4138:                     }
 4139:                 } elsif ($entry eq 'tools') {
 4140:                     foreach my $item (@{$usertools}) {
 4141:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 4142:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4143:                             $r->print("<td>$lt{$item}</td>\n");
 4144:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 4145:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 4146:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4147:                         }
 4148:                     }
 4149:                 } elsif ($entry eq 'quota') {
 4150:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 4151:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 4152:                         foreach my $name ('portfolio','author') {
 4153:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 4154:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4155:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 4156:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 4157:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 4158:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4159:                             }
 4160:                         }
 4161:                     }
 4162:                 } else {
 4163:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 4164:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4165:                         $r->print("<td>$lt{$entry}</td>\n");
 4166:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 4167:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 4168:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4169:                     }
 4170:                 }
 4171:             }
 4172:         }
 4173:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 4174:     } else {
 4175:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 4176:                   '<p>'.&mt('No changes made to user information').'</p>');
 4177:     }
 4178:     return;
 4179: }
 4180: 
 4181: sub tool_changes {
 4182:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 4183:         $changed,$newaccess,$newaccesstext) = @_;
 4184:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 4185:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 4186:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 4187:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 4188:         return;
 4189:     }
 4190:     my %reqdisplay = &requestchange_display();
 4191:     if ($context eq 'reqcrsotherdom') {
 4192:         my @options = ('approval','validate','autolimit');
 4193:         my $optregex = join('|',@options);
 4194:         my $cdom = $env{'request.role.domain'};
 4195:         foreach my $tool (@{$usertools}) {
 4196:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4197:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4198:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 4199:             my ($newop,$limit);
 4200:             if ($env{'form.'.$context.'_'.$tool}) {
 4201:                 $newop = $env{'form.'.$context.'_'.$tool};
 4202:                 if ($newop eq 'autolimit') {
 4203:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4204:                     $limit =~ s/\D+//g;
 4205:                     $newop .= '='.$limit;
 4206:                 }
 4207:             }
 4208:             if ($userenv->{$context.'.'.$tool} eq '') {
 4209:                 if ($newop) {
 4210:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 4211:                                                   $changeHash,$context);
 4212:                     if ($changed->{$tool}) {
 4213:                         if ($newop =~ /^autolimit/) {
 4214:                             if ($limit) {
 4215:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4216:                             } else {
 4217:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4218:                             }
 4219:                         } else {
 4220:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 4221:                         }
 4222:                     } else {
 4223:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4224:                     }
 4225:                 }
 4226:             } else {
 4227:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 4228:                 my @new;
 4229:                 my $changedoms;
 4230:                 foreach my $req (@curr) {
 4231:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 4232:                         my $oldop = $1;
 4233:                         if ($oldop =~ /^autolimit=(\d*)/) {
 4234:                             my $limit = $1;
 4235:                             if ($limit) {
 4236:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4237:                             } else {
 4238:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4239:                             }
 4240:                         } else {
 4241:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 4242:                         }
 4243:                         if ($oldop ne $newop) {
 4244:                             $changedoms = 1;
 4245:                             foreach my $item (@curr) {
 4246:                                 my ($reqdom,$option) = split(':',$item);
 4247:                                 unless ($reqdom eq $cdom) {
 4248:                                     push(@new,$item);
 4249:                                 }
 4250:                             }
 4251:                             if ($newop) {
 4252:                                 push(@new,$cdom.':'.$newop);
 4253:                             }
 4254:                             @new = sort(@new);
 4255:                         }
 4256:                         last;
 4257:                     }
 4258:                 }
 4259:                 if ((!$changedoms) && ($newop)) {
 4260:                     $changedoms = 1;
 4261:                     @new = sort(@curr,$cdom.':'.$newop);
 4262:                 }
 4263:                 if ($changedoms) {
 4264:                     my $newdomstr;
 4265:                     if (@new) {
 4266:                         $newdomstr = join(',',@new);
 4267:                     }
 4268:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 4269:                                                   $context);
 4270:                     if ($changed->{$tool}) {
 4271:                         if ($env{'form.'.$context.'_'.$tool}) {
 4272:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 4273:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4274:                                 $limit =~ s/\D+//g;
 4275:                                 if ($limit) {
 4276:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4277:                                 } else {
 4278:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4279:                                 }
 4280:                             } else {
 4281:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 4282:                             }
 4283:                         } else {
 4284:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4285:                         }
 4286:                     }
 4287:                 }
 4288:             }
 4289:         }
 4290:         return;
 4291:     }
 4292:     my %tooldesc = &Apache::lonlocal::texthash(
 4293:         'edit' => 'Standard editor (Edit)',
 4294:         'xml'  => 'Text editor (EditXML)',
 4295:         'daxe' => 'Daxe editor (Daxe)',
 4296:     );
 4297:     foreach my $tool (@{$usertools}) {
 4298:         my ($newval,$limit,$envkey);
 4299:         $envkey = $context.'.'.$tool;
 4300:         if ($context eq 'requestcourses') {
 4301:             $newval = $env{'form.crsreq_'.$tool};
 4302:             if ($newval eq 'autolimit') {
 4303:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 4304:                 $limit =~ s/\D+//g;
 4305:                 $newval .= '='.$limit;
 4306:             }
 4307:         } elsif ($context eq 'requestauthor') {
 4308:             $newval = $env{'form.'.$context};
 4309:             $envkey = $context;
 4310:         } elsif ($context eq 'authordefaults') {
 4311:             if ($tool eq 'editors') {
 4312:                 $envkey = 'authoreditors';
 4313:                 if ($env{'form.customeditors'} == 1) {
 4314:                     my @editors;
 4315:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 4316:                     if (@posseditors) {
 4317:                         foreach my $editor (@posseditors) {
 4318:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 4319:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 4320:                                     push(@editors,$editor);
 4321:                                 }
 4322:                             }
 4323:                         }
 4324:                     }
 4325:                     if (@editors) {
 4326:                         $newval = join(',',(sort(@editors)));
 4327:                     }
 4328:                 }
 4329:             } elsif ($tool eq 'managers') {
 4330:                 $envkey = 'authormanagers';
 4331:                 my @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 4332:                 if (@possibles) {
 4333:                     my %ca_roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},
 4334:                                                                  undef,['active','future'],['ca']);
 4335:                     if (keys(%ca_roles)) {
 4336:                         my @custommanagers;
 4337:                         foreach my $user (@possibles) {
 4338:                             if ($user =~ /^($match_username):($match_domain)$/) {
 4339:                                 if (exists($ca_roles{$user.':ca'})) {
 4340:                                     unless ($user eq $env{'form.ccuname'}.':'.$env{'form.ccdomain'}) {
 4341:                                         push(@custommanagers,$user);
 4342:                                     }
 4343:                                 }
 4344:                             }
 4345:                         }
 4346:                         if (@custommanagers) {
 4347:                             $newval = join(',',sort(@custommanagers));
 4348:                         }
 4349:                     }
 4350:                 }
 4351:             } elsif ($tool eq 'webdav') {
 4352:                 $envkey = 'tools.webdav';
 4353:                 $newval = $env{'form.'.$context.'_'.$tool};
 4354:             }
 4355:         } else {
 4356:             $newval = $env{'form.'.$context.'_'.$tool};
 4357:         }
 4358:         if ($userenv->{$envkey} ne '') {
 4359:             $oldaccess->{$tool} = &mt('custom');
 4360:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4361:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 4362:                     my $currlimit = $1;
 4363:                     if ($currlimit eq '') {
 4364:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4365:                     } else {
 4366:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 4367:                     }
 4368:                 } elsif ($userenv->{$envkey}) {
 4369:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4370:                 } else {
 4371:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4372:                 }
 4373:             } elsif ($context eq 'authordefaults') {
 4374:                 if ($tool eq 'managers') {
 4375:                     if ($userenv->{$envkey} eq '') {
 4376:                         $oldaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4377:                     } else {
 4378:                         my $managers = $userenv->{$envkey};
 4379:                         $managers =~ s/,/, /g;
 4380:                         $oldaccesstext->{$tool} = $managers;
 4381:                     }
 4382:                 } elsif ($tool eq 'editors') {
 4383:                     $oldaccesstext->{$tool} = &mt('can use: [_1]',
 4384:                                                   join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4385:                 } elsif ($tool eq 'webdav') {
 4386:                     if ($userenv->{$envkey}) {
 4387:                         $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4388:                     } else {
 4389:                         $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4390:                     }
 4391:                 }
 4392:             } else {
 4393:                 if ($userenv->{$envkey}) {
 4394:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4395:                 } else {
 4396:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4397:                 }
 4398:             }
 4399:             $changeHash->{$envkey} = $userenv->{$envkey};
 4400:             if (($env{'form.custom'.$tool} == 1) ||
 4401:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4402:                 if ($newval ne $userenv->{$envkey}) {
 4403:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4404:                                                     $context);
 4405:                     if ($changed->{$tool}) {
 4406:                         $newaccess->{$tool} = &mt('custom');
 4407:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4408:                             if ($newval =~ /^autolimit/) {
 4409:                                 if ($limit) {
 4410:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4411:                                 } else {
 4412:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4413:                                 }
 4414:                             } elsif ($newval) {
 4415:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 4416:                             } else {
 4417:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4418:                             }
 4419:                         } elsif ($context eq 'authordefaults') {
 4420:                             if ($tool eq 'editors') {
 4421:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4422:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$changeHash->{$envkey})));
 4423:                             } elsif ($tool eq 'managers') {
 4424:                                 if ($changeHash->{$envkey} eq '') {
 4425:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4426:                                 } else {
 4427:                                     my $managers = $changeHash->{$envkey};
 4428:                                     $managers =~ s/,/, /g;
 4429:                                     $newaccesstext->{$tool} = $managers;
 4430:                                 }
 4431:                             } elsif ($tool eq 'webdav') {
 4432:                                 if ($newval) {
 4433:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4434:                                 } else {
 4435:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4436:                                 }
 4437:                             }
 4438:                         } else {
 4439:                             if ($newval) {
 4440:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4441:                             } else {
 4442:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4443:                             }
 4444:                         }
 4445:                     } else {
 4446:                         $newaccess->{$tool} = $oldaccess->{$tool};
 4447:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4448:                             if ($userenv->{$envkey} =~ /^autolimit/) {
 4449:                                 if ($limit) {
 4450:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4451:                                 } else {
 4452:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4453:                                 }
 4454:                             } elsif ($userenv->{$envkey}) {
 4455:                                 $newaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4456:                             } else {
 4457:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4458:                             }
 4459:                         } elsif ($context eq 'authordefaults') {
 4460:                             if ($tool eq 'editors') {
 4461:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4462:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4463:                             } elsif ($tool eq 'managers') {
 4464:                                 if ($userenv->{$envkey} eq '') {
 4465:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4466:                                 } else {
 4467:                                     my $managers = $userenv->{$envkey};
 4468:                                     $managers =~ s/,/, /g;
 4469:                                     $newaccesstext->{$tool} = $managers;
 4470:                                 }
 4471:                             } elsif ($tool eq 'webdav') {
 4472:                                 if ($userenv->{$envkey}) {
 4473:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4474:                                 } else {
 4475:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4476:                                 }
 4477:                             }
 4478:                         } else {
 4479:                             if ($userenv->{$context.'.'.$tool}) {
 4480:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4481:                             } else {
 4482:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4483:                             }
 4484:                         }
 4485:                     }
 4486:                 } else {
 4487:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4488:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4489:                 }
 4490:             } else {
 4491:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 4492:                 if ($changed->{$tool}) {
 4493:                     $newaccess->{$tool} = &mt('default');
 4494:                 } else {
 4495:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4496:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4497:                         if ($newval =~ /^autolimit/) {
 4498:                             if ($limit) {
 4499:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4500:                             } else {
 4501:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4502:                             }
 4503:                         } elsif ($newval) {
 4504:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4505:                         } else {
 4506:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4507:                         }
 4508:                     } elsif ($context eq 'authordefaults') {
 4509:                         if ($tool eq 'editors') {
 4510:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4511:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4512:                         } elsif ($tool eq 'managers') {
 4513:                             if ($newval eq '') {
 4514:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4515:                             } else {
 4516:                                 my $managers = $newval;
 4517:                                 $managers =~ s/,/, /g;
 4518:                                 $newaccesstext->{$tool} = $managers;
 4519:                             }
 4520:                         } elsif ($tool eq 'webdav') {
 4521:                             if ($userenv->{$envkey}) {
 4522:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4523:                             } else {
 4524:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4525:                             }
 4526:                         }
 4527:                     } else {
 4528:                         if ($userenv->{$context.'.'.$tool}) {
 4529:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4530:                         } else {
 4531:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4532:                         }
 4533:                     }
 4534:                 }
 4535:             }
 4536:         } else {
 4537:             $oldaccess->{$tool} = &mt('default');
 4538:             if (($env{'form.custom'.$tool} == 1) ||
 4539:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4540:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4541:                                                 $context);
 4542:                 if ($changed->{$tool}) {
 4543:                     $newaccess->{$tool} = &mt('custom');
 4544:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4545:                         if ($newval =~ /^autolimit/) {
 4546:                             if ($limit) {
 4547:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4548:                             } else {
 4549:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4550:                             }
 4551:                         } elsif ($newval) {
 4552:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4553:                         } else {
 4554:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4555:                         }
 4556:                     } elsif ($context eq 'authordefaults') {
 4557:                         if ($tool eq 'managers') {
 4558:                             if ($newval eq '') {
 4559:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4560:                             } else {
 4561:                                 my $managers = $newval;
 4562:                                 $managers =~ s/,/, /g;
 4563:                                 $newaccesstext->{$tool} = $managers;
 4564:                             }
 4565:                         } elsif ($tool eq 'editors') {
 4566:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4567:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4568:                         } elsif ($tool eq 'webdav') {
 4569:                             if ($newval) {
 4570:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4571:                             } else {
 4572:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4573:                             }
 4574:                         }
 4575:                     } else {
 4576:                         if ($newval) {
 4577:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4578:                         } else {
 4579:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4580:                         }
 4581:                     }
 4582:                 } else {
 4583:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4584:                 }
 4585:             } else {
 4586:                 $newaccess->{$tool} = $oldaccess->{$tool};
 4587:             }
 4588:         }
 4589:     }
 4590:     return;
 4591: }
 4592: 
 4593: sub update_roles {
 4594:     my ($r,$context,$showcredits) = @_;
 4595:     my $now=time;
 4596:     my @rolechanges;
 4597:     my (%disallowed,%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 4598:         %pending,%reject,%notifydc,%status,%unauthorized,%currqueued);
 4599:     $got_role_approvals{$context} = '';
 4600:     $process_by{$context} = {};
 4601:     my @domroles = &Apache::lonuserutils::domain_roles();
 4602:     my @cstrroles = &Apache::lonuserutils::construction_space_roles();
 4603:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
 4604:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 4605:     foreach my $key (keys(%env)) {
 4606: 	next if (! $env{$key});
 4607:         next if ($key eq 'form.action');
 4608: 	# Revoke roles
 4609: 	if ($key=~/^form\.rev/) {
 4610: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 4611: # Revoke standard role
 4612: 		my ($scope,$role) = ($1,$2);
 4613: 		my $result =
 4614: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 4615: 						$env{'form.ccuname'},
 4616: 						$scope,$role,'','',$context);
 4617:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4618:                             &mt('Revoking [_1] in [_2]',
 4619:                                 &Apache::lonnet::plaintext($role),
 4620:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4621:                                 $result ne "ok").'<br />');
 4622:                 if ($result ne "ok") {
 4623:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4624:                 }
 4625: 		if ($role eq 'st') {
 4626: 		    my $result = 
 4627:                         &Apache::lonuserutils::classlist_drop($scope,
 4628:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4629: 			    $now);
 4630:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4631: 		}
 4632:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4633:                     push(@rolechanges,$role);
 4634:                 }
 4635: 	    }
 4636: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4637: # Revoke custom role
 4638:                 my $result = &Apache::lonnet::revokecustomrole(
 4639:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4640:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4641:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4642:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4643:                             $result ne 'ok').'<br />');
 4644:                 if ($result ne "ok") {
 4645:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4646:                 }
 4647:                 if (!grep(/^cr$/,@rolechanges)) {
 4648:                     push(@rolechanges,'cr');
 4649:                 }
 4650: 	    }
 4651: 	} elsif ($key=~/^form\.del/) {
 4652: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4653: # Delete standard role
 4654: 		my ($scope,$role) = ($1,$2);
 4655: 		my $result =
 4656: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4657: 						$env{'form.ccuname'},
 4658: 						$scope,$role,$now,0,1,'',
 4659:                                                 $context);
 4660:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4661:                             &mt('Deleting [_1] in [_2]',
 4662:                                 &Apache::lonnet::plaintext($role),
 4663:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4664:                             $result ne 'ok').'<br />');
 4665:                 if ($result ne "ok") {
 4666:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4667:                 }
 4668: 
 4669: 		if ($role eq 'st') {
 4670: 		    my $result = 
 4671:                         &Apache::lonuserutils::classlist_drop($scope,
 4672:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4673: 			    $now);
 4674: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4675: 		}
 4676:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4677:                     push(@rolechanges,$role);
 4678:                 }
 4679:             }
 4680: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4681:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4682: # Delete custom role
 4683:                 my $result =
 4684:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4685:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4686:                         0,1,$context);
 4687:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4688:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4689:                       $result ne "ok").'<br />');
 4690:                 if ($result ne "ok") {
 4691:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4692:                 }
 4693: 
 4694:                 if (!grep(/^cr$/,@rolechanges)) {
 4695:                     push(@rolechanges,'cr');
 4696:                 }
 4697:             }
 4698: 	} elsif ($key=~/^form\.ren/) {
 4699:             my $udom = $env{'form.ccdomain'};
 4700:             my $uname = $env{'form.ccuname'};
 4701: # Re-enable standard role
 4702: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4703:                 my $url = $1;
 4704:                 my $role = $2;
 4705:                 my $id = $url.'_'.$role;
 4706:                 my $logmsg;
 4707:                 my $output;
 4708:                 if ($role eq 'st') {
 4709:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4710:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4711:                         my $credits;
 4712:                         if ($showcredits) {
 4713:                             my $defaultcredits =
 4714:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4715:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4716:                         }
 4717:                         unless ($udom eq $cdom) {
 4718:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4719:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,$credits,
 4720:                                          \%process_by,\%instdoms,\%got_role_approvals,
 4721:                                          \%got_instdoms,\%reject,\%pending,\%notifydc,
 4722:                                          \%status,\%unauthorized,\%currqueued));
 4723:                         }
 4724:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4725:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4726:                             if ($result eq 'refused' && $logmsg) {
 4727:                                 $output = $logmsg;
 4728:                             } else { 
 4729:                                 $output = &mt('Error: [_1]',$result)."\n";
 4730:                             }
 4731:                         } else {
 4732:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4733:                                         &Apache::lonnet::plaintext($role),
 4734:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4735:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4736:                         }
 4737:                     }
 4738:                 } else {
 4739:                     my ($cdom,$cnum,$csec);
 4740:                     if (grep(/^\Q$role\E$/,@cstrroles)) {
 4741:                         ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_username)$});
 4742:                     } elsif (grep(/^\Q$role\E$/,@domroles)) {
 4743:                         ($cdom) = ($url =~ m{^/($match_domain)/$});
 4744:                     } elsif ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4745:                         ($cdom,$cnum,$csec) = ($1,$2,$3);
 4746:                     }
 4747:                     if ($cdom ne '') {
 4748:                         unless ($udom eq $cdom) {
 4749:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4750:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4751:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4752:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4753:                         }
 4754:                     }
 4755: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4756:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4757:                                $context);
 4758:                     $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4759:                                     &Apache::lonnet::plaintext($role),
 4760:                                     &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4761:                     if ($result ne "ok") {
 4762:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4763:                     }
 4764:                 }
 4765:                 $r->print($output);
 4766:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4767:                     push(@rolechanges,$role);
 4768:                 }
 4769: 	    }
 4770: # Re-enable custom role
 4771: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4772:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4773:                 my $id = $url.'_cr'."/$rdom/$rnam/$rolename";
 4774:                 my $role = "cr/$rdom/$rnam/$rolename";
 4775:                 if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4776:                     my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4777:                     unless ($udom eq $cdom) {
 4778:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4779:                                      $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4780:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4781:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4782:                     }
 4783:                 }
 4784:                 my $result = &Apache::lonnet::assigncustomrole(
 4785:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4786:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4787:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4788:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4789:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4790:                     $result ne "ok").'<br />');
 4791:                 if ($result ne "ok") {
 4792:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4793:                 }
 4794:                 if (!grep(/^cr$/,@rolechanges)) {
 4795:                     push(@rolechanges,'cr');
 4796:                 }
 4797:             }
 4798: 	} elsif ($key=~/^form\.act/) {
 4799:             my $udom = $env{'form.ccdomain'};
 4800:             my $uname = $env{'form.ccuname'};
 4801: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4802:                 # Activate a custom role
 4803: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4804: 		my $url='/'.$one.'/'.$two;
 4805:                 my $id = $url.'_cr/'."$three/$four/$five";
 4806:                 my $role = "cr/$three/$four/$five";
 4807: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4808: 
 4809:                 my $start = ( $env{'form.start_'.$full} ?
 4810:                               $env{'form.start_'.$full} :
 4811:                               $now );
 4812:                 my $end   = ( $env{'form.end_'.$full} ?
 4813:                               $env{'form.end_'.$full} :
 4814:                               0 );
 4815: 
 4816:                 # split multiple sections
 4817:                 my %sections = ();
 4818:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$five);
 4819:                 if ($num_sections == 0) {
 4820:                     unless ($udom eq $one) {
 4821:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4822:                                      $uname,$role,$start,$end,$one,$two,'','',\%process_by,
 4823:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4824:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4825:                     }
 4826:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4827:                 } else {
 4828: 		    my %curr_groups =
 4829: 			&Apache::longroup::coursegroups($one,$two);
 4830:                     my ($restricted,$numchanges);
 4831:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4832:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4833:                             exists($curr_groups{$sec})) {
 4834:                             $disallowed{$sec} = $url;
 4835:                             next;
 4836:                         }
 4837:                         my $securl = $url.'/'.$sec;
 4838:                         my $secid = $securl.'_cr'."/$three/$four/$five";
 4839:                         undef($restricted);
 4840:                         unless ($udom eq $one) {
 4841:                             next if (&Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4842:                                          $uname,$role,$start,$end,$one,$two,$sec,'',\%process_by,
 4843:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4844:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4845:                         }
 4846:                         $numchanges ++;
 4847: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4848:                     }
 4849:                     next unless ($numchanges);
 4850:                 }
 4851:                 if (!grep(/^cr$/,@rolechanges)) {
 4852:                     push(@rolechanges,'cr');
 4853:                 }
 4854: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4855: 		# Activate roles for sections with 3 id numbers
 4856: 		# set start, end times, and the url for the class
 4857: 		my ($one,$two,$three)=($1,$2,$3);
 4858: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ?
 4859: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} :
 4860: 			      $now );
 4861: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ?
 4862: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4863: 			      0 );
 4864: 		my $url='/'.$one.'/'.$two;
 4865:                 my $id = $url.'_'.$three;
 4866:                 # split multiple sections
 4867:                 my %sections = ();
 4868:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4869:                 my ($credits,$numchanges);
 4870:                 if ($three eq 'st') {
 4871:                     if ($showcredits) {
 4872:                         my $defaultcredits = 
 4873:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4874:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4875:                         $credits =~ s/[^\d\.]//g;
 4876:                         if ($credits eq $defaultcredits) {
 4877:                             undef($credits);
 4878:                         }
 4879:                     }
 4880:                 }
 4881:                 if ($num_sections == 0) {
 4882:                     unless ($udom eq $one) {
 4883:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4884:                                      $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4885:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4886:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4887:                     }
 4888:                     $numchanges ++;
 4889:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4890:                 } else {
 4891:                     my %curr_groups = 
 4892: 			&Apache::longroup::coursegroups($one,$two);
 4893:                     my $emptysec = 0;
 4894:                     my $restricted;
 4895:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4896:                         $sec =~ s/\W//g;
 4897:                         if ($sec ne '') {
 4898:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4899:                                 exists($curr_groups{$sec})) {
 4900:                                 $disallowed{$sec} = $url;
 4901:                                 next;
 4902:                             }
 4903:                             my $securl = $url.'/'.$sec;
 4904:                             my $secid = $securl.'_'.$three;
 4905:                             unless ($udom eq $one) {
 4906:                                 undef($restricted);
 4907:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4908:                                                   $uname,$three,$start,$end,$one,$two,$sec,$credits,\%process_by,
 4909:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4910:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4911:                                 next if ($restricted);
 4912:                             }
 4913:                             $numchanges ++;
 4914:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4915:                         } else {
 4916:                             $emptysec = 1;
 4917:                         }
 4918:                     }
 4919:                     if ($emptysec) {
 4920:                         unless ($udom eq $one) {
 4921:                             undef($restricted);
 4922:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4923:                                               $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4924:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4925:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4926:                             next if ($restricted);
 4927:                         }
 4928:                         $numchanges ++;
 4929:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4930:                     }
 4931:                     next unless ($numchanges);
 4932:                 }
 4933:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4934:                     push(@rolechanges,$three);
 4935:                 }
 4936: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4937: 		# Activate roles for sections with two id numbers
 4938: 		# set start, end times, and the url for the class
 4939: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ?
 4940: 			      $env{'form.start_'.$1.'_'.$2} :
 4941: 			      $now );
 4942: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ?
 4943: 			      $env{'form.end_'.$1.'_'.$2} :
 4944: 			      0 );
 4945:                 my $one = $1;
 4946:                 my $two = $2;
 4947: 		my $url='/'.$one.'/';
 4948:                 my $id = $url.'_'.$two;
 4949:                 my ($cdom,$cnum) = split(/\//,$one);
 4950:                 # split multiple sections
 4951:                 my %sections = ();
 4952:                 my ($restricted,$numchanges);
 4953:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4954:                 if ($num_sections == 0) {
 4955:                     unless ($udom eq $one) {
 4956:                         $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4957:                                           $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4958:                                           \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4959:                                           \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4960:                         next if ($restricted);
 4961:                     }
 4962:                     $numchanges ++;
 4963:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4964:                 } else {
 4965:                     my $emptysec = 0;
 4966:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4967:                         if ($sec ne '') {
 4968:                             my $securl = $url.'/'.$sec;
 4969:                             my $secid = $securl.'_'.$two;
 4970:                             unless ($udom eq $one) {
 4971:                                 undef($restricted);
 4972:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4973:                                                   $uname,$two,$start,$end,$cdom,$cnum,$sec,'',\%process_by,
 4974:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4975:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4976:                                 next if ($restricted);
 4977:                             }
 4978:                             $numchanges ++;
 4979:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4980:                         } else {
 4981:                             $emptysec = 1;
 4982:                         }
 4983:                     }
 4984:                     if ($emptysec) {
 4985:                         unless ($udom eq $one) {
 4986:                             undef($restricted);
 4987:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4988:                                               $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 4989:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4990:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4991:                             next if ($restricted);
 4992:                         }
 4993:                         $numchanges ++;
 4994:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4995:                     }
 4996:                     next unless ($numchanges); 
 4997:                 }
 4998:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4999:                     push(@rolechanges,$two);
 5000:                 }
 5001: 	    } else {
 5002: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 5003:             }
 5004:             foreach my $key (sort(keys(%disallowed))) {
 5005:                 $r->print('<p class="LC_warning">');
 5006:                 if (($key eq 'none') || ($key eq 'all')) {  
 5007:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 5008:                 } else {
 5009:                     $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>'));
 5010:                 }
 5011:                 $r->print('</p><p>'
 5012:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 5013:                              ,'<a href="javascript:history.go(-1)'
 5014:                              ,'</a>')
 5015:                          .'</p><br />'
 5016:                 );
 5017:             }
 5018: 	}
 5019:     } # End of foreach (keys(%env))
 5020:     if ((keys(%reject)) || (keys(%unauthorized))) {
 5021:         $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5022:     }
 5023:     if ((keys(%pending)) || (keys(%currqueued))) {
 5024:         $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5025:     }
 5026: # Flush the course logs so reverse user roles immediately updated
 5027:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5028:     if (@rolechanges == 0) {
 5029:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 5030:     }
 5031:     return @rolechanges;
 5032: }
 5033: 
 5034: sub get_user_credits {
 5035:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 5036:     if ($cdom eq '' || $cnum eq '') {
 5037:         return unless ($env{'request.course.id'});
 5038:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5039:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5040:     }
 5041:     my $credits;
 5042:     my %currhash =
 5043:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 5044:     if (keys(%currhash) > 0) {
 5045:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 5046:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 5047:         $credits = $items[$crdidx];
 5048:         $credits =~ s/[^\d\.]//g;
 5049:     }
 5050:     if ($credits eq $defaultcredits) {
 5051:         undef($credits);
 5052:     }
 5053:     return $credits;
 5054: }
 5055: 
 5056: sub enroll_single_student {
 5057:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 5058:         $showcredits,$defaultcredits) = @_;
 5059:     $r->print('<h3>');
 5060:     if ($crstype eq 'Community') {
 5061:         $r->print(&mt('Enrolling Member'));
 5062:     } else {
 5063:         $r->print(&mt('Enrolling Student'));
 5064:     }
 5065:     $r->print('</h3>');
 5066: 
 5067:     # Remove non alphanumeric values from section
 5068:     $env{'form.sections'}=~s/\W//g;
 5069: 
 5070:     my $credits;
 5071:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 5072:         $credits = $env{'form.credits'};
 5073:         $credits =~ s/[^\d\.]//g;
 5074:         if ($credits ne '') {
 5075:             if ($credits eq $defaultcredits) {
 5076:                 undef($credits);
 5077:             }
 5078:         }
 5079:     }
 5080:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 5081:     my (%got_role_approvals,%got_instdoms,%process_by,%instdoms,%pending,%reject,%notifydc,
 5082:         %status,%unauthorized,%currqueued);
 5083:     unless ($env{'form.ccdomain'} eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 5084:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5085:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5086:         my $csec = $env{'form.sections'};
 5087:         my $id = "/$cdom/$cnum";
 5088:         if ($csec ne '') {
 5089:             $id .= "/$csec";
 5090:         }
 5091:         $id .= '_st';
 5092:         if (&Apache::lonuserutils::restricted_dom($context,$id,$env{'form.ccdomain'},$env{'form.ccuname'},
 5093:                                                   'st',$startdate,$enddate,$cdom,$cnum,$csec,$credits,
 5094:                                                   \%process_by,\%instdoms,\%got_role_approvals,\%got_instdoms,
 5095:                                                   \%reject,\%pending,\%notifydc,\%status,\%unauthorized,\%currqueued)) {
 5096:             if ((keys(%reject)) || (keys(%unauthorized))) {
 5097:                 $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5098:             }
 5099:             if ((keys(%pending)) || (keys(%currqueued))) {
 5100:                 $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5101:             }
 5102:             return;
 5103:         }
 5104:     }
 5105: 
 5106:     # Clean out any old student roles the user has in this class.
 5107:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 5108:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 5109:     my $enroll_result =
 5110:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 5111:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 5112:             $env{'form.cmiddlename'},$env{'form.clastname'},
 5113:             $env{'form.generation'},$env{'form.sections'},$enddate,
 5114:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 5115:             $credits);
 5116:     if ($enroll_result =~ /^ok/) {
 5117:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 5118:         if ($env{'form.sections'} ne '') {
 5119:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 5120:         }
 5121:         my ($showstart,$showend);
 5122:         if ($startdate <= $now) {
 5123:             $showstart = &mt('Access starts immediately');
 5124:         } else {
 5125:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 5126:         }
 5127:         if ($enddate == 0) {
 5128:             $showend = &mt('ends: no ending date');
 5129:         } else {
 5130:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 5131:         }
 5132:         $r->print('.<br />'.$showstart.'; '.$showend);
 5133:         if ($startdate <= $now && !$newuser) {
 5134:             $r->print('<p class="LC_info">');
 5135:             if ($crstype eq 'Community') {
 5136:                 $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.'));
 5137:             } else {
 5138:                 $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.'));
 5139:            }
 5140:            $r->print('</p>');
 5141:         }
 5142:     } else {
 5143:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 5144:     }
 5145:     return;
 5146: }
 5147: 
 5148: sub get_defaultquota_text {
 5149:     my ($settingstatus) = @_;
 5150:     my $defquotatext; 
 5151:     if ($settingstatus eq '') {
 5152:         $defquotatext = &mt('default');
 5153:     } else {
 5154:         my ($usertypes,$order) =
 5155:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 5156:         if ($usertypes->{$settingstatus} eq '') {
 5157:             $defquotatext = &mt('default');
 5158:         } else {
 5159:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 5160:         }
 5161:     }
 5162:     return $defquotatext;
 5163: }
 5164: 
 5165: sub update_result_form {
 5166:     my ($uhome) = @_;
 5167:     my $outcome = 
 5168:     '<form name="userupdate" method="post" action="">'."\n";
 5169:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 5170:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5171:     }
 5172:     if ($env{'form.origname'} ne '') {
 5173:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 5174:     }
 5175:     foreach my $item ('sortby','seluname','seludom') {
 5176:         if (exists($env{'form.'.$item})) {
 5177:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5178:         }
 5179:     }
 5180:     if ($uhome eq 'no_host') {
 5181:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 5182:     }
 5183:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 5184:                 '<input type="hidden" name="currstate" value="" />'."\n".
 5185:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5186:                 '</form>';
 5187:     return $outcome;
 5188: }
 5189: 
 5190: sub quota_admin {
 5191:     my ($setquota,$changeHash,$name) = @_;
 5192:     my $quotachanged;
 5193:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 5194:         # Current user has quota modification privileges
 5195:         if (ref($changeHash) eq 'HASH') {
 5196:             $quotachanged = 1;
 5197:             $changeHash->{$name.'quota'} = $setquota;
 5198:         }
 5199:     }
 5200:     return $quotachanged;
 5201: }
 5202: 
 5203: sub tool_admin {
 5204:     my ($tool,$settool,$changeHash,$context) = @_;
 5205:     my $canchange = 0; 
 5206:     if ($context eq 'requestcourses') {
 5207:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 5208:             $canchange = 1;
 5209:         }
 5210:     } elsif ($context eq 'reqcrsotherdom') {
 5211:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 5212:             $canchange = 1;
 5213:         }
 5214:     } elsif ($context eq 'requestauthor') {
 5215:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5216:             $canchange = 1;
 5217:         }
 5218:     } elsif ($context eq 'authordefaults') {
 5219:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5220:             $canchange = 1;
 5221:         }
 5222:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 5223:         # Current user has quota modification privileges
 5224:         $canchange = 1;
 5225:     }
 5226:     my $toolchanged;
 5227:     if ($canchange) {
 5228:         if (ref($changeHash) eq 'HASH') {
 5229:             $toolchanged = 1;
 5230:             if ($tool eq 'requestauthor') {
 5231:                 $changeHash->{$context} = $settool;
 5232:             } elsif (($tool eq 'managers') || ($tool eq 'editors')) {
 5233:                 $changeHash->{'author'.$tool} = $settool;
 5234:             } elsif ($tool eq 'webdav') {
 5235:                 $changeHash->{'tools.'.$tool} = $settool;
 5236:             } else {
 5237:                 $changeHash->{$context.'.'.$tool} = $settool;
 5238:             }
 5239:         }
 5240:     }
 5241:     return $toolchanged;
 5242: }
 5243: 
 5244: sub build_roles {
 5245:     my ($sectionstr,$sections,$role) = @_;
 5246:     my $num_sections = 0;
 5247:     if ($sectionstr=~ /,/) {
 5248:         my @secnums = split/,/,$sectionstr;
 5249:         if ($role eq 'st') {
 5250:             $secnums[0] =~ s/\W//g;
 5251:             $$sections{$secnums[0]} = 1;
 5252:             $num_sections = 1;
 5253:         } else {
 5254:             foreach my $sec (@secnums) {
 5255:                 $sec =~ ~s/\W//g;
 5256:                 if (!($sec eq "")) {
 5257:                     if (exists($$sections{$sec})) {
 5258:                         $$sections{$sec} ++;
 5259:                     } else {
 5260:                         $$sections{$sec} = 1;
 5261:                         $num_sections ++;
 5262:                     }
 5263:                 }
 5264:             }
 5265:         }
 5266:     } else {
 5267:         $sectionstr=~s/\W//g;
 5268:         unless ($sectionstr eq '') {
 5269:             $$sections{$sectionstr} = 1;
 5270:             $num_sections ++;
 5271:         }
 5272:     }
 5273: 
 5274:     return $num_sections;
 5275: }
 5276: 
 5277: # ========================================================== Custom Role Editor
 5278: 
 5279: sub custom_role_editor {
 5280:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5281:     my $action = $env{'form.customroleaction'};
 5282:     my ($rolename,$helpitem);
 5283:     if ($action eq 'new') {
 5284:         $rolename=$env{'form.newrolename'};
 5285:     } else {
 5286:         $rolename=$env{'form.rolename'};
 5287:     }
 5288: 
 5289:     my ($crstype,$context);
 5290:     if ($env{'request.course.id'}) {
 5291:         $crstype = &Apache::loncommon::course_type();
 5292:         $context = 'course';
 5293:         $helpitem = 'Course_Editing_Custom_Roles';
 5294:     } else {
 5295:         $context = 'domain';
 5296:         $crstype = 'course';
 5297:         $helpitem = 'Domain_Editing_Custom_Roles';
 5298:     }
 5299: 
 5300:     $rolename=~s/[^A-Za-z0-9]//gs;
 5301:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 5302: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 5303:                                    $permission);
 5304:         return;
 5305:     }
 5306: 
 5307:     my $formname = 'form1';
 5308:     my %privs=();
 5309:     my $body_top = '<h2>';
 5310: # ------------------------------------------------------- Does this role exist?
 5311:     my ($rdummy,$roledef)=
 5312: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5313:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5314:         $body_top .= &mt('Existing Role').' "';
 5315: # ------------------------------------------------- Get current role privileges
 5316:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 5317:         if ($privs{'system'} =~ /bre\&S/) {
 5318:             if ($context eq 'domain') {
 5319:                 $crstype = 'Course';
 5320:             } elsif ($crstype eq 'Community') {
 5321:                 $privs{'system'} =~ s/bre\&S//;
 5322:             }
 5323:         } elsif ($context eq 'domain') {
 5324:             $crstype = 'Course';
 5325:         }
 5326:     } else {
 5327:         $body_top .= &mt('New Role').' "';
 5328:         $roledef='';
 5329:     }
 5330:     $body_top .= $rolename.'"</h2>';
 5331: 
 5332: # ------------------------------------------------------- What can be assigned?
 5333:     my %full=();
 5334:     my %levels=(
 5335:                  course => {},
 5336:                  domain => {},
 5337:                  system => {},
 5338:                );
 5339:     my %levelscurrent=(
 5340:                         course => {},
 5341:                         domain => {},
 5342:                         system => {},
 5343:                       );
 5344:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5345:     my ($jsback,$elements) = &crumb_utilities();
 5346:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5347:     my $head_script =
 5348:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 5349:                                                   \%full,\@templateroles,$jsback);
 5350:     push (@{$brcrum},
 5351:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 5352:                text => "Pick custom role",
 5353:                faq  => 282,bug=>'Instructor Interface',},
 5354:               {href => "javascript:backPage(document.$formname,'','')",
 5355:                text => "Edit custom role",
 5356:                faq  => 282,
 5357:                bug  => 'Instructor Interface',
 5358:                help => $helpitem}
 5359:               );
 5360:     my $args = { bread_crumbs          => $brcrum,
 5361:                  bread_crumbs_component => 'User Management'};
 5362:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 5363:                                              $head_script,$args).
 5364:               $body_top);
 5365:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 5366:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 5367:                                                         \@templateroles,$prefix));
 5368: 
 5369:     $r->print(<<ENDCCF);
 5370: <input type="hidden" name="phase" value="set_custom_roles" />
 5371: <input type="hidden" name="rolename" value="$rolename" />
 5372: ENDCCF
 5373:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5374:                                                        \%levelscurrent,$prefix));
 5375:     $r->print(&Apache::loncommon::end_data_table().
 5376:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 5377:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 5378:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 5379:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 5380:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 5381: }
 5382: 
 5383: # ---------------------------------------------------------- Call to definerole
 5384: sub set_custom_role {
 5385:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5386:     my $rolename=$env{'form.rolename'};
 5387:     $rolename=~s/[^A-Za-z0-9]//gs;
 5388:     if (!$rolename) {
 5389: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5390:         return;
 5391:     }
 5392:     my ($jsback,$elements) = &crumb_utilities();
 5393:     my $jscript = '<script type="text/javascript">'
 5394:                  .'// <![CDATA['."\n"
 5395:                  .$jsback."\n"
 5396:                  .'// ]]>'."\n"
 5397:                  .'</script>'."\n";
 5398:     my $helpitem = 'Course_Editing_Custom_Roles';
 5399:     if ($context eq 'domain') {
 5400:         $helpitem = 'Domain_Editing_Custom_Roles';
 5401:     }
 5402:     push(@{$brcrum},
 5403:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 5404:          text => "Pick custom role",
 5405:          faq  => 282,
 5406:          bug  => 'Instructor Interface',},
 5407:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 5408:          text => "Edit custom role",
 5409:          faq  => 282,
 5410:          bug  => 'Instructor Interface',},
 5411:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 5412:          text => "Result",
 5413:          faq  => 282,
 5414:          bug  => 'Instructor Interface',
 5415:          help => $helpitem,}
 5416:         );
 5417:     my $args = { bread_crumbs           => $brcrum,
 5418:                  bread_crumbs_component => 'User Management'};
 5419:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 5420: 
 5421:     my $newrole;
 5422:     my ($rdummy,$roledef)=
 5423: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5424: 
 5425: # ------------------------------------------------------- Does this role exist?
 5426:     $r->print('<h3>');
 5427:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5428: 	$r->print(&mt('Existing Role').' "');
 5429:     } else {
 5430: 	$r->print(&mt('New Role').' "');
 5431: 	$roledef='';
 5432:         $newrole = 1;
 5433:     }
 5434:     $r->print($rolename.'"</h3>');
 5435: # ------------------------------------------------- Assign role and show result
 5436: 
 5437:     my $errmsg;
 5438:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 5439:     # Assign role and return result
 5440:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 5441:                                              $newprivs{'c'});
 5442:     if ($result ne 'ok') {
 5443:         $errmsg = ': '.$result;
 5444:     }
 5445:     my $message =
 5446:         &Apache::lonhtmlcommon::confirm_success(
 5447:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 5448:     if ($env{'request.course.id'}) {
 5449:         my $url='/'.$env{'request.course.id'};
 5450:         $url=~s/\_/\//g;
 5451:         $result =
 5452:             &Apache::lonnet::assigncustomrole(
 5453:                 $env{'user.domain'},$env{'user.name'},
 5454:                 $url,
 5455:                 $env{'user.domain'},$env{'user.name'},
 5456:                 $rolename,undef,undef,undef,$context);
 5457:         if ($result ne 'ok') {
 5458:             $errmsg = ': '.$result;
 5459:         }
 5460:         $message .=
 5461:             '<br />'
 5462:            .&Apache::lonhtmlcommon::confirm_success(
 5463:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 5464:     }
 5465:     $r->print(
 5466:         &Apache::loncommon::confirmwrapper($message)
 5467:        .'<br />'
 5468:        .&Apache::lonhtmlcommon::actionbox([
 5469:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 5470:            .&mt('Create or edit another custom role')
 5471:            .'</a>'])
 5472:        .'<form name="customresult" method="post" action="">'
 5473:        .&Apache::lonhtmlcommon::echo_form_input([])
 5474:        .'</form>'
 5475:     );
 5476: }
 5477: 
 5478: sub show_role_requests {
 5479:     my ($caller,$dom) = @_;
 5480:     my $showrolereqs;
 5481:     my %domconfig = &Apache::lonnet::get_dom('configuration',['privacy'],$dom);
 5482:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 5483:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 5484:             my %approvalconf = %{$domconfig{'privacy'}{'approval'}};
 5485:             foreach my $key ('instdom','extdom') {
 5486:                 if (ref($approvalconf{$key}) eq 'HASH') {
 5487:                     if (keys(%{$approvalconf{$key}})) {
 5488:                         foreach my $context ('domain','author','course','community') {
 5489:                             if ($approvalconf{$key}{$context} eq $caller) {
 5490:                                 $showrolereqs = 1;
 5491:                                 last if ($showrolereqs);
 5492:                             }
 5493:                         }
 5494:                     }
 5495:                 }
 5496:                 last if ($showrolereqs);
 5497:             }
 5498:         }
 5499:     }
 5500:     return $showrolereqs;
 5501: }
 5502: 
 5503: sub display_coauthor_managers {
 5504:     my ($permission) = @_;
 5505:     my $output;
 5506:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5507:         $output = '<form action="/adm/createuser" method="post" name="camanagers">'.
 5508:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5509:                   '<p>';
 5510:         my (@possmanagers,@custommanagers);
 5511:         my %userenv =
 5512:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5513:                                              $env{'user.name'},
 5514:                                              'authormanagers');
 5515:         my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5516:                                                      ['active','future'],['ca']);
 5517:         if (keys(%ca_roles)) {
 5518:             foreach my $entry (sort(keys(%ca_roles))) {
 5519:                 if ($entry =~ /^($match_username\:$match_domain):ca$/) {
 5520:                     my $user = $1;
 5521:                     unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5522:                         push(@possmanagers,$user);
 5523:                     }
 5524:                 }
 5525:             }
 5526:         }
 5527:         if ($userenv{'authormanagers'} eq '') {
 5528:             $output .= &mt('Currently author manages co-author roles');
 5529:         } else {
 5530:             if (keys(%ca_roles)) {
 5531:                 foreach my $user (split(/,/,$userenv{'authormanagers'})) {
 5532:                     if ($user =~ /^($match_username)\:($match_domain)$/) {
 5533:                         if (exists($ca_roles{$user.':ca'})) {
 5534:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5535:                                 push(@custommanagers,$user);
 5536:                             }
 5537:                         }
 5538:                     }
 5539:                 }
 5540:             }
 5541:             if (@custommanagers) {
 5542:                 $output .= &mt('Co-authors with active or future roles who currently manage co-author roles: [_1]',
 5543:                               '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @custommanagers));
 5544:             } else {
 5545:                 $output .= &mt('Currently author manages co-author roles');
 5546:             }
 5547:         }
 5548:         $output .= "</p>\n";
 5549:         if (@possmanagers) {
 5550:             $output .= '<p>'.&mt('If checked, can manage').': ';
 5551:             foreach my $user (@possmanagers) {
 5552:                  my $checked;
 5553:                  if (grep(/^\Q$user\E$/,@custommanagers)) {
 5554:                      $checked = ' checked="checked"';
 5555:                  }
 5556:                  $output .= '<span style="LC_nobreak"><label>'.
 5557:                             '<input type="checkbox" name="custommanagers" '.
 5558:                             'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
 5559:                             &Apache::loncommon::plainname(split(/:/,$user))." ($user)".'</label></span> '."\n";
 5560:             }
 5561:             $output .= '<input type="hidden" name="state" value="process" /></p>'."\n".
 5562:                        '<p><input type="submit" value="'.&mt('Save changes').'" /></p>'."\n";
 5563:         } else {
 5564:             $output .= '<p>'.&mt('No co-author roles assignable as manager').'</p>';
 5565:         }
 5566:         $output .= '</form>';
 5567:     } else {
 5568:         $output = '<span class="LC_warning">'.
 5569:                   &mt('You do not have permission to perform this action').
 5570:                   '</span>';
 5571:     }
 5572:     return $output;
 5573: }
 5574: 
 5575: sub update_coauthor_managers {
 5576:     my ($permission) = @_;
 5577:     my $output;
 5578:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5579:         my ($current,$newval,@possibles,@managers);
 5580:         my %userenv =
 5581:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5582:                                              $env{'user.name'},
 5583:                                              'authormanagers');
 5584:         $current = $userenv{'authormanagers'};
 5585:         @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 5586:         if (@possibles) {
 5587:             my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5588:                                                          ['active','future'],['ca']);
 5589:             if (keys(%ca_roles)) {
 5590:                 foreach my $user (@possibles) {
 5591:                     if ($user =~ /^($match_username):($match_domain)$/) {
 5592:                         if (exists($ca_roles{$user.':ca'})) {
 5593:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5594:                                 push(@managers,$user);
 5595:                             }
 5596:                         }
 5597:                     }
 5598:                 }
 5599:                 if (@managers) {
 5600:                     $newval = join(',',sort(@managers));
 5601:                 }
 5602:             }
 5603:         }
 5604:         if ($current eq $newval) {
 5605:             $output = &mt('No changes made to management of co-author roles');
 5606:         } else {
 5607:             my $chgresult =
 5608:                 &Apache::lonnet::put('environment',{'authormanagers' => $newval},
 5609:                                      $env{'user.domain'},$env{'user.name'});
 5610:             if ($chgresult eq 'ok') {
 5611:                 &Apache::lonnet::appenv({'environment.authormanagers' => $newval});
 5612:                 my (@adds,@dels);
 5613:                 if ($newval eq '') {
 5614:                     @dels = split(/,/,$current);
 5615:                 } elsif ($current eq '') {
 5616:                     @adds = @managers;
 5617:                 } else {
 5618:                     my @old = split(/,/,$current);
 5619:                     my @diffs = &Apache::loncommon::compare_arrays(\@old,\@managers);
 5620:                     if (@diffs) {
 5621:                         foreach my $user (@diffs) {
 5622:                             if (grep(/^\Q$user\E$/,@old)) {
 5623:                                 push(@dels,$user);
 5624:                             } elsif (grep(/^\Q$user\E$/,@managers)) {
 5625:                                 push(@adds,$user);
 5626:                             }
 5627:                         }
 5628:                     }
 5629:                 }
 5630:                 my $key = "internal.manager./$env{'user.domain'}/$env{'user.name'}";
 5631:                 if (@dels) {
 5632:                     foreach my $user (@dels) {
 5633:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5634:                             &Apache::lonnet::del('environment',[$key],$2,$1);
 5635:                         }
 5636:                     }
 5637:                 }
 5638:                 if (@adds) {
 5639:                     foreach my $user (@adds) {
 5640:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5641:                             &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 5642:                         }
 5643:                     }
 5644:                 }
 5645:                 if ($newval eq '') {
 5646:                     $output = &mt('Management of co-authors set to be author-only');
 5647:                 } else {
 5648:                     $output .= &mt('Co-authors who can manage co-author roles set to: [_1]',
 5649:                                    '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @managers));
 5650:                 }
 5651:             }
 5652:         }
 5653:     } else {
 5654:         $output = '<span class="LC_warning">'.
 5655:                   &mt('You do not have permission to perform this action').
 5656:                   '</span>';
 5657:     }
 5658:     return $output;
 5659: }
 5660: 
 5661: # ================================================================ Main Handler
 5662: sub handler {
 5663:     my $r = shift;
 5664:     if ($r->header_only) {
 5665:        &Apache::loncommon::content_type($r,'text/html');
 5666:        $r->send_http_header;
 5667:        return OK;
 5668:     }
 5669:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 5670: 
 5671:     if ($env{'request.course.id'}) {
 5672:         $context = 'course';
 5673:         $crstype = &Apache::loncommon::course_type();
 5674:     } elsif ($env{'request.role'} =~ /^au\./) {
 5675:         $context = 'author';
 5676:     } elsif ($env{'request.role'} =~ m{^(ca|aa)\./$match_domain/$match_username$}) {
 5677:         $context = 'coauthor';
 5678:     } else {
 5679:         $context = 'domain';
 5680:     }
 5681: 
 5682:     my ($permission,$allowed) =
 5683:         &Apache::lonuserutils::get_permission($context,$crstype);
 5684:     if (($context eq 'coauthor') && ($allowed)) {
 5685:         $context = 'author';
 5686:     }
 5687: 
 5688:     if ($allowed) {
 5689:         my @allhelp;
 5690:         if ($context eq 'course') {
 5691:             $cid = $env{'request.course.id'};
 5692:             $cdom = $env{'course.'.$cid.'.domain'};
 5693:             $cnum = $env{'course.'.$cid.'.num'};
 5694: 
 5695:             if ($permission->{'cusr'}) {
 5696:                 push(@allhelp,'Course_Create_Class_List');
 5697:             }
 5698:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5699:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 5700:             }
 5701:             if ($permission->{'custom'}) {
 5702:                 push(@allhelp,'Course_Editing_Custom_Roles');
 5703:             }
 5704:             if ($permission->{'cusr'}) {
 5705:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 5706:             }
 5707:             unless ($permission->{'cusr_section'}) {
 5708:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 5709:                     push(@allhelp,'Course_Automated_Enrollment');
 5710:                 }
 5711:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 5712:                     push(@allhelp,'Course_Approve_Selfenroll');
 5713:                 }
 5714:             }
 5715:             if ($permission->{'grp_manage'}) {
 5716:                 push(@allhelp,'Course_Manage_Group');
 5717:             }
 5718:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5719:                 push(@allhelp,'Course_User_Logs');
 5720:             }
 5721:         } elsif ($context eq 'author') {
 5722:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5723:                            'Author_View_Coauthor_List','Author_User_Logs'));
 5724:         } elsif ($context eq 'coauthor') {
 5725:             if ($permission->{'cusr'}) {
 5726:                 push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5727:                                'Author_View_Coauthor_List','Author_User_Logs'));
 5728:             } elsif ($permission->{'view'}) {
 5729:                 push(@allhelp,'Author_View_Coauthor_List');
 5730:             }
 5731:         } else {
 5732:             if ($permission->{'cusr'}) {
 5733:                 push(@allhelp,'Domain_Change_Privileges');
 5734:                 if ($permission->{'activity'}) {
 5735:                     push(@allhelp,'Domain_User_Access_Logs');
 5736:                 }
 5737:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 5738:                 if ($permission->{'custom'}) {
 5739:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 5740:                 }
 5741:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 5742:             } elsif ($permission->{'view'}) {
 5743:                 push(@allhelp,'Domain_View_Privileges');
 5744:                 if ($permission->{'activity'}) {
 5745:                     push(@allhelp,'Domain_User_Access_Logs');
 5746:                 }
 5747:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 5748:             }
 5749:         }
 5750:         if (@allhelp) {
 5751:             $allhelpitems = join(',',@allhelp);
 5752:         }
 5753:     }
 5754: 
 5755:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5756:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 5757:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue',
 5758:          'forceedit']);
 5759:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5760:     my $args;
 5761:     my $brcrum = [];
 5762:     my $bread_crumbs_component = 'User Management';
 5763:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 5764:         $brcrum = [{href=>"/adm/createuser",
 5765:                     text=>"User Management",
 5766:                     help=>$allhelpitems}
 5767:                   ];
 5768:     }
 5769:     if (!$allowed) {
 5770:         if ($context eq 'course') {
 5771:             $r->internal_redirect('/adm/viewclasslist');
 5772:             return OK;
 5773:         } elsif ($context eq 'coauthor') {
 5774:             $r->internal_redirect('/adm/viewcoauthors');
 5775:             return OK;
 5776:         }
 5777:         $env{'user.error.msg'}=
 5778:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 5779:                                  "or view user status.";
 5780:         return HTTP_NOT_ACCEPTABLE;
 5781:     }
 5782: 
 5783:     &Apache::loncommon::content_type($r,'text/html');
 5784:     $r->send_http_header;
 5785: 
 5786:     my $showcredits;
 5787:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 5788:          ($context eq 'domain')) {
 5789:         my %domdefaults = 
 5790:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 5791:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 5792:             $showcredits = 1;
 5793:         }
 5794:     }
 5795: 
 5796:     # Main switch on form.action and form.state, as appropriate
 5797:     if (! exists($env{'form.action'})) {
 5798:         $args = {bread_crumbs => $brcrum,
 5799:                  bread_crumbs_component => $bread_crumbs_component}; 
 5800:         $r->print(&header(undef,$args));
 5801:         $r->print(&print_main_menu($permission,$context,$crstype));
 5802:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 5803:         my $helpitem = 'Course_Create_Class_List';
 5804:         if ($context eq 'author') {
 5805:             $helpitem = 'Author_Create_Coauthor_List';
 5806:         } elsif ($context eq 'domain') {
 5807:             $helpitem = 'Domain_Create_Users';
 5808:         }
 5809:         push(@{$brcrum},
 5810:               { href => '/adm/createuser?action=upload&state=',
 5811:                 text => 'Upload Users List',
 5812:                 help => $helpitem,
 5813:               });
 5814:         $bread_crumbs_component = 'Upload Users List';
 5815:         $args = {bread_crumbs           => $brcrum,
 5816:                  bread_crumbs_component => $bread_crumbs_component};
 5817:         $r->print(&header(undef,$args));
 5818:         $r->print('<form name="studentform" method="post" '.
 5819:                   'enctype="multipart/form-data" '.
 5820:                   ' action="/adm/createuser">'."\n");
 5821:         if (! exists($env{'form.state'})) {
 5822:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5823:         } elsif ($env{'form.state'} eq 'got_file') {
 5824:             my $result = 
 5825:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 5826:                                                                  $permission,
 5827:                                                                  $crstype,$showcredits);
 5828:             if ($result eq 'missingdata') {
 5829:                 delete($env{'form.state'});
 5830:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5831:             }
 5832:         } elsif ($env{'form.state'} eq 'enrolling') {
 5833:             if ($env{'form.datatoken'}) {
 5834:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 5835:                                                                     $permission,
 5836:                                                                     $showcredits);
 5837:                 if ($result eq 'missingdata') {
 5838:                     delete($env{'form.state'});
 5839:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5840:                 } elsif ($result eq 'invalidhome') {
 5841:                     $env{'form.state'} = 'got_file';
 5842:                     delete($env{'form.lcserver'});
 5843:                     my $result =
 5844:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 5845:                                                                          $crstype,$showcredits);
 5846:                     if ($result eq 'missingdata') {
 5847:                         delete($env{'form.state'});
 5848:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5849:                     }
 5850:                 }
 5851:             } else {
 5852:                 delete($env{'form.state'});
 5853:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5854:             }
 5855:         } else {
 5856:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5857:         }
 5858:         $r->print('</form>');
 5859:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 5860:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 5861:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 5862:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 5863:         my $phase = $env{'form.phase'};
 5864:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 5865: 	&Apache::loncreateuser::restore_prev_selections();
 5866: 	my $srch;
 5867: 	foreach my $item (@search) {
 5868: 	    $srch->{$item} = $env{'form.'.$item};
 5869: 	}
 5870:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 5871:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 5872:             if ($env{'form.phase'} eq 'createnewuser') {
 5873:                 my $response;
 5874:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 5875:                     my $response =
 5876:                         '<span class="LC_warning">'
 5877:                        .&mt('You must specify a valid username. Only the following are allowed:'
 5878:                            .' letters numbers - . @')
 5879:                        .'</span>';
 5880:                     $env{'form.phase'} = '';
 5881:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 5882:                                                $crstype,$brcrum,$permission);
 5883:                 } else {
 5884:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 5885:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 5886:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 5887:                                                   $srch,$response,$context,
 5888:                                                   $permission,$crstype,$brcrum,
 5889:                                                   $showcredits);
 5890:                 }
 5891:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 5892:                 my ($currstate,$response,$forcenewuser,$results) = 
 5893:                     &user_search_result($context,$srch);
 5894:                 if ($env{'form.currstate'} eq 'modify') {
 5895:                     $currstate = $env{'form.currstate'};
 5896:                 }
 5897:                 if ($currstate eq 'select') {
 5898:                     &print_user_selection_page($r,$response,$srch,$results,
 5899:                                                \@search,$context,undef,$crstype,
 5900:                                                $brcrum);
 5901:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 5902:                     my ($ccuname,$ccdomain,$uhome);
 5903:                     if (($srch->{'srchby'} eq 'uname') && 
 5904:                         ($srch->{'srchtype'} eq 'exact')) {
 5905:                         $ccuname = $srch->{'srchterm'};
 5906:                         $ccdomain= $srch->{'srchdomain'};
 5907:                     } else {
 5908:                         my @matchedunames = keys(%{$results});
 5909:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 5910:                     }
 5911:                     $ccuname =&LONCAPA::clean_username($ccuname);
 5912:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 5913:                     if ($env{'form.action'} eq 'accesslogs') {
 5914:                         my $uhome;
 5915:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 5916:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 5917:                         }
 5918:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 5919:                             $env{'form.phase'} = '';
 5920:                             undef($forcenewuser);
 5921:                             #if ($response) {
 5922:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 5923:                             #        $response .= '<br /><br />';
 5924:                             #    }
 5925:                             #}
 5926:                             &print_username_entry_form($r,$context,$response,$srch,
 5927:                                                        $forcenewuser,$crstype,$brcrum,
 5928:                                                        $permission);
 5929:                         } else {
 5930:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5931:                         }
 5932:                     } else {
 5933:                         if ($env{'form.forcenewuser'}) {
 5934:                             $response = '';
 5935:                         }
 5936:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 5937:                                                       $srch,$response,$context,
 5938:                                                       $permission,$crstype,$brcrum);
 5939:                     }
 5940:                 } elsif ($currstate eq 'query') {
 5941:                     &print_user_query_page($r,'createuser',$brcrum);
 5942:                 } else {
 5943:                     $env{'form.phase'} = '';
 5944:                     &print_username_entry_form($r,$context,$response,$srch,
 5945:                                                $forcenewuser,$crstype,$brcrum,
 5946:                                                $permission);
 5947:                 }
 5948:             } elsif ($env{'form.phase'} eq 'userpicked') {
 5949:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 5950:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 5951:                 if ($env{'form.action'} eq 'accesslogs') {
 5952:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5953:                 } else {
 5954:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 5955:                                                   $context,$permission,$crstype,
 5956:                                                   $brcrum);
 5957:                 }
 5958:             } elsif ($env{'form.action'} eq 'accesslogs') {
 5959:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 5960:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 5961:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5962:             }
 5963:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 5964:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 5965:         } else {
 5966:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 5967:                                        $brcrum,$permission);
 5968:         }
 5969:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 5970:         my $prefix;
 5971:         if ($env{'form.phase'} eq 'set_custom_roles') {
 5972:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 5973:         } else {
 5974:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5975:         }
 5976:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 5977:              ($permission->{'cusr'}) && 
 5978:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5979:         push(@{$brcrum},
 5980:                  {href => '/adm/createuser?action=processauthorreq',
 5981:                   text => 'Authoring Space requests',
 5982:                   help => 'Domain_Role_Approvals'});
 5983:         $bread_crumbs_component = 'Authoring requests';
 5984:         if ($env{'form.state'} eq 'done') {
 5985:             push(@{$brcrum},
 5986:                      {href => '/adm/createuser?action=authorreqqueue',
 5987:                       text => 'Result',
 5988:                       help => 'Domain_Role_Approvals'});
 5989:             $bread_crumbs_component = 'Authoring request result';
 5990:         }
 5991:         $args = { bread_crumbs           => $brcrum,
 5992:                   bread_crumbs_component => $bread_crumbs_component};
 5993:         my $js = &usernamerequest_javascript();
 5994:         $r->print(&header(&add_script($js),$args));
 5995:         if (!exists($env{'form.state'})) {
 5996:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 5997:                                                                             $env{'request.role.domain'}));
 5998:         } elsif ($env{'form.state'} eq 'done') {
 5999:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 6000:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 6001:                                                                          $env{'request.role.domain'}));
 6002:         }
 6003:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 6004:              ($permission->{'cusr'}) &&
 6005:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 6006:         push(@{$brcrum},
 6007:                  {href => '/adm/createuser?action=processusernamereq',
 6008:                   text => 'LON-CAPA account requests',
 6009:                   help => 'Domain_Username_Approvals'});
 6010:         $bread_crumbs_component = 'Account requests';
 6011:         if ($env{'form.state'} eq 'done') {
 6012:             push(@{$brcrum},
 6013:                      {href => '/adm/createuser?action=usernamereqqueue',
 6014:                       text => 'Result',
 6015:                       help => 'Domain_Username_Approvals'});
 6016:             $bread_crumbs_component = 'LON-CAPA account request result';
 6017:         }
 6018:         $args = { bread_crumbs           => $brcrum,
 6019:                   bread_crumbs_component => $bread_crumbs_component};
 6020:         my $js = &usernamerequest_javascript();
 6021:         $r->print(&header(&add_script($js),$args));
 6022:         if (!exists($env{'form.state'})) {
 6023:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 6024:                                                                             $env{'request.role.domain'}));
 6025:         } elsif ($env{'form.state'} eq 'done') {
 6026:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 6027:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 6028:                                                                          $env{'request.role.domain'}));
 6029:         }
 6030:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 6031:              ($permission->{'cusr'})) {
 6032:         my $dom = $env{'form.domain'};
 6033:         my $uname = $env{'form.username'};
 6034:         my $warning;
 6035:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 6036:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 6037:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 6038:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 6039:                     if ($uhome eq 'no_host') {
 6040:                         my $queue = $env{'form.queue'};
 6041:                         my $reqkey = &escape($uname).'_'.$queue; 
 6042:                         my $namespace = 'usernamequeue';
 6043:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 6044:                         my %queued =
 6045:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 6046:                         unless ($queued{$reqkey}) {
 6047:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 6048:                         }
 6049:                     } else {
 6050:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 6051:                     }
 6052:                 } else {
 6053:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 6054:                 }
 6055:             } else {
 6056:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 6057:             }
 6058:         } else {
 6059:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 6060:         }
 6061:         my $args = { only_body => 1 };
 6062:         $r->print(&header(undef,$args).
 6063:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 6064:         if ($warning ne '') {
 6065:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 6066:         } else {
 6067:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 6068:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 6069:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6070:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6071:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 6072:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 6073:                         my %info =
 6074:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 6075:                         if (ref($info{$uname}) eq 'HASH') {
 6076:                             my $usertype = $info{$uname}{'inststatus'};
 6077:                             unless ($usertype) {
 6078:                                 $usertype = 'default';
 6079:                             }
 6080:                             my ($showstatus,$showemail,$pickstart);
 6081:                             my $numextras = 0;
 6082:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6083:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 6084:                                 if (ref($usertypes) eq 'HASH') {
 6085:                                     if ($usertypes->{$usertype}) {
 6086:                                         $showstatus = $usertypes->{$usertype};
 6087:                                     } else {
 6088:                                         $showstatus = $othertitle;
 6089:                                     }
 6090:                                     if ($showstatus) {
 6091:                                         $numextras ++;
 6092:                                     }
 6093:                                 }
 6094:                             }
 6095:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 6096:                                 $showemail = $info{$uname}{'email'};
 6097:                                 $numextras ++;
 6098:                             }
 6099:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 6100:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 6101:                                     $pickstart = 1;
 6102:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6103:                                     my ($num,$count);
 6104:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 6105:                                     $count += $numextras;
 6106:                                     foreach my $field (@{$infofields}) {
 6107:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 6108:                                         next unless ($infotitles->{$field});
 6109:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 6110:                                                   $info{$uname}{$field});
 6111:                                         $num ++;
 6112:                                         unless ($count == $num) {
 6113:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 6114:                                         }
 6115:                                     }
 6116:                                 }
 6117:                             }
 6118:                             if ($numextras) {
 6119:                                 unless ($pickstart) {
 6120:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6121:                                     $pickstart = 1;
 6122:                                 }
 6123:                                 if ($showemail) {
 6124:                                     my $closure = '';
 6125:                                     unless ($showstatus) {
 6126:                                         $closure = 1;
 6127:                                     }
 6128:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 6129:                                               $showemail.
 6130:                                               &Apache::lonhtmlcommon::row_closure($closure));
 6131:                                 }
 6132:                                 if ($showstatus) {
 6133:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 6134:                                               $showstatus.
 6135:                                               &Apache::lonhtmlcommon::row_closure(1));
 6136:                                 }
 6137:                             }
 6138:                             if ($pickstart) { 
 6139:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 6140:                             } else {
 6141:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 6142:                             }
 6143:                         } else {
 6144:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 6145:                         }
 6146:                     }
 6147:                 }
 6148:             }
 6149:         }
 6150:         $r->print(&close_popup_form());
 6151:     } elsif (($env{'form.action'} eq 'listusers') && 
 6152:              ($permission->{'view'} || $permission->{'cusr'})) {
 6153:         my $helpitem = 'Course_View_Class_List';
 6154:         if ($context eq 'author') {
 6155:             $helpitem = 'Author_View_Coauthor_List';
 6156:         } elsif ($context eq 'domain') {
 6157:             $helpitem = 'Domain_View_Users_List';
 6158:         }
 6159:         if ($env{'form.phase'} eq 'bulkchange') {
 6160:             push(@{$brcrum},
 6161:                     {href => '/adm/createuser?action=listusers',
 6162:                      text => "List Users"},
 6163:                     {href => "/adm/createuser",
 6164:                      text => "Result",
 6165:                      help => $helpitem});
 6166:             $bread_crumbs_component = 'Update Users';
 6167:             $args = {bread_crumbs           => $brcrum,
 6168:                      bread_crumbs_component => $bread_crumbs_component};
 6169:             $r->print(&header(undef,$args));
 6170:             my $setting = $env{'form.roletype'};
 6171:             my $choice = $env{'form.bulkaction'};
 6172:             if ($permission->{'cusr'}) {
 6173:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 6174:             } else {
 6175:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 6176:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 6177:             }
 6178:         } else {
 6179:             push(@{$brcrum},
 6180:                     {href => '/adm/createuser?action=listusers',
 6181:                      text => "List Users",
 6182:                      help => $helpitem});
 6183:             $bread_crumbs_component = 'List Users';
 6184:             $args = {bread_crumbs           => $brcrum,
 6185:                      bread_crumbs_component => $bread_crumbs_component};
 6186:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 6187:             my $formname = 'studentform';
 6188:             my $hidecall = "hide_searching();";
 6189:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 6190:                 ($env{'form.roletype'} eq 'community'))) {
 6191:                 if ($env{'form.roletype'} eq 'course') {
 6192:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 6193:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 6194:                                                                 $formname);
 6195:                 } elsif ($env{'form.roletype'} eq 'community') {
 6196:                     $cb_jscript = 
 6197:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 6198:                     my %elements = (
 6199:                                       coursepick => 'radio',
 6200:                                       coursetotal => 'text',
 6201:                                       courselist => 'text',
 6202:                                    );
 6203:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 6204:                 }
 6205:                 $jscript .= &verify_user_display($context)."\n".
 6206:                             &Apache::loncommon::check_uncheck_jscript();
 6207:                 my $js = &add_script($jscript).$cb_jscript;
 6208:                 my $loadcode = 
 6209:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 6210:                 if ($loadcode ne '') {
 6211:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 6212:                 } else {
 6213:                     $args->{add_entries} = {onload => $hidecall};
 6214:                 }
 6215:                 $r->print(&header($js,$args));
 6216:             } else {
 6217:                 $args->{add_entries} = {onload => $hidecall};
 6218:                 $jscript = &verify_user_display($context).
 6219:                            &Apache::loncommon::check_uncheck_jscript(); 
 6220:                 $r->print(&header(&add_script($jscript),$args));
 6221:             }
 6222:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 6223:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 6224:                          $showcredits);
 6225:         }
 6226:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 6227:         my $brtext;
 6228:         if ($crstype eq 'Community') {
 6229:             $brtext = 'Drop Members';
 6230:         } else {
 6231:             $brtext = 'Drop Students';
 6232:         }
 6233:         push(@{$brcrum},
 6234:                 {href => '/adm/createuser?action=drop',
 6235:                  text => $brtext,
 6236:                  help => 'Course_Drop_Student'});
 6237:         if ($env{'form.state'} eq 'done') {
 6238:             push(@{$brcrum},
 6239:                      {href=>'/adm/createuser?action=drop',
 6240:                       text=>"Result"});
 6241:         }
 6242:         $bread_crumbs_component = $brtext;
 6243:         $args = {bread_crumbs           => $brcrum,
 6244:                  bread_crumbs_component => $bread_crumbs_component}; 
 6245:         $r->print(&header(undef,$args));
 6246:         if (!exists($env{'form.state'})) {
 6247:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 6248:         } elsif ($env{'form.state'} eq 'done') {
 6249:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 6250:                                                     $env{'form.action'});
 6251:         }
 6252:     } elsif ($env{'form.action'} eq 'dateselect') {
 6253:         if ($permission->{'cusr'}) {
 6254:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6255:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 6256:                                                                    $crstype,$showcredits));
 6257:         } else {
 6258:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6259:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 6260:         }
 6261:     } elsif ($env{'form.action'} eq 'selfenroll') {
 6262:         my %currsettings;
 6263:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 6264:             %currsettings = (
 6265:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 6266:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 6267:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 6268:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 6269:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 6270:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 6271:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 6272:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 6273:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 6274:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 6275:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 6276:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 6277:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 6278:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 6279:             );
 6280:         }
 6281:         if ($permission->{selfenrolladmin}) {
 6282:             push(@{$brcrum},
 6283:                     {href => '/adm/createuser?action=selfenroll',
 6284:                      text => "Configure Self-enrollment",
 6285:                      help => 'Course_Self_Enrollment'});
 6286:             if (!exists($env{'form.state'})) {
 6287:                 $args = { bread_crumbs           => $brcrum,
 6288:                           bread_crumbs_component => 'Configure Self-enrollment'};
 6289:                 $r->print(&header(undef,$args));
 6290:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6291:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 6292:             } elsif ($env{'form.state'} eq 'done') {
 6293:                 push (@{$brcrum},
 6294:                           {href=>'/adm/createuser?action=selfenroll',
 6295:                            text=>"Result"});
 6296:                 $args = { bread_crumbs           => $brcrum,
 6297:                           bread_crumbs_component => 'Self-enrollment result'};
 6298:                 $r->print(&header(undef,$args));
 6299:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6300:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 6301:             }
 6302:         } elsif ($permission->{selfenrollview}) {
 6303:             push(@{$brcrum},
 6304:                     {href => '/adm/createuser?action=selfenroll',
 6305:                      text => "View Self-enrollment configuration",
 6306:                      help => 'Course_Self_Enrollment'});
 6307:             $args = { bread_crumbs           => $brcrum,
 6308:                       bread_crumbs_component => 'Self-enrollment Settings'};
 6309:             $r->print(&header(undef,$args));
 6310:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6311:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 6312:         } else {
 6313:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6314:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 6315:         }
 6316:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 6317:         if ($permission->{selfenrolladmin}) {
 6318:             push(@{$brcrum},
 6319:                      {href => '/adm/createuser?action=selfenrollqueue',
 6320:                       text => 'Enrollment requests',
 6321:                       help => 'Course_Approve_Selfenroll'});
 6322:             $bread_crumbs_component = 'Enrollment requests';
 6323:             if ($env{'form.state'} eq 'done') {
 6324:                 push(@{$brcrum},
 6325:                          {href => '/adm/createuser?action=selfenrollqueue',
 6326:                           text => 'Result',
 6327:                           help => 'Course_Approve_Selfenroll'});
 6328:                 $bread_crumbs_component = 'Enrollment result';
 6329:             }
 6330:             $args = { bread_crumbs           => $brcrum,
 6331:                       bread_crumbs_component => $bread_crumbs_component};
 6332:             $r->print(&header(undef,$args));
 6333:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6334:             if (!exists($env{'form.state'})) {
 6335:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 6336:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 6337:                                                                                 $cdom,$cnum));
 6338:             } elsif ($env{'form.state'} eq 'done') {
 6339:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 6340:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 6341:                               $cdom,$cnum,$coursedesc));
 6342:             }
 6343:         } else {
 6344:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6345:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 6346:         }
 6347:     } elsif ($env{'form.action'} eq 'changelogs') {
 6348:         if ($permission->{cusr} || $permission->{view}) {
 6349:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 6350:         } else {
 6351:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6352:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 6353:         }
 6354:     } elsif ($env{'form.action'} eq 'helpdesk') {
 6355:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6356:             ($permission->{'cusr'} || $permission->{'view'})) {
 6357:             if ($env{'form.state'} eq 'process') {
 6358:                 if ($permission->{'owner'}) {
 6359:                     &update_helpdeskaccess($r,$permission,$brcrum);
 6360:                 } else {
 6361:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 6362:                 }
 6363:             } else {
 6364:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 6365:             }
 6366:         } else {
 6367:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6368:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 6369:         }
 6370:     } elsif ($env{'form.action'} eq 'rolerequests') {
 6371:         if ($permission->{cusr} || $permission->{view}) {
 6372:             &print_queued_roles($r,$context,$permission,$brcrum);
 6373:         }
 6374:     } elsif ($env{'form.action'} eq 'queuedroles') {
 6375:         if (($permission->{cusr}) && ($context eq 'domain')) {
 6376:             if (&show_role_requests($context,$env{'request.role.domain'})) {
 6377:                 if ($env{'form.state'} eq 'done') {
 6378:                     &process_pendingroles($r,$context,$permission,$brcrum);
 6379:                 } else {
 6380:                     &print_pendingroles($r,$context,$permission,$brcrum);
 6381:                 }
 6382:             } else {
 6383:                 $r->print(&header(undef,{'no_nav_bar' => 1}).
 6384:                           '<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>');
 6385:             }
 6386:         } else {
 6387:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6388:                      '<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>');
 6389:         }
 6390:     } elsif ($env{'form.action'} eq 'camanagers') {
 6391:         if (($permission->{cusr}) && ($context eq 'author')) {
 6392:             push(@{$brcrum},
 6393:                      {href => '/adm/createuser?action=camanagers',
 6394:                       text => 'Co-author Managers',
 6395:                       help => 'Author_Manage_Coauthors'});
 6396:             if ($env{'form.state'} eq 'process') {
 6397:                 push(@{$brcrum},
 6398:                          {href => '/adm/createuser?action=camanagers',
 6399:                           text => 'Result',
 6400:                           help => 'Author_Manage_Coauthors'});
 6401:             }
 6402:             $args = { bread_crumbs           => $brcrum };
 6403:             $r->print(&header(undef,$args));
 6404:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6405:             if (!exists($env{'form.state'})) {
 6406:                 $r->print('<h3>'.&mt('Co-author Management').'</h3>'."\n".
 6407:                           &display_coauthor_managers($permission));
 6408:             } elsif ($env{'form.state'} eq 'process') {
 6409:                 $r->print('<h3>'.&mt('Co-author Management Update Result').'</h3>'."\n".
 6410:                           &update_coauthor_managers($permission));
 6411:             }
 6412:         }
 6413:     } elsif (($env{'form.action'} eq 'calist') && ($context eq 'author')) {
 6414:         if ($permission->{'cusr'}) {
 6415:             my ($role,$audom,$auname,$canview,$canedit) =
 6416:                 &Apache::lonviewcoauthors::get_allowable();
 6417:             if (($canedit) && ($env{'form.forceedit'})) {
 6418:                 &Apache::lonviewcoauthors::get_editor_crumbs($brcrum,'/adm/createuser');
 6419:                 my $args = { 'bread_crumbs' => $brcrum };
 6420:                 $r->print(&Apache::loncommon::start_page('Configure co-author listing',undef,
 6421:                                                          $args).
 6422:                           &Apache::lonviewcoauthors::edit_settings($audom,$auname,$role,
 6423:                                                                    '/adm/createuser'));
 6424:             } else {
 6425:                 push(@{$brcrum},
 6426:                        {href => '/adm/createuser?action=calist',
 6427:                         text => 'Coauthor-viewable list',
 6428:                         help => 'Author_List_Coauthors'});
 6429:                 my $args = { 'bread_crumbs' => $brcrum };
 6430:                 $r->print(&Apache::loncommon::start_page('Coauthor-viewable list',undef,
 6431:                                                          $args));
 6432:                 my %viewsettings =
 6433:                     &Apache::lonviewcoauthors::retrieve_view_settings($auname,$audom,$role);
 6434:                 if ($viewsettings{'show'} eq 'none') {
 6435:                     $r->print('<h3>'.&mt('Coauthor-viewable listing').'</h3>'.
 6436:                               '<p class="LC_info">'.
 6437:                               &mt('Listing of co-authors not enabled for this Authoring Space').
 6438:                               '</p>');
 6439:                 } else {
 6440:                     &Apache::lonviewcoauthors::print_coauthors($r,$auname,$audom,$role,
 6441:                                                                '/adm/createuser',\%viewsettings);
 6442:                 }
 6443:             }
 6444:         } else {
 6445:             $r->internal_redirect('/adm/viewcoauthors');
 6446:             return OK;
 6447:         }
 6448:     } else {
 6449:         $bread_crumbs_component = 'User Management';
 6450:         $args = { bread_crumbs           => $brcrum,
 6451:                   bread_crumbs_component => $bread_crumbs_component};
 6452:         $r->print(&header(undef,$args));
 6453:         $r->print(&print_main_menu($permission,$context,$crstype));
 6454:     }
 6455:     $r->print(&Apache::loncommon::end_page());
 6456:     return OK;
 6457: }
 6458: 
 6459: sub header {
 6460:     my ($jscript,$args) = @_;
 6461:     my $start_page;
 6462:     if (ref($args) eq 'HASH') {
 6463:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 6464:     } else {
 6465:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 6466:     }
 6467:     return $start_page;
 6468: }
 6469: 
 6470: sub add_script {
 6471:     my ($js) = @_;
 6472:     return '<script type="text/javascript">'."\n"
 6473:           .'// <![CDATA['."\n"
 6474:           .$js."\n"
 6475:           .'// ]]>'."\n"
 6476:           .'</script>'."\n";
 6477: }
 6478: 
 6479: sub usernamerequest_javascript {
 6480:     my $js = <<ENDJS;
 6481: 
 6482: function openusernamereqdisplay(dom,uname,queue) {
 6483:     var url = '/adm/createuser?action=displayuserreq';
 6484:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 6485:     var title = 'Account_Request_Browser';
 6486:     var options = 'scrollbars=1,resizable=1,menubar=0';
 6487:     options += ',width=700,height=600';
 6488:     var stdeditbrowser = open(url,title,options,'1');
 6489:     stdeditbrowser.focus();
 6490:     return;
 6491: }
 6492:  
 6493: ENDJS
 6494: }
 6495: 
 6496: sub close_popup_form {
 6497:     my $close= &mt('Close Window');
 6498:     return << "END";
 6499: <p><form name="displayreq" action="" method="post">
 6500: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 6501: </form></p>
 6502: END
 6503: }
 6504: 
 6505: sub verify_user_display {
 6506:     my ($context) = @_;
 6507:     my %lt = &Apache::lonlocal::texthash (
 6508:         course    => 'course(s): description, section(s), status',
 6509:         community => 'community(s): description, section(s), status',
 6510:         author    => 'author',
 6511:     );
 6512:     my $photos;
 6513:     if (($context eq 'course') && $env{'request.course.id'}) {
 6514:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 6515:     }
 6516:     my $output = <<"END";
 6517: 
 6518: function hide_searching() {
 6519:     if (document.getElementById('searching')) {
 6520:         document.getElementById('searching').style.display = 'none';
 6521:     }
 6522:     return;
 6523: }
 6524: 
 6525: function display_update() {
 6526:     document.studentform.action.value = 'listusers';
 6527:     document.studentform.phase.value = 'display';
 6528:     document.studentform.submit();
 6529: }
 6530: 
 6531: function updateCols(caller) {
 6532:     var context = '$context';
 6533:     var photos = '$photos';
 6534:     if (caller == 'Status') {
 6535:         if ((context == 'domain') && 
 6536:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6537:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 6538:             document.getElementById('showcolstatus').checked = false;
 6539:             document.getElementById('showcolstatus').disabled = 'disabled';
 6540:             document.getElementById('showcolstart').checked = false;
 6541:             document.getElementById('showcolend').checked = false;
 6542:         } else {
 6543:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6544:                 document.getElementById('showcolstatus').checked = true;
 6545:                 document.getElementById('showcolstatus').disabled = '';
 6546:                 document.getElementById('showcolstart').checked = true;
 6547:                 document.getElementById('showcolend').checked = true;
 6548:             } else {
 6549:                 document.getElementById('showcolstatus').checked = false;
 6550:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6551:                 document.getElementById('showcolstart').checked = false;
 6552:                 document.getElementById('showcolend').checked = false;
 6553:             }
 6554:             if (context == 'author') {
 6555:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Expired') {
 6556:                     document.getElementById('showcolmanager').checked = false;
 6557:                     document.getElementById('showcolmanager').disabled = 'disabled';
 6558:                 } else if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value != 'aa') {
 6559:                     document.getElementById('showcolmanager').checked = true;
 6560:                     document.getElementById('showcolmanager').disabled = '';
 6561:                 }
 6562:             }
 6563:         }
 6564:     }
 6565:     if (caller == 'output') {
 6566:         if (photos == 1) {
 6567:             if (document.getElementById('showcolphoto')) {
 6568:                 var photoitem = document.getElementById('showcolphoto');
 6569:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 6570:                     photoitem.checked = true;
 6571:                     photoitem.disabled = '';
 6572:                 } else {
 6573:                     photoitem.checked = false;
 6574:                     photoitem.disabled = 'disabled';
 6575:                 }
 6576:             }
 6577:         }
 6578:     }
 6579:     if (caller == 'showrole') {
 6580:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 6581:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 6582:             document.getElementById('showcolrole').checked = true;
 6583:             document.getElementById('showcolrole').disabled = '';
 6584:         } else {
 6585:             document.getElementById('showcolrole').checked = false;
 6586:             document.getElementById('showcolrole').disabled = 'disabled';
 6587:         }
 6588:         if (context == 'domain') {
 6589:             var quotausageshow = 0;
 6590:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6591:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 6592:                 document.getElementById('showcolstatus').checked = false;
 6593:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6594:                 document.getElementById('showcolstart').checked = false;
 6595:                 document.getElementById('showcolend').checked = false;
 6596:             } else {
 6597:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6598:                     document.getElementById('showcolstatus').checked = true;
 6599:                     document.getElementById('showcolstatus').disabled = '';
 6600:                     document.getElementById('showcolstart').checked = true;
 6601:                     document.getElementById('showcolend').checked = true;
 6602:                 }
 6603:             }
 6604:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 6605:                 document.getElementById('showcolextent').disabled = 'disabled';
 6606:                 document.getElementById('showcolextent').checked = 'false';
 6607:                 document.getElementById('showextent').style.display='none';
 6608:                 document.getElementById('showcoltextextent').innerHTML = '';
 6609:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 6610:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 6611:                     if (document.getElementById('showcolauthorusage')) {
 6612:                         document.getElementById('showcolauthorusage').disabled = '';
 6613:                     }
 6614:                     if (document.getElementById('showcolauthorquota')) {
 6615:                         document.getElementById('showcolauthorquota').disabled = '';
 6616:                     }
 6617:                     quotausageshow = 1;
 6618:                 }
 6619:             } else {
 6620:                 document.getElementById('showextent').style.display='block';
 6621:                 document.getElementById('showextent').style.textAlign='left';
 6622:                 document.getElementById('showextent').style.textFace='normal';
 6623:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 6624:                     document.getElementById('showcolextent').disabled = '';
 6625:                     document.getElementById('showcolextent').checked = 'true';
 6626:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 6627:                 } else {
 6628:                     document.getElementById('showcolextent').disabled = '';
 6629:                     document.getElementById('showcolextent').checked = 'true';
 6630:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 6631:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 6632:                     } else {
 6633:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 6634:                     }
 6635:                 }
 6636:             }
 6637:             if (quotausageshow == 0)  {
 6638:                 if (document.getElementById('showcolauthorusage')) {
 6639:                     document.getElementById('showcolauthorusage').checked = false;
 6640:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 6641:                 }
 6642:                 if (document.getElementById('showcolauthorquota')) {
 6643:                     document.getElementById('showcolauthorquota').checked = false;
 6644:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 6645:                 }
 6646:             }
 6647:         }
 6648:         if (context == 'author') {
 6649:             if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'aa') {
 6650:                 document.getElementById('showcolmanager').checked = false;
 6651:                 document.getElementById('showcolmanager').disabled = 'disabled';
 6652:             } else if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value != 'Expired') {
 6653:                 document.getElementById('showcolmanager').checked = true;
 6654:                 document.getElementById('showcolmanager').disabled = '';
 6655:             }
 6656:         }
 6657:     }
 6658:     return;
 6659: }
 6660: 
 6661: END
 6662:     return $output;
 6663: 
 6664: }
 6665: 
 6666: ###############################################################
 6667: ###############################################################
 6668: #  Menu Phase One
 6669: sub print_main_menu {
 6670:     my ($permission,$context,$crstype) = @_;
 6671:     my $linkcontext = $context;
 6672:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 6673:     if (($context eq 'course') && ($crstype eq 'Community')) {
 6674:         $linkcontext = lc($crstype);
 6675:         $stuterm = 'Members';
 6676:     }
 6677:     my %links = (
 6678:                 domain => {
 6679:                             upload     => 'Upload a File of Users',
 6680:                             singleuser => 'Add/Modify a User',
 6681:                             listusers  => 'Manage Users',
 6682:                             },
 6683:                 author => {
 6684:                             upload     => 'Upload a File of Co-authors',
 6685:                             singleuser => 'Add/Modify a Co-author',
 6686:                             listusers  => 'Manage Co-authors',
 6687:                             },
 6688:                 course => {
 6689:                             upload     => 'Upload a File of Course Users',
 6690:                             singleuser => 'Add/Modify a Course User',
 6691:                             listusers  => 'List and Modify Multiple Course Users',
 6692:                             },
 6693:                 community => {
 6694:                             upload     => 'Upload a File of Community Users',
 6695:                             singleuser => 'Add/Modify a Community User',
 6696:                             listusers  => 'List and Modify Multiple Community Users',
 6697:                            },
 6698:                 );
 6699:      my %linktitles = (
 6700:                 domain => {
 6701:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 6702:                             listusers  => 'Show and manage users in this domain.',
 6703:                             },
 6704:                 author => {
 6705:                             singleuser => 'Add a user with a co- or assistant author role.',
 6706:                             listusers  => 'Show and manage co- or assistant authors.',
 6707:                             },
 6708:                 course => {
 6709:                             singleuser => 'Add a user with a certain role to this course.',
 6710:                             listusers  => 'Show and manage users in this course.',
 6711:                             },
 6712:                 community => {
 6713:                             singleuser => 'Add a user with a certain role to this community.',
 6714:                             listusers  => 'Show and manage users in this community.',
 6715:                            },
 6716:                 );
 6717: 
 6718:   if ($linkcontext eq 'domain') {
 6719:       unless ($permission->{'cusr'}) {
 6720:           $links{'domain'}{'singleuser'} = 'View a User';
 6721:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 6722:       }
 6723:   } elsif ($linkcontext eq 'course') {
 6724:       unless ($permission->{'cusr'}) {
 6725:           $links{'course'}{'singleuser'} = 'View a Course User';
 6726:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 6727:           $links{'course'}{'listusers'} = 'List Course Users';
 6728:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 6729:       }
 6730:   } elsif ($linkcontext eq 'community') {
 6731:       unless ($permission->{'cusr'}) {
 6732:           $links{'community'}{'singleuser'} = 'View a Community User';
 6733:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 6734:           $links{'community'}{'listusers'} = 'List Community Users';
 6735:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 6736:       }
 6737:   }
 6738:   my @menu = ( {categorytitle => 'Single Users', 
 6739:          items =>
 6740:          [
 6741:             {
 6742:              linktext => $links{$linkcontext}{'singleuser'},
 6743:              icon => 'edit-redo.png',
 6744:              #help => 'Course_Change_Privileges',
 6745:              url => '/adm/createuser?action=singleuser',
 6746:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6747:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 6748:             },
 6749:          ]},
 6750: 
 6751:          {categorytitle => 'Multiple Users',
 6752:          items => 
 6753:          [
 6754:             {
 6755:              linktext => $links{$linkcontext}{'upload'},
 6756:              icon => 'uplusr.png',
 6757:              #help => 'Course_Create_Class_List',
 6758:              url => '/adm/createuser?action=upload',
 6759:              permission => $permission->{'cusr'},
 6760:              linktitle => 'Upload a CSV or a text file containing users.',
 6761:             },
 6762:             {
 6763:              linktext => $links{$linkcontext}{'listusers'},
 6764:              icon => 'mngcu.png',
 6765:              #help => 'Course_View_Class_List',
 6766:              url => '/adm/createuser?action=listusers',
 6767:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6768:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 6769:             },
 6770: 
 6771:          ]},
 6772: 
 6773:          {categorytitle => 'Administration',
 6774:          items => [ ]},
 6775:        );
 6776: 
 6777:     if ($context eq 'domain'){
 6778:         push(@{  $menu[0]->{items} }, # Single Users
 6779:             {
 6780:              linktext => 'User Access Log',
 6781:              icon => 'document-properties.png',
 6782:              #help => 'Domain_User_Access_Logs',
 6783:              url => '/adm/createuser?action=accesslogs',
 6784:              permission => $permission->{'activity'},
 6785:              linktitle => 'View user access log.',
 6786:             }
 6787:         );
 6788:         
 6789:         push(@{ $menu[2]->{items} }, #Category: Administration
 6790:             {
 6791:              linktext => 'Custom Roles',
 6792:              icon => 'emblem-photos.png',
 6793:              #help => 'Course_Editing_Custom_Roles',
 6794:              url => '/adm/createuser?action=custom',
 6795:              permission => $permission->{'custom'},
 6796:              linktitle => 'Configure a custom role.',
 6797:             },
 6798:             {
 6799:              linktext => 'Authoring Space Requests',
 6800:              icon => 'selfenrl-queue.png',
 6801:              #help => 'Domain_Role_Approvals',
 6802:              url => '/adm/createuser?action=processauthorreq',
 6803:              permission => $permission->{'cusr'},
 6804:              linktitle => 'Approve or reject author role requests',
 6805:             },
 6806:             {
 6807:              linktext => 'LON-CAPA Account Requests',
 6808:              icon => 'list-add.png',
 6809:              #help => 'Domain_Username_Approvals',
 6810:              url => '/adm/createuser?action=processusernamereq',
 6811:              permission => $permission->{'cusr'},
 6812:              linktitle => 'Approve or reject LON-CAPA account requests',
 6813:             },
 6814:             {
 6815:              linktext => 'Change Log',
 6816:              icon => 'document-properties.png',
 6817:              #help => 'Course_User_Logs',
 6818:              url => '/adm/createuser?action=changelogs',
 6819:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 6820:              linktitle => 'View change log.',
 6821:             },
 6822:         );
 6823:         
 6824:     }elsif ($context eq 'course'){
 6825:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 6826: 
 6827:         my %linktext = (
 6828:                          'Course'    => {
 6829:                                           single => 'Add/Modify a Student', 
 6830:                                           drop   => 'Drop Students',
 6831:                                           groups => 'Course Groups',
 6832:                                         },
 6833:                          'Community' => {
 6834:                                           single => 'Add/Modify a Member', 
 6835:                                           drop   => 'Drop Members',
 6836:                                           groups => 'Community Groups',
 6837:                                         },
 6838:                        );
 6839:         $linktext{'Placement'} = $linktext{'Course'};
 6840: 
 6841:         my %linktitle = (
 6842:             'Course' => {
 6843:                   single => 'Add a user with the role of student to this course',
 6844:                   drop   => 'Remove a student from this course.',
 6845:                   groups => 'Manage course groups',
 6846:                         },
 6847:             'Community' => {
 6848:                   single => 'Add a user with the role of member to this community',
 6849:                   drop   => 'Remove a member from this community.',
 6850:                   groups => 'Manage community groups',
 6851:                            },
 6852:         );
 6853: 
 6854:         $linktitle{'Placement'} = $linktitle{'Course'};
 6855: 
 6856:         push(@{ $menu[0]->{items} }, #Category: Single Users
 6857:             {   
 6858:              linktext => $linktext{$crstype}{'single'},
 6859:              #help => 'Course_Add_Student',
 6860:              icon => 'list-add.png',
 6861:              url => '/adm/createuser?action=singlestudent',
 6862:              permission => $permission->{'cusr'},
 6863:              linktitle => $linktitle{$crstype}{'single'},
 6864:             },
 6865:         );
 6866:         
 6867:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 6868:             {
 6869:              linktext => $linktext{$crstype}{'drop'},
 6870:              icon => 'edit-undo.png',
 6871:              #help => 'Course_Drop_Student',
 6872:              url => '/adm/createuser?action=drop',
 6873:              permission => $permission->{'cusr'},
 6874:              linktitle => $linktitle{$crstype}{'drop'},
 6875:             },
 6876:         );
 6877:         push(@{ $menu[2]->{items} }, #Category: Administration
 6878:             {
 6879:              linktext => 'Helpdesk Access',
 6880:              icon => 'helpdesk-access.png',
 6881:              #help => 'Course_Helpdesk_Access',
 6882:              url => '/adm/createuser?action=helpdesk',
 6883:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6884:                             ($permission->{'view'} || $permission->{'cusr'})),
 6885:              linktitle => 'Helpdesk access options',
 6886:             },
 6887:             {
 6888:              linktext => 'Custom Roles',
 6889:              icon => 'emblem-photos.png',
 6890:              #help => 'Course_Editing_Custom_Roles',
 6891:              url => '/adm/createuser?action=custom',
 6892:              permission => $permission->{'custom'},
 6893:              linktitle => 'Configure a custom role.',
 6894:             },
 6895:             {
 6896:              linktext => $linktext{$crstype}{'groups'},
 6897:              icon => 'grps.png',
 6898:              #help => 'Course_Manage_Group',
 6899:              url => '/adm/coursegroups?refpage=cusr',
 6900:              permission => $permission->{'grp_manage'},
 6901:              linktitle => $linktitle{$crstype}{'groups'},
 6902:             },
 6903:             {
 6904:              linktext => 'Change Log',
 6905:              icon => 'document-properties.png',
 6906:              #help => 'Course_User_Logs',
 6907:              url => '/adm/createuser?action=changelogs',
 6908:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6909:              linktitle => 'View change log.',
 6910:             },
 6911:         );
 6912:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 6913:             push(@{ $menu[2]->{items} },
 6914:                     {
 6915:                      linktext => 'Enrollment Requests',
 6916:                      icon => 'selfenrl-queue.png',
 6917:                      #help => 'Course_Approve_Selfenroll',
 6918:                      url => '/adm/createuser?action=selfenrollqueue',
 6919:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6920:                      linktitle =>'Approve or reject enrollment requests.',
 6921:                     },
 6922:             );
 6923:         }
 6924:         
 6925:         if (!exists($permission->{'cusr_section'})){
 6926:             if ($crstype ne 'Community') {
 6927:                 push(@{ $menu[2]->{items} },
 6928:                     {
 6929:                      linktext => 'Automated Enrollment',
 6930:                      icon => 'roles.png',
 6931:                      #help => 'Course_Automated_Enrollment',
 6932:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 6933:                                          && (($permission->{'cusr'}) ||
 6934:                                              ($permission->{'view'}))),
 6935:                      url  => '/adm/populate',
 6936:                      linktitle => 'Automated enrollment manager.',
 6937:                     }
 6938:                 );
 6939:             }
 6940:             push(@{ $menu[2]->{items} }, 
 6941:                 {
 6942:                  linktext => 'User Self-Enrollment',
 6943:                  icon => 'self_enroll.png',
 6944:                  #help => 'Course_Self_Enrollment',
 6945:                  url => '/adm/createuser?action=selfenroll',
 6946:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6947:                  linktitle => 'Configure user self-enrollment.',
 6948:                 },
 6949:             );
 6950:         }
 6951:     } elsif ($context eq 'author') {
 6952:         push(@{ $menu[2]->{items} }, #Category: Administration
 6953:             {
 6954:              linktext => 'Change Log',
 6955:              icon => 'document-properties.png',
 6956:              #help => 'Course_User_Logs',
 6957:              url => '/adm/createuser?action=changelogs',
 6958:              permission => $permission->{'cusr'},
 6959:              linktitle => 'View change log.',
 6960:             },
 6961:             {
 6962:              linktext => 'Co-author Managers',
 6963:              icon => 'camanager.png',
 6964:              #help => 'Coauthor_Management',
 6965:              url => '/adm/createuser?action=camanagers',
 6966:              permission => $permission->{'author'},
 6967:              linktitle => 'Assign/Revoke right to manage co-author roles',
 6968:             },
 6969:             {
 6970:              linktext => 'Configure Co-author Listing',
 6971:              icon => 'coauthors.png',
 6972:              #help => 'Coauthor_Settings',
 6973:              url => '/adm/createuser?action=calist&forceedit=1',
 6974:              permission => ($permission->{'cusr'}),
 6975:              linktitle => 'Set availability of coauthor-viewable user listing',
 6976:             },
 6977:         );
 6978:     }
 6979:     push(@{ $menu[2]->{items} },
 6980:         {
 6981:          linktext => 'Role Requests (other domains)',
 6982:          icon => 'edit-find.png',
 6983:          #help => 'Role_Requests',
 6984:          url => '/adm/createuser?action=rolerequests',
 6985:          permission => $permission->{'cusr'},
 6986:          linktitle => 'Role requests for users in other domains',
 6987:         },
 6988:     );
 6989:     if (&show_role_requests($context,$env{'request.role.domain'})) {
 6990:         push(@{ $menu[2]->{items} },
 6991:             {
 6992:              linktext => 'Queued Role Assignments (this domain)',
 6993:              icon => 'edit-find.png',
 6994:              #help => 'Role_Approvals',
 6995:              url => '/adm/createuser?action=queuedroles',
 6996:              permission => $permission->{'cusr'},
 6997:              linktitle => "Role requests for this domain's users",
 6998:             },
 6999:         );
 7000:     }
 7001:     return Apache::lonhtmlcommon::generate_menu(@menu);
 7002: #               { text => 'View Log-in History',
 7003: #                 help => 'Course_User_Logins',
 7004: #                 action => 'logins',
 7005: #                 permission => $permission->{'cusr'},
 7006: #               });
 7007: }
 7008: 
 7009: sub restore_prev_selections {
 7010:     my %saveable_parameters = ('srchby'   => 'scalar',
 7011: 			       'srchin'   => 'scalar',
 7012: 			       'srchtype' => 'scalar',
 7013: 			       );
 7014:     &Apache::loncommon::store_settings('user','user_picker',
 7015: 				       \%saveable_parameters);
 7016:     &Apache::loncommon::restore_settings('user','user_picker',
 7017: 					 \%saveable_parameters);
 7018: }
 7019: 
 7020: sub print_selfenroll_menu {
 7021:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 7022:     my $crstype = &Apache::loncommon::course_type();
 7023:     my $formname = 'selfenroll';
 7024:     my $nolink = 1;
 7025:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7026:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 7027:     my $setsec_js = 
 7028:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 7029:     my %alerts = &Apache::lonlocal::texthash(
 7030:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 7031:         butn => 'but no user types have been checked.',
 7032:         wilf => "Please uncheck 'activate' or check at least one type.",
 7033:     );
 7034:     my $disabled;
 7035:     if ($readonly) {
 7036:        $disabled = ' disabled="disabled"';
 7037:     }
 7038:     &js_escape(\%alerts);
 7039:     my $selfenroll_js = <<"ENDSCRIPT";
 7040: function update_types(caller,num) {
 7041:     var delidx = getIndexByName('selfenroll_delete');
 7042:     var actidx = getIndexByName('selfenroll_activate');
 7043:     if (caller == 'selfenroll_all') {
 7044:         var selall;
 7045:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7046:             if (document.$formname.selfenroll_all[i].checked) {
 7047:                 selall = document.$formname.selfenroll_all[i].value;
 7048:             }
 7049:         }
 7050:         if (selall == 1) {
 7051:             if (delidx != -1) {
 7052:                 if (document.$formname.selfenroll_delete.length) {
 7053:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7054:                         document.$formname.selfenroll_delete[j].checked = true;
 7055:                     }
 7056:                 } else {
 7057:                     document.$formname.elements[delidx].checked = true;
 7058:                 }
 7059:             }
 7060:             if (actidx != -1) {
 7061:                 if (document.$formname.selfenroll_activate.length) {
 7062:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7063:                         document.$formname.selfenroll_activate[j].checked = false;
 7064:                     }
 7065:                 } else {
 7066:                     document.$formname.elements[actidx].checked = false;
 7067:                 }
 7068:             }
 7069:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 7070:         }
 7071:     }
 7072:     if (caller == 'selfenroll_activate') {
 7073:         if (document.$formname.selfenroll_activate.length) {
 7074:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7075:                 if (document.$formname.selfenroll_activate[j].value == num) {
 7076:                     if (document.$formname.selfenroll_activate[j].checked) {
 7077:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7078:                             if (document.$formname.selfenroll_all[i].value == '1') {
 7079:                                 document.$formname.selfenroll_all[i].checked = false;
 7080:                             }
 7081:                             if (document.$formname.selfenroll_all[i].value == '0') {
 7082:                                 document.$formname.selfenroll_all[i].checked = true;
 7083:                             }
 7084:                         }
 7085:                     }
 7086:                 }
 7087:             }
 7088:         } else {
 7089:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7090:                 if (document.$formname.selfenroll_all[i].value == '1') {
 7091:                     document.$formname.selfenroll_all[i].checked = false;
 7092:                 }
 7093:                 if (document.$formname.selfenroll_all[i].value == '0') {
 7094:                     document.$formname.selfenroll_all[i].checked = true;
 7095:                 }
 7096:             }
 7097:         }
 7098:     }
 7099:     if (caller == 'selfenroll_delete') {
 7100:         if (document.$formname.selfenroll_delete.length) {
 7101:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7102:                 if (document.$formname.selfenroll_delete[j].value == num) {
 7103:                     if (document.$formname.selfenroll_delete[j].checked) {
 7104:                         var delindex = getIndexByName('selfenroll_types_'+num);
 7105:                         if (delindex != -1) { 
 7106:                             if (document.$formname.elements[delindex].length) {
 7107:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7108:                                     document.$formname.elements[delindex][k].checked = false;
 7109:                                 }
 7110:                             } else {
 7111:                                 document.$formname.elements[delindex].checked = false;
 7112:                             }
 7113:                         }
 7114:                     }
 7115:                 }
 7116:             }
 7117:         } else {
 7118:             if (document.$formname.selfenroll_delete.checked) {
 7119:                 var delindex = getIndexByName('selfenroll_types_'+num);
 7120:                 if (delindex != -1) {
 7121:                     if (document.$formname.elements[delindex].length) {
 7122:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7123:                             document.$formname.elements[delindex][k].checked = false;
 7124:                         }
 7125:                     } else {
 7126:                         document.$formname.elements[delindex].checked = false;
 7127:                     }
 7128:                 }
 7129:             }
 7130:         }
 7131:     }
 7132:     return;
 7133: }
 7134: 
 7135: function validate_types(form) {
 7136:     var needaction = new Array();
 7137:     var countfail = 0;
 7138:     var actidx = getIndexByName('selfenroll_activate');
 7139:     if (actidx != -1) {
 7140:         if (document.$formname.selfenroll_activate.length) {
 7141:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7142:                 var num = document.$formname.selfenroll_activate[j].value;
 7143:                 if (document.$formname.selfenroll_activate[j].checked) {
 7144:                     countfail = check_types(num,countfail,needaction)
 7145:                 }
 7146:             }
 7147:         } else {
 7148:             if (document.$formname.selfenroll_activate.checked) {
 7149:                 var num = document.$formname.selfenroll_activate.value;
 7150:                 countfail = check_types(num,countfail,needaction)
 7151:             }
 7152:         }
 7153:     }
 7154:     if (countfail > 0) {
 7155:         var msg = "$alerts{'acto'}\\n";
 7156:         var loopend = needaction.length -1;
 7157:         if (loopend > 0) {
 7158:             for (var m=0; m<loopend; m++) {
 7159:                 msg += needaction[m]+", ";
 7160:             }
 7161:         }
 7162:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 7163:         alert(msg);
 7164:         return; 
 7165:     }
 7166:     setSections(form);
 7167: }
 7168: 
 7169: function check_types(num,countfail,needaction) {
 7170:     var boxname = 'selfenroll_types_'+num;
 7171:     var typeidx = getIndexByName(boxname);
 7172:     var count = 0;
 7173:     if (typeidx != -1) {
 7174:         if (document.$formname.elements[boxname].length) {
 7175:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 7176:                 if (document.$formname.elements[boxname][k].checked) {
 7177:                     count ++;
 7178:                 }
 7179:             }
 7180:         } else {
 7181:             if (document.$formname.elements[typeidx].checked) {
 7182:                 count ++;
 7183:             }
 7184:         }
 7185:         if (count == 0) {
 7186:             var domidx = getIndexByName('selfenroll_dom_'+num);
 7187:             if (domidx != -1) {
 7188:                 var domname = document.$formname.elements[domidx].value;
 7189:                 needaction[countfail] = domname;
 7190:                 countfail ++;
 7191:             }
 7192:         }
 7193:     }
 7194:     return countfail;
 7195: }
 7196: 
 7197: function toggleNotify() {
 7198:     var selfenrollApproval = 0;
 7199:     if (document.$formname.selfenroll_approval.length) {
 7200:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 7201:             if (document.$formname.selfenroll_approval[i].checked) {
 7202:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 7203:                 break;        
 7204:             }
 7205:         }
 7206:     }
 7207:     if (document.getElementById('notified')) {
 7208:         if (selfenrollApproval == 0) {
 7209:             document.getElementById('notified').style.display='none';
 7210:         } else {
 7211:             document.getElementById('notified').style.display='block';
 7212:         }
 7213:     }
 7214:     return;
 7215: }
 7216: 
 7217: function getIndexByName(item) {
 7218:     for (var i=0;i<document.$formname.elements.length;i++) {
 7219:         if (document.$formname.elements[i].name == item) {
 7220:             return i;
 7221:         }
 7222:     }
 7223:     return -1;
 7224: }
 7225: ENDSCRIPT
 7226: 
 7227:     my $output = '<script type="text/javascript">'."\n".
 7228:                  '// <![CDATA['."\n".
 7229:                  $setsec_js."\n".$selfenroll_js."\n".
 7230:                  '// ]]>'."\n".
 7231:                  '</script>'."\n".
 7232:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 7233:     my $visactions = &cat_visibility($cdom);
 7234:     my ($cathash,%cattype);
 7235:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7236:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7237:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7238:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7239:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7240:         if ($cattype{'auth'} eq '') {
 7241:             $cattype{'auth'} = 'std';
 7242:         }
 7243:         if ($cattype{'unauth'} eq '') {
 7244:             $cattype{'unauth'} = 'std';
 7245:         }
 7246:     } else {
 7247:         $cathash = {};
 7248:         $cattype{'auth'} = 'std';
 7249:         $cattype{'unauth'} = 'std';
 7250:     }
 7251:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7252:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7253:                   '<br />'.
 7254:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7255:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7256:                   '</ul>');
 7257:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7258:         if ($currsettings->{'uniquecode'}) {
 7259:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7260:         } else {
 7261:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7262:                   '<br />'.
 7263:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7264:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7265:                   '</ul><br />');
 7266:         }
 7267:     } else {
 7268:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7269:         if (ref($visactions) eq 'HASH') {
 7270:             if ($visible) {
 7271:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 7272:            } else {
 7273:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 7274:                           .$visactions->{'yous'}.
 7275:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 7276:                 if (ref($vismsgs) eq 'ARRAY') {
 7277:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 7278:                     foreach my $item (@{$vismsgs}) {
 7279:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 7280:                     }
 7281:                     $output .= '</ul>';
 7282:                 }
 7283:                 $output .= '</p>';
 7284:             }
 7285:         }
 7286:     }
 7287:     my $actionhref = '/adm/createuser';
 7288:     if ($context eq 'domain') {
 7289:         $actionhref = '/adm/modifycourse';
 7290:     }
 7291: 
 7292:     my %noedit;
 7293:     unless ($context eq 'domain') {
 7294:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7295:     }
 7296:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 7297:                &Apache::lonhtmlcommon::start_pick_box();
 7298:     if (ref($row) eq 'ARRAY') {
 7299:         foreach my $item (@{$row}) {
 7300:             my $title = $item; 
 7301:             if (ref($lt) eq 'HASH') {
 7302:                 $title = $lt->{$item};
 7303:             }
 7304:             $output .= &Apache::lonhtmlcommon::row_title($title);
 7305:             if ($item eq 'types') {
 7306:                 my $curr_types;
 7307:                 if (ref($currsettings) eq 'HASH') {
 7308:                     $curr_types = $currsettings->{'selfenroll_types'};
 7309:                 }
 7310:                 if ($noedit{$item}) {
 7311:                     if ($curr_types eq '*') {
 7312:                         $output .= &mt('Any user in any domain');   
 7313:                     } else {
 7314:                         my @entries = split(/;/,$curr_types);
 7315:                         if (@entries > 0) {
 7316:                             $output .= '<ul>'; 
 7317:                             foreach my $entry (@entries) {
 7318:                                 my ($currdom,$typestr) = split(/:/,$entry);
 7319:                                 next if ($typestr eq '');
 7320:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 7321:                                 my @currinsttypes = split(',',$typestr);
 7322:                                 my ($othertitle,$usertypes,$types) = 
 7323:                                     &Apache::loncommon::sorted_inst_types($currdom);
 7324:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7325:                                     $usertypes->{'any'} = &mt('any user'); 
 7326:                                     if (keys(%{$usertypes}) > 0) {
 7327:                                         $usertypes->{'other'} = &mt('other users');
 7328:                                     }
 7329:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 7330:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 7331:                                  }
 7332:                             }
 7333:                             $output .= '</ul>';
 7334:                         } else {
 7335:                             $output .= &mt('None');
 7336:                         }
 7337:                     }
 7338:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7339:                     next;
 7340:                 }
 7341:                 my $showdomdesc = 1;
 7342:                 my $includeempty = 1;
 7343:                 my $num = 0;
 7344:                 $output .= &Apache::loncommon::start_data_table().
 7345:                            &Apache::loncommon::start_data_table_row()
 7346:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 7347:                            .&mt('Any user in any domain:')
 7348:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 7349:                 if ($curr_types eq '*') {
 7350:                     $output .= ' checked="checked" '; 
 7351:                 }
 7352:                 $output .= 'onchange="javascript:update_types('.
 7353:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 7354:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 7355:                 if ($curr_types ne '*') {
 7356:                     $output .= ' checked="checked" ';
 7357:                 }
 7358:                 $output .= ' onchange="javascript:update_types('.
 7359:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 7360:                            &Apache::loncommon::end_data_table_row().
 7361:                            &Apache::loncommon::end_data_table().
 7362:                            &mt('Or').'<br />'.
 7363:                            &Apache::loncommon::start_data_table();
 7364:                 my %currdoms;
 7365:                 if ($curr_types eq '') {
 7366:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 7367:                 } elsif ($curr_types ne '*') {
 7368:                     my @entries = split(/;/,$curr_types);
 7369:                     if (@entries > 0) {
 7370:                         foreach my $entry (@entries) {
 7371:                             my ($currdom,$typestr) = split(/:/,$entry);
 7372:                             $currdoms{$currdom} = 1;
 7373:                             my $domdesc = &Apache::lonnet::domain($currdom);
 7374:                             my @currinsttypes = split(',',$typestr);
 7375:                             $output .= &Apache::loncommon::start_data_table_row()
 7376:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 7377:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 7378:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 7379:                                        .'" value="'.$currdom.'" /></span><br />'
 7380:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 7381:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 7382:                                        .&mt('Delete').'</label></span></td>';
 7383:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 7384:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 7385:                                        .&Apache::loncommon::end_data_table_row();
 7386:                             $num ++;
 7387:                         }
 7388:                     }
 7389:                 }
 7390:                 my $add_domtitle = &mt('Users in additional domain:');
 7391:                 if ($curr_types eq '*') { 
 7392:                     $add_domtitle = &mt('Users in specific domain:');
 7393:                 } elsif ($curr_types eq '') {
 7394:                     $add_domtitle = &mt('Users in other domain:');
 7395:                 }
 7396:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 7397:                 $output .= &Apache::loncommon::start_data_table_row()
 7398:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 7399:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 7400:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 7401:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 7402:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 7403:                            .&Apache::loncommon::end_data_table();
 7404:             } elsif ($item eq 'registered') {
 7405:                 my ($regon,$regoff);
 7406:                 my $registered;
 7407:                 if (ref($currsettings) eq 'HASH') {
 7408:                     $registered = $currsettings->{'selfenroll_registered'};
 7409:                 }
 7410:                 if ($noedit{$item}) {
 7411:                     if ($registered) {
 7412:                         $output .= &mt('Must be registered in course');
 7413:                     } else {
 7414:                         $output .= &mt('No requirement');
 7415:                     }
 7416:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7417:                     next;
 7418:                 }
 7419:                 if ($registered) {
 7420:                     $regon = ' checked="checked" ';
 7421:                     $regoff = '';
 7422:                 } else {
 7423:                     $regon = '';
 7424:                     $regoff = ' checked="checked" ';
 7425:                 }
 7426:                 $output .= '<label>'.
 7427:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 7428:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 7429:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 7430:                            &mt('No').'</label>';
 7431:             } elsif ($item eq 'enroll_dates') {
 7432:                 my ($starttime,$endtime);
 7433:                 if (ref($currsettings) eq 'HASH') {
 7434:                     $starttime = $currsettings->{'selfenroll_start_date'};
 7435:                     $endtime = $currsettings->{'selfenroll_end_date'};
 7436:                     if ($starttime eq '') {
 7437:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7438:                     }
 7439:                     if ($endtime eq '') {
 7440:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7441:                     }
 7442:                 }
 7443:                 if ($noedit{$item}) {
 7444:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7445:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7446:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7447:                     next;
 7448:                 }
 7449:                 my $startform =
 7450:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 7451:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7452:                 my $endform =
 7453:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 7454:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7455:                 $output .= &selfenroll_date_forms($startform,$endform);
 7456:             } elsif ($item eq 'access_dates') {
 7457:                 my ($starttime,$endtime);
 7458:                 if (ref($currsettings) eq 'HASH') {
 7459:                     $starttime = $currsettings->{'selfenroll_start_access'};
 7460:                     $endtime = $currsettings->{'selfenroll_end_access'};
 7461:                     if ($starttime eq '') {
 7462:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7463:                     }
 7464:                     if ($endtime eq '') {
 7465:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7466:                     }
 7467:                 }
 7468:                 if ($noedit{$item}) {
 7469:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7470:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7471:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7472:                     next;
 7473:                 }
 7474:                 my $startform =
 7475:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 7476:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7477:                 my $endform =
 7478:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 7479:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7480:                 $output .= &selfenroll_date_forms($startform,$endform);
 7481:             } elsif ($item eq 'section') {
 7482:                 my $currsec;
 7483:                 if (ref($currsettings) eq 'HASH') {
 7484:                     $currsec = $currsettings->{'selfenroll_section'};
 7485:                 }
 7486:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 7487:                 my $newsecval;
 7488:                 if ($currsec ne 'none' && $currsec ne '') {
 7489:                     if (!defined($sections_count{$currsec})) {
 7490:                         $newsecval = $currsec;
 7491:                     }
 7492:                 }
 7493:                 if ($noedit{$item}) {
 7494:                     if ($currsec ne '') {
 7495:                         $output .= $currsec;
 7496:                     } else {
 7497:                         $output .= &mt('No specific section');
 7498:                     }
 7499:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7500:                     next;
 7501:                 }
 7502:                 my $sections_select = 
 7503:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 7504:                 $output .= '<table class="LC_createuser">'."\n".
 7505:                            '<tr class="LC_section_row">'."\n".
 7506:                            '<td align="center">'.&mt('Existing sections')."\n".
 7507:                            '<br />'.$sections_select.'</td><td align="center">'.
 7508:                            &mt('New section').'<br />'."\n".
 7509:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 7510:                            '<input type="hidden" name="sections" value="" />'."\n".
 7511:                            '</td></tr></table>'."\n";
 7512:             } elsif ($item eq 'approval') {
 7513:                 my ($currnotified,$currapproval,%appchecked);
 7514:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7515:                 if (ref($currsettings) eq 'HASH') {
 7516:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 7517:                     $currapproval = $currsettings->{'selfenroll_approval'};
 7518:                 }
 7519:                 if ($currapproval !~ /^[012]$/) {
 7520:                     $currapproval = 0;
 7521:                 }
 7522:                 if ($noedit{$item}) {
 7523:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 7524:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 7525:                     next;
 7526:                 }
 7527:                 $appchecked{$currapproval} = ' checked="checked"';
 7528:                 for my $i (0..2) {
 7529:                     $output .= '<label>'.
 7530:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 7531:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 7532:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 7533:                 }
 7534:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 7535:                 my (@ccs,%notified);
 7536:                 my $ccrole = 'cc';
 7537:                 if ($crstype eq 'Community') {
 7538:                     $ccrole = 'co';
 7539:                 }
 7540:                 if ($advhash{$ccrole}) {
 7541:                     @ccs = split(/,/,$advhash{$ccrole});
 7542:                 }
 7543:                 if ($currnotified) {
 7544:                     foreach my $current (split(/,/,$currnotified)) {
 7545:                         $notified{$current} = 1;
 7546:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 7547:                             push(@ccs,$current);
 7548:                         }
 7549:                     }
 7550:                 }
 7551:                 if (@ccs) {
 7552:                     my $style;
 7553:                     unless ($currapproval) {
 7554:                         $style = ' style="display: none;"'; 
 7555:                     }
 7556:                     $output .= '<br /><div id="notified"'.$style.'>'.
 7557:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 7558:                                &Apache::loncommon::start_data_table().
 7559:                                &Apache::loncommon::start_data_table_row();
 7560:                     my $count = 0;
 7561:                     my $numcols = 4;
 7562:                     foreach my $cc (sort(@ccs)) {
 7563:                         my $notifyon;
 7564:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 7565:                         if ($notified{$cc}) {
 7566:                             $notifyon = ' checked="checked" ';
 7567:                         }
 7568:                         if ($count && !$count%$numcols) {
 7569:                             $output .= &Apache::loncommon::end_data_table_row().
 7570:                                        &Apache::loncommon::start_data_table_row()
 7571:                         }
 7572:                         $output .= '<td><span class="LC_nobreak"><label>'.
 7573:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 7574:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 7575:                                    '</label></span></td>';
 7576:                         $count ++;
 7577:                     }
 7578:                     my $rem = $count%$numcols;
 7579:                     if ($rem) {
 7580:                         my $emptycols = $numcols - $rem;
 7581:                         for (my $i=0; $i<$emptycols; $i++) { 
 7582:                             $output .= '<td>&nbsp;</td>';
 7583:                         }
 7584:                     }
 7585:                     $output .= &Apache::loncommon::end_data_table_row().
 7586:                                &Apache::loncommon::end_data_table().
 7587:                                '</div>';
 7588:                 }
 7589:             } elsif ($item eq 'limit') {
 7590:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 7591:                 if (ref($currsettings) eq 'HASH') {
 7592:                     $currlim = $currsettings->{'selfenroll_limit'};
 7593:                     $currcap = $currsettings->{'selfenroll_cap'};
 7594:                 }
 7595:                 if ($noedit{$item}) {
 7596:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 7597:                         if ($currlim eq 'allstudents') {
 7598:                             $output .= &mt('Limit by total students');
 7599:                         } elsif ($currlim eq 'selfenrolled') {
 7600:                             $output .= &mt('Limit by total self-enrolled students');
 7601:                         }
 7602:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 7603:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 7604:                     } else {
 7605:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 7606:                     }
 7607:                     next;
 7608:                 }
 7609:                 if ($currlim eq 'allstudents') {
 7610:                     $crslimit = ' checked="checked" ';
 7611:                     $selflimit = ' ';
 7612:                     $nolimit = ' ';
 7613:                 } elsif ($currlim eq 'selfenrolled') {
 7614:                     $crslimit = ' ';
 7615:                     $selflimit = ' checked="checked" ';
 7616:                     $nolimit = ' '; 
 7617:                 } else {
 7618:                     $crslimit = ' ';
 7619:                     $selflimit = ' ';
 7620:                     $nolimit = ' checked="checked" ';
 7621:                 }
 7622:                 $output .= '<table><tr><td><label>'.
 7623:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 7624:                            &mt('No limit').'</label></td><td><label>'.
 7625:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 7626:                            &mt('Limit by total students').'</label></td><td><label>'.
 7627:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 7628:                            &mt('Limit by total self-enrolled students').
 7629:                            '</td></tr><tr>'.
 7630:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 7631:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 7632:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 7633:             }
 7634:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 7635:         }
 7636:     }
 7637:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 7638:     unless ($readonly) {
 7639:         $output .= '<input type="button" name="selfenrollconf" value="'
 7640:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 7641:     }
 7642:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 7643:               .'<input type="hidden" name="state" value="done" />'."\n"
 7644:               .$additional.'</form>';
 7645:     $r->print($output);
 7646:     return;
 7647: }
 7648: 
 7649: sub get_noedit_fields {
 7650:     my ($cdom,$cnum,$crstype,$row) = @_;
 7651:     my %noedit;
 7652:     if (ref($row) eq 'ARRAY') {
 7653:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 7654:                                                            'internal.selfenrollmgrdc',
 7655:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 7656:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 7657:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 7658:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 7659:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 7660:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 7661:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 7662: 
 7663:         foreach my $item (@{$row}) {
 7664:             next if ($specific_managebycc{$item});
 7665:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 7666:                 $noedit{$item} = 1;
 7667:             }
 7668:         }
 7669:     }
 7670:     return %noedit;
 7671: }
 7672: 
 7673: sub visible_in_stdcat {
 7674:     my ($cdom,$cnum,$domconf) = @_;
 7675:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 7676:     unless (ref($domconf) eq 'HASH') {
 7677:         return ($visible,$cansetvis,\@vismsgs);
 7678:     }
 7679:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7680:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 7681:             $settable{'togglecats'} = 1;
 7682:         }
 7683:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 7684:             $settable{'categorize'} = 1;
 7685:         }
 7686:         $cathash = $domconf->{'coursecategories'}{'cats'};
 7687:     }
 7688:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 7689:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 7690:     } elsif ($settable{'togglecats'}) {
 7691:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 7692:     } elsif ($settable{'categorize'}) {
 7693:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 7694:     } else {
 7695:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 7696:     }
 7697:      
 7698:     my %currsettings =
 7699:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 7700:                              $cdom,$cnum);
 7701:     $visible = 0;
 7702:     if ($currsettings{'internal.coursecode'} ne '') {
 7703:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7704:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7705:             if (ref($cathash) eq 'HASH') {
 7706:                 if ($cathash->{'instcode::0'} eq '') {
 7707:                     push(@vismsgs,'dc_addinst'); 
 7708:                 } else {
 7709:                     $visible = 1;
 7710:                 }
 7711:             } else {
 7712:                 $visible = 1;
 7713:             }
 7714:         } else {
 7715:             $visible = 1;
 7716:         }
 7717:     } else {
 7718:         if (ref($cathash) eq 'HASH') {
 7719:             if ($cathash->{'instcode::0'} ne '') {
 7720:                 push(@vismsgs,'dc_instcode');
 7721:             }
 7722:         } else {
 7723:             push(@vismsgs,'dc_instcode');
 7724:         }
 7725:     }
 7726:     if ($currsettings{'categories'} ne '') {
 7727:         my $cathash;
 7728:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7729:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7730:             if (ref($cathash) eq 'HASH') {
 7731:                 if (keys(%{$cathash}) == 0) {
 7732:                     push(@vismsgs,'dc_catalog');
 7733:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 7734:                     push(@vismsgs,'dc_categories');
 7735:                 } else {
 7736:                     my @currcategories = split('&',$currsettings{'categories'});
 7737:                     my $matched = 0;
 7738:                     foreach my $cat (@currcategories) {
 7739:                         if ($cathash->{$cat} ne '') {
 7740:                             $visible = 1;
 7741:                             $matched = 1;
 7742:                             last;
 7743:                         }
 7744:                     }
 7745:                     if (!$matched) {
 7746:                         if ($settable{'categorize'}) { 
 7747:                             push(@vismsgs,'chgcat');
 7748:                         } else {
 7749:                             push(@vismsgs,'dc_chgcat');
 7750:                         }
 7751:                     }
 7752:                 }
 7753:             }
 7754:         }
 7755:     } else {
 7756:         if (ref($cathash) eq 'HASH') {
 7757:             if ((keys(%{$cathash}) > 1) || 
 7758:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 7759:                 if ($settable{'categorize'}) {
 7760:                     push(@vismsgs,'addcat');
 7761:                 } else {
 7762:                     push(@vismsgs,'dc_addcat');
 7763:                 }
 7764:             }
 7765:         }
 7766:     }
 7767:     if ($currsettings{'hidefromcat'} eq 'yes') {
 7768:         $visible = 0;
 7769:         if ($settable{'togglecats'}) {
 7770:             unshift(@vismsgs,'unhide');
 7771:         } else {
 7772:             unshift(@vismsgs,'dc_unhide')
 7773:         }
 7774:     }
 7775:     return ($visible,$cansetvis,\@vismsgs);
 7776: }
 7777: 
 7778: sub cat_visibility {
 7779:     my ($cdom) = @_;
 7780:     my %visactions = &Apache::lonlocal::texthash(
 7781:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 7782:                    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.',
 7783:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 7784:                    none => 'Display of a course catalog is disabled for this domain.',
 7785:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 7786:                    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.',
 7787:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 7788:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 7789:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 7790:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 7791:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 7792:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 7793:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 7794:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 7795:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 7796:                    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',
 7797:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 7798:     );
 7799:     if ($env{'request.role'} eq "dc./$cdom/") {
 7800:         $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;');
 7801:         $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;');
 7802:         $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;');
 7803:         $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;');
 7804:         $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;');
 7805:         $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;');
 7806:         $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;');
 7807:         $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;');
 7808:         $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;');
 7809:     }
 7810:     $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>"');
 7811:     $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>"');
 7812:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 7813:     return \%visactions;
 7814: }
 7815: 
 7816: sub new_selfenroll_dom_row {
 7817:     my ($newdom,$num) = @_;
 7818:     my $domdesc = &Apache::lonnet::domain($newdom);
 7819:     my $output;
 7820:     if ($domdesc ne '') {
 7821:         $output .= &Apache::loncommon::start_data_table_row()
 7822:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 7823:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 7824:                    .'" value="'.$newdom.'" /></span><br />'
 7825:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 7826:                    .'name="selfenroll_activate" value="'.$num.'" '
 7827:                    .'onchange="javascript:update_types('
 7828:                    ."'selfenroll_activate','$num'".');" />'
 7829:                    .&mt('Activate').'</label></span></td>';
 7830:         my @currinsttypes;
 7831:         $output .= '<td>'.&mt('User types:').'<br />'
 7832:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 7833:                    .&Apache::loncommon::end_data_table_row();
 7834:     }
 7835:     return $output;
 7836: }
 7837: 
 7838: sub selfenroll_inst_types {
 7839:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 7840:     my $output;
 7841:     my $numinrow = 4;
 7842:     my $count = 0;
 7843:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 7844:     my $othervalue = 'any';
 7845:     my $disabled;
 7846:     if ($readonly) {
 7847:         $disabled = ' disabled="disabled"';
 7848:     }
 7849:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7850:         if (keys(%{$usertypes}) > 0) {
 7851:             $othervalue = 'other';
 7852:         }
 7853:         $output .= '<table><tr>';
 7854:         foreach my $type (@{$types}) {
 7855:             if (($count > 0) && ($count%$numinrow == 0)) {
 7856:                 $output .= '</tr><tr>';
 7857:             }
 7858:             if (defined($usertypes->{$type})) {
 7859:                 my $esc_type = &escape($type);
 7860:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 7861:                            $esc_type.'" ';
 7862:                 if (ref($currinsttypes) eq 'ARRAY') {
 7863:                     if (@{$currinsttypes} > 0) {
 7864:                         if (grep(/^any$/,@{$currinsttypes})) {
 7865:                             $output .= 'checked="checked"';
 7866:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 7867:                             $output .= 'checked="checked"';
 7868:                         }
 7869:                     } else {
 7870:                         $output .= 'checked="checked"';
 7871:                     }
 7872:                 }
 7873:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 7874:             }
 7875:             $count ++;
 7876:         }
 7877:         if (($count > 0) && ($count%$numinrow == 0)) {
 7878:             $output .= '</tr><tr>';
 7879:         }
 7880:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 7881:         if (ref($currinsttypes) eq 'ARRAY') {
 7882:             if (@{$currinsttypes} > 0) {
 7883:                 if (grep(/^any$/,@{$currinsttypes})) { 
 7884:                     $output .= ' checked="checked"';
 7885:                 } elsif ($othervalue eq 'other') {
 7886:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 7887:                         $output .= ' checked="checked"';
 7888:                     }
 7889:                 }
 7890:             } else {
 7891:                 $output .= ' checked="checked"';
 7892:             }
 7893:         } else {
 7894:             $output .= ' checked="checked"';
 7895:         }
 7896:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 7897:     }
 7898:     return $output;
 7899: }
 7900: 
 7901: sub selfenroll_date_forms {
 7902:     my ($startform,$endform) = @_;
 7903:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 7904:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 7905:                                                     'LC_oddrow_value')."\n".
 7906:                   $startform."\n".
 7907:                   &Apache::lonhtmlcommon::row_closure(1).
 7908:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 7909:                                                    'LC_oddrow_value')."\n".
 7910:                   $endform."\n".
 7911:                   &Apache::lonhtmlcommon::row_closure(1).
 7912:                   &Apache::lonhtmlcommon::end_pick_box();
 7913:     return $output;
 7914: }
 7915: 
 7916: sub print_userchangelogs_display {
 7917:     my ($r,$context,$permission,$brcrum) = @_;
 7918:     my $formname = 'rolelog';
 7919:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 7920:     if ($context eq 'domain') {
 7921:         $domain = $env{'request.role.domain'};
 7922:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 7923:     } else {
 7924:         if ($context eq 'course') { 
 7925:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7926:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 7927:             $crstype = &Apache::loncommon::course_type();
 7928:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 7929:             my %saveable_parameters = ('show' => 'scalar',);
 7930:             &Apache::loncommon::store_course_settings('roles_log',
 7931:                                                       \%saveable_parameters);
 7932:             &Apache::loncommon::restore_course_settings('roles_log',
 7933:                                                         \%saveable_parameters);
 7934:         } elsif ($context eq 'author') {
 7935:             $domain = $env{'user.domain'};
 7936:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 7937:                 $username = $env{'user.name'};
 7938:             } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 7939:                 ($domain,$username) = ($1,$2);
 7940:             } else {
 7941:                 undef($domain);
 7942:             }
 7943:         }
 7944:         if ($domain ne '' && $username ne '') { 
 7945:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 7946:         }
 7947:     }
 7948:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 7949: 
 7950:     my $helpitem;
 7951:     if ($context eq 'course') {
 7952:         $helpitem = 'Course_User_Logs';
 7953:     } elsif ($context eq 'domain') {
 7954:         $helpitem = 'Domain_Role_Logs';
 7955:     } elsif ($context eq 'author') {
 7956:         $helpitem = 'Author_User_Logs';
 7957:     }
 7958:     push (@{$brcrum},
 7959:              {href => '/adm/createuser?action=changelogs',
 7960:               text => 'User Management Logs',
 7961:               help => $helpitem});
 7962:     my $bread_crumbs_component = 'User Changes';
 7963:     my $args = { bread_crumbs           => $brcrum,
 7964:                  bread_crumbs_component => $bread_crumbs_component};
 7965: 
 7966:     # Create navigation javascript
 7967:     my $jsnav = &userlogdisplay_js($formname);
 7968: 
 7969:     my $jscript = (<<ENDSCRIPT);
 7970: <script type="text/javascript">
 7971: // <![CDATA[
 7972: $jsnav
 7973: // ]]>
 7974: </script>
 7975: ENDSCRIPT
 7976: 
 7977:     # print page header
 7978:     $r->print(&header($jscript,$args));
 7979: 
 7980:     # set defaults
 7981:     my $now = time();
 7982:     my $defstart = $now - (7*24*3600); #7 days ago 
 7983:     my %defaults = (
 7984:                      page               => '1',
 7985:                      show               => '10',
 7986:                      role               => 'any',
 7987:                      chgcontext         => 'any',
 7988:                      rolelog_start_date => $defstart,
 7989:                      rolelog_end_date   => $now,
 7990:                      approvals          => 'any',
 7991:                    );
 7992:     my $more_records = 0;
 7993: 
 7994:     # set current
 7995:     my %curr;
 7996:     foreach my $item ('show','page','role','chgcontext','approvals') {
 7997:         $curr{$item} = $env{'form.'.$item};
 7998:     }
 7999:     my ($startdate,$enddate) = 
 8000:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 8001:     $curr{'rolelog_start_date'} = $startdate;
 8002:     $curr{'rolelog_end_date'} = $enddate;
 8003:     foreach my $key (keys(%defaults)) {
 8004:         if ($curr{$key} eq '') {
 8005:             $curr{$key} = $defaults{$key};
 8006:         }
 8007:     }
 8008:     my (%whodunit,%changed,$version);
 8009:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 8010:     my ($minshown,$maxshown);
 8011:     $minshown = 1;
 8012:     my $count = 0;
 8013:     if ($curr{'show'} =~ /\D/) {
 8014:         $curr{'page'} = 1;
 8015:     } else {
 8016:         $maxshown = $curr{'page'} * $curr{'show'};
 8017:         if ($curr{'page'} > 1) {
 8018:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8019:         }
 8020:     }
 8021: 
 8022:     # Form Header
 8023:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8024:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 8025:                                    $version,$crstype));
 8026: 
 8027:     my $showntableheader = 0;
 8028: 
 8029:     # Table Header
 8030:     my $tableheader = 
 8031:         &Apache::loncommon::start_data_table_header_row()
 8032:        .'<th>&nbsp;</th>'
 8033:        .'<th>'.&mt('When').'</th>'
 8034:        .'<th>'.&mt('Who made the change').'</th>'
 8035:        .'<th>'.&mt('Changed User').'</th>'
 8036:        .'<th>'.&mt('Role').'</th>';
 8037: 
 8038:     if ($context eq 'course') {
 8039:         $tableheader .= '<th>'.&mt('Section').'</th>';
 8040:     }
 8041:     $tableheader .=
 8042:         '<th>'.&mt('Context').'</th>'
 8043:        .'<th>'.&mt('Start').'</th>'
 8044:        .'<th>'.&mt('End').'</th>'
 8045:        .&Apache::loncommon::end_data_table_header_row();
 8046: 
 8047:     # Display user change log data
 8048:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 8049:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 8050:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 8051:         if ($curr{'show'} !~ /\D/) {
 8052:             if ($count >= $curr{'page'} * $curr{'show'}) {
 8053:                 $more_records = 1;
 8054:                 last;
 8055:             }
 8056:         }
 8057:         if ($curr{'role'} ne 'any') {
 8058:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 8059:         }
 8060:         if ($curr{'chgcontext'} ne 'any') {
 8061:             if ($curr{'chgcontext'} eq 'selfenroll') {
 8062:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 8063:             } else {
 8064:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 8065:             }
 8066:         }
 8067:         if (($context eq 'course') && ($viewablesec ne '')) {
 8068:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 8069:         }
 8070:         if ($curr{'approvals'} eq 'none') {
 8071:             next if ($roleslog{$id}{'logentry'}{'approval'});
 8072:         } elsif ($curr{'approvals'} ne 'any') { 
 8073:             next if ($roleslog{$id}{'logentry'}{'approval'} ne $curr{'approvals'});
 8074:         }
 8075:         $count ++;
 8076:         next if ($count < $minshown);
 8077:         unless ($showntableheader) {
 8078:             $r->print(&Apache::loncommon::start_data_table()
 8079:                      .$tableheader);
 8080:             $r->rflush();
 8081:             $showntableheader = 1;
 8082:         }
 8083:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 8084:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 8085:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 8086:         }
 8087:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 8088:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 8089:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 8090:         }
 8091:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 8092:         if ($sec eq '') {
 8093:             $sec = &mt('None');
 8094:         }
 8095:         my ($rolestart,$roleend);
 8096:         if ($roleslog{$id}{'delflag'}) {
 8097:             $rolestart = &mt('deleted');
 8098:             $roleend = &mt('deleted');
 8099:         } else {
 8100:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 8101:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 8102:             if ($rolestart eq '' || $rolestart == 0) {
 8103:                 $rolestart = &mt('No start date'); 
 8104:             } else {
 8105:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 8106:             }
 8107:             if ($roleend eq '' || $roleend == 0) { 
 8108:                 $roleend = &mt('No end date');
 8109:             } else {
 8110:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 8111:             }
 8112:         }
 8113:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 8114:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 8115:             $chgcontext = 'selfenroll';
 8116:         }
 8117:         my %lt = &rolechg_contexts($context,$crstype);
 8118:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 8119:             $chgcontext = $lt{$chgcontext};
 8120:         }
 8121:         my ($showreqby,%reqby);
 8122:         if (($roleslog{$id}{'logentry'}{'approval'}) &&
 8123:             ($roleslog{$id}{'logentry'}{'requester'})) {
 8124:             if ($reqby{$roleslog{$id}{'logentry'}{'requester'}} eq '') {
 8125:                 my ($requname,$requdom) = split(/:/,$roleslog{$id}{'logentry'}{'requester'});
 8126:                 $reqby{$roleslog{$id}{'logentry'}{'requester'}} =
 8127:                     &Apache::loncommon::plainname($requname,$requdom);
 8128:             }
 8129:             $showreqby = &mt('Requester').': <span class="LC_nobreak">'.$reqby{$roleslog{$id}{'logentry'}{'requester'}}.'</span><br />';
 8130:             if ($roleslog{$id}{'logentry'}{'approval'} eq 'domain') {
 8131:                 $showreqby .= &mt('Adjudicator').': <span class="LC_nobreak">'.
 8132:                               $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.
 8133:                               '</span>';
 8134:             } else {
 8135:                 $showreqby .= '<span class="LC_nobreak">'.&mt('User approved').'</span>';
 8136:             }
 8137:         } else {
 8138:             $showreqby = $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}};
 8139:         }
 8140:         $r->print(
 8141:             &Apache::loncommon::start_data_table_row()
 8142:            .'<td>'.$count.'</td>'
 8143:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 8144:            .'<td>'.$showreqby.'</td>'
 8145:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 8146:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 8147:         if ($context eq 'course') { 
 8148:             $r->print('<td>'.$sec.'</td>');
 8149:         }
 8150:         $r->print(
 8151:             '<td>'.$chgcontext.'</td>'
 8152:            .'<td>'.$rolestart.'</td>'
 8153:            .'<td>'.$roleend.'</td>'
 8154:            .&Apache::loncommon::end_data_table_row()."\n");
 8155:     }
 8156: 
 8157:     if ($showntableheader) { # Table footer, if content displayed above
 8158:         $r->print(&Apache::loncommon::end_data_table().
 8159:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8160:     } else { # No content displayed above
 8161:         $r->print('<p class="LC_info">'
 8162:                  .&mt('There are no records to display.')
 8163:                  .'</p>'
 8164:         );
 8165:     }
 8166: 
 8167:     # Form Footer
 8168:     $r->print( 
 8169:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8170:        .'<input type="hidden" name="action" value="changelogs" />'
 8171:        .'</form>');
 8172:     return;
 8173: }
 8174: 
 8175: sub print_useraccesslogs_display {
 8176:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 8177:     my $formname = 'accesslog';
 8178:     my $form = 'document.accesslog';
 8179: 
 8180: # set breadcrumbs
 8181:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 8182:     my $prevphasestr;
 8183:     if ($env{'form.popup'}) {
 8184:         $brcrum = [];
 8185:     } else {
 8186:         push (@{$brcrum},
 8187:             {href => "javascript:backPage($form)",
 8188:              text => $breadcrumb_text{'search'}});
 8189:         my @prevphases;
 8190:         if ($env{'form.prevphases'}) {
 8191:             @prevphases = split(/,/,$env{'form.prevphases'});
 8192:             $prevphasestr = $env{'form.prevphases'};
 8193:         }
 8194:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 8195:             push(@{$brcrum},
 8196:                   {href => "javascript:backPage($form,'get_user_info','select')",
 8197:                    text => $breadcrumb_text{'userpicked'}});
 8198:             if ($env{'form.phase'} eq 'userpicked') {
 8199:                 $prevphasestr = 'userpicked';
 8200:             }
 8201:         }
 8202:     }
 8203:     push(@{$brcrum},
 8204:              {href => '/adm/createuser?action=accesslogs',
 8205:               text => 'User access logs',
 8206:               help => 'Domain_User_Access_Logs'});
 8207:     my $bread_crumbs_component = 'User Access Logs';
 8208:     my $args = { bread_crumbs           => $brcrum,
 8209:                  bread_crumbs_component => 'User Management'};
 8210:     if ($env{'form.popup'}) {
 8211:         $args->{'no_nav_bar'} = 1;
 8212:         $args->{'bread_crumbs_nomenu'} = 1;
 8213:     }
 8214: 
 8215: # set javascript
 8216:     my ($jsback,$elements) = &crumb_utilities();
 8217:     my $jsnav = &userlogdisplay_js($formname);
 8218: 
 8219:     my $jscript = (<<ENDSCRIPT);
 8220: <script type="text/javascript">
 8221: // <![CDATA[
 8222: 
 8223: $jsback
 8224: $jsnav
 8225: 
 8226: // ]]>
 8227: </script>
 8228: 
 8229: ENDSCRIPT
 8230: 
 8231: # print page header
 8232:     $r->print(&header($jscript,$args));
 8233: 
 8234: # early out unless log data can be displayed.
 8235:     unless ($permission->{'activity'}) {
 8236:         $r->print('<p class="LC_warning">'
 8237:                  .&mt('You do not have rights to display user access logs.')
 8238:                  .'</p>');
 8239:         if ($env{'form.popup'}) {
 8240:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8241:         } else {
 8242:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8243:         }
 8244:         return;
 8245:     }
 8246: 
 8247:     unless ($udom eq $env{'request.role.domain'}) {
 8248:         $r->print('<p class="LC_warning">'
 8249:                  .&mt("User's domain must match role's domain")
 8250:                  .'</p>'
 8251:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8252:         return;
 8253:     }
 8254: 
 8255:     if (($uname eq '') || ($udom eq '')) {
 8256:         $r->print('<p class="LC_warning">'
 8257:                  .&mt('Invalid username or domain')
 8258:                  .'</p>'
 8259:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8260:         return;
 8261:     }
 8262: 
 8263:     if (&Apache::lonnet::privileged($uname,$udom,
 8264:                                     [$env{'request.role.domain'}],['dc','su'])) {
 8265:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 8266:                                             [$env{'request.role.domain'}],['dc','su'])) {
 8267:             $r->print('<p class="LC_warning">'
 8268:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 8269:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 8270:                                                          $uname,$udom))
 8271:                  .'</p>');
 8272:             if ($env{'form.popup'}) {
 8273:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8274:             } else {
 8275:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8276:             }
 8277:             return;
 8278:         }
 8279:     }
 8280: 
 8281: # set defaults
 8282:     my $now = time();
 8283:     my $defstart = $now - (7*24*3600);
 8284:     my %defaults = (
 8285:                      page                 => '1',
 8286:                      show                 => '10',
 8287:                      activity             => 'any',
 8288:                      accesslog_start_date => $defstart,
 8289:                      accesslog_end_date   => $now,
 8290:                    );
 8291:     my $more_records = 0;
 8292: 
 8293: # set current
 8294:     my %curr;
 8295:     foreach my $item ('show','page','activity') {
 8296:         $curr{$item} = $env{'form.'.$item};
 8297:     }
 8298:     my ($startdate,$enddate) =
 8299:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 8300:     $curr{'accesslog_start_date'} = $startdate;
 8301:     $curr{'accesslog_end_date'} = $enddate;
 8302:     foreach my $key (keys(%defaults)) {
 8303:         if ($curr{$key} eq '') {
 8304:             $curr{$key} = $defaults{$key};
 8305:         }
 8306:     }
 8307:     my ($minshown,$maxshown);
 8308:     $minshown = 1;
 8309:     my $count = 0;
 8310:     if ($curr{'show'} =~ /\D/) {
 8311:         $curr{'page'} = 1;
 8312:     } else {
 8313:         $maxshown = $curr{'page'} * $curr{'show'};
 8314:         if ($curr{'page'} > 1) {
 8315:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8316:         }
 8317:     }
 8318: 
 8319: # form header
 8320:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8321:               &activity_display_filter($formname,\%curr));
 8322: 
 8323:     my $showntableheader = 0;
 8324:     my ($nav_script,$nav_links);
 8325: 
 8326: # table header
 8327:     my $heading = '<h3>'.
 8328:         &mt('User access logs for: [_1]',
 8329:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 8330:     my $tableheader = $heading
 8331:        .&Apache::loncommon::start_data_table_header_row()
 8332:        .'<th>&nbsp;</th>'
 8333:        .'<th>'.&mt('When').'</th>'
 8334:        .'<th>'.&mt('HostID').'</th>'
 8335:        .'<th>'.&mt('Event').'</th>'
 8336:        .'<th>'.&mt('Other data').'</th>'
 8337:        .&Apache::loncommon::end_data_table_header_row();
 8338: 
 8339:     my %filters=(
 8340:         start  => $curr{'accesslog_start_date'},
 8341:         end    => $curr{'accesslog_end_date'},
 8342:         action => $curr{'activity'},
 8343:     );
 8344: 
 8345:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 8346:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8347:         my (%courses,%missing);
 8348:         my @results = split(/\&/,$reply);
 8349:         foreach my $item (reverse(@results)) {
 8350:             my ($timestamp,$host,$event) = split(/:/,$item);
 8351:             next unless ($event =~ /^(Log|Role)/);
 8352:             if ($curr{'show'} !~ /\D/) {
 8353:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 8354:                     $more_records = 1;
 8355:                     last;
 8356:                 }
 8357:             }
 8358:             $count ++;
 8359:             next if ($count < $minshown);
 8360:             unless ($showntableheader) {
 8361:                 $r->print($nav_script
 8362:                          .&Apache::loncommon::start_data_table()
 8363:                          .$tableheader);
 8364:                 $r->rflush();
 8365:                 $showntableheader = 1;
 8366:             }
 8367:             my ($shown,$extra);
 8368:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 8369:             if ($event eq 'Role') {
 8370:                 my ($rolecode,$extent) = split(/\./,$data,2);
 8371:                 next if ($extent eq '');
 8372:                 my ($crstype,$desc,$info);
 8373:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 8374:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 8375:                     my $cid = $cdom.'_'.$cnum;
 8376:                     if (exists($courses{$cid})) {
 8377:                         $crstype = $courses{$cid}{'type'};
 8378:                         $desc = $courses{$cid}{'description'};
 8379:                     } elsif ($missing{$cid}) {
 8380:                         $crstype = 'Course';
 8381:                         $desc = 'Course/Community';
 8382:                     } else {
 8383:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8384:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 8385:                             $courses{$cid} = $crsinfo{$cid};
 8386:                             $crstype = $crsinfo{$cid}{'type'};
 8387:                             $desc = $crsinfo{$cid}{'description'};
 8388:                         } else {
 8389:                             $missing{$cid} = 1;
 8390:                         }
 8391:                     }
 8392:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 8393:                     if ($sec ne '') {
 8394:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 8395:                     }
 8396:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 8397:                     my ($dom,$name) = ($1,$2);
 8398:                     if ($rolecode eq 'au') {
 8399:                         $extra = '';
 8400:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 8401:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 8402:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 8403:                         $extra = &mt('Domain: [_1]',$dom);
 8404:                     }
 8405:                 }
 8406:                 my $rolename;
 8407:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 8408:                     my $role = $3;
 8409:                     my $owner = "($2:$1)";
 8410:                     if ($2 eq $1.'-domainconfig') {
 8411:                         $owner = '(ad hoc)';
 8412:                     }
 8413:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 8414:                 } else {
 8415:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 8416:                 }
 8417:                 $shown = &mt('Role selection: [_1]',$rolename);
 8418:             } else {
 8419:                 $shown = &mt($event);
 8420:                 if ($data =~ /^webdav/) {
 8421:                     my ($path,$clientip) = split(/\s+/,$data,2);
 8422:                     $path =~ s/^webdav//;
 8423:                     if ($clientip ne '') {
 8424:                         $extra = &mt('Client IP address: [_1]',$clientip);
 8425:                     }
 8426:                     if ($path ne '') {
 8427:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 8428:                     }
 8429:                 } elsif ($data ne '') {
 8430:                     $extra = &mt('Client IP address: [_1]',$data);
 8431:                 }
 8432:             }
 8433:             $r->print(
 8434:             &Apache::loncommon::start_data_table_row()
 8435:            .'<td>'.$count.'</td>'
 8436:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 8437:            .'<td>'.$host.'</td>'
 8438:            .'<td>'.$shown.'</td>'
 8439:            .'<td>'.$extra.'</td>'
 8440:            .&Apache::loncommon::end_data_table_row()."\n");
 8441:         }
 8442:     }
 8443: 
 8444:     if ($showntableheader) { # Table footer, if content displayed above
 8445:         $r->print(&Apache::loncommon::end_data_table().
 8446:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8447:     } else { # No content displayed above
 8448:         $r->print($heading.'<p class="LC_info">'
 8449:                  .&mt('There are no records to display.')
 8450:                  .'</p>');
 8451:     }
 8452: 
 8453:     if ($env{'form.popup'} == 1) {
 8454:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 8455:     }
 8456: 
 8457:     # Form Footer
 8458:     $r->print(
 8459:         '<input type="hidden" name="currstate" value="" />'
 8460:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 8461:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 8462:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8463:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 8464:        .'<input type="hidden" name="phase" value="activity" />'
 8465:        .'<input type="hidden" name="action" value="accesslogs" />'
 8466:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 8467:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 8468:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 8469:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 8470:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 8471:        .'</form>');
 8472:     return;
 8473: }
 8474: 
 8475: sub earlyout_accesslog_form {
 8476:     my ($formname,$prevphasestr,$udom) = @_;
 8477:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 8478:    return <<"END";
 8479: <form action="/adm/createuser" method="post" name="$formname">
 8480: <input type="hidden" name="currstate" value="" />
 8481: <input type="hidden" name="prevphases" value="$prevphasestr" />
 8482: <input type="hidden" name="phase" value="activity" />
 8483: <input type="hidden" name="action" value="accesslogs" />
 8484: <input type="hidden" name="srchdomain" value="$udom" />
 8485: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 8486: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 8487: <input type="hidden" name="srchterm" value="$srchterm" />
 8488: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 8489: </form>
 8490: END
 8491: }
 8492: 
 8493: sub activity_display_filter {
 8494:     my ($formname,$curr) = @_;
 8495:     my $nolink = 1;
 8496:     my $output = '<table><tr><td valign="top">'.
 8497:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 8498:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8499:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8500:                  '</td><td>&nbsp;&nbsp;</td>';
 8501:     my $startform =
 8502:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 8503:                                             $curr->{'accesslog_start_date'},undef,
 8504:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8505:     my $endform =
 8506:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 8507:                                             $curr->{'accesslog_end_date'},undef,
 8508:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8509:     my %lt = &Apache::lonlocal::texthash (
 8510:                                           activity => 'Activity',
 8511:                                           Role     => 'Role selection',
 8512:                                           log      => 'Log-in or Logout',
 8513:     );
 8514:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 8515:                '<table><tr><td>'.&mt('After:').
 8516:                '</td><td>'.$startform.'</td></tr>'.
 8517:                '<tr><td>'.&mt('Before:').'</td>'.
 8518:                '<td>'.$endform.'</td></tr></table>'.
 8519:                '</td>'.
 8520:                '<td>&nbsp;&nbsp;</td>'.
 8521:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 8522:                '<select name="activity"><option value="any"';
 8523:     if ($curr->{'activity'} eq 'any') {
 8524:         $output .= ' selected="selected"';
 8525:     }
 8526:     $output .= '>'.&mt('Any').'</option>'."\n";
 8527:     foreach my $activity ('Role','log') {
 8528:         my $selstr = '';
 8529:         if ($activity eq $curr->{'activity'}) {
 8530:             $selstr = ' selected="selected"';
 8531:         }
 8532:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 8533:     }
 8534:     $output .= '</select></td>'.
 8535:                '</tr></table>';
 8536:     # Update Display button
 8537:     $output .= '<p>'
 8538:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8539:               .'</p><hr />';
 8540:     return $output;
 8541: }
 8542: 
 8543: sub userlogdisplay_js {
 8544:     my ($formname) = @_;
 8545:     return <<"ENDSCRIPT";
 8546: 
 8547: function chgPage(caller) {
 8548:     if (caller == 'previous') {
 8549:         document.$formname.page.value --;
 8550:     }
 8551:     if (caller == 'next') {
 8552:         document.$formname.page.value ++;
 8553:     }
 8554:     document.$formname.submit();
 8555:     return;
 8556: }
 8557: ENDSCRIPT
 8558: }
 8559: 
 8560: sub userlogdisplay_navlinks {
 8561:     my ($curr,$more_records) = @_;
 8562:     return unless(ref($curr) eq 'HASH');
 8563:     # Navigation Buttons
 8564:     my $nav_links = '<p>';
 8565:     if (($curr->{'page'} > 1) || ($more_records)) {
 8566:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 8567:             $nav_links .= '<input type="button"'
 8568:                          .' onclick="javascript:chgPage('."'previous'".');"'
 8569:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 8570:                          .'" /> ';
 8571:         }
 8572:         if ($more_records) {
 8573:             $nav_links .= '<input type="button"'
 8574:                          .' onclick="javascript:chgPage('."'next'".');"'
 8575:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 8576:                          .'" />';
 8577:         }
 8578:     }
 8579:     $nav_links .= '</p>';
 8580:     return $nav_links;
 8581: }
 8582: 
 8583: sub role_display_filter {
 8584:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 8585:     my $nolink = 1;
 8586:     my $output = '<table><tr><td valign="top">'.
 8587:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 8588:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8589:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8590:                  '</td><td>&nbsp;&nbsp;</td>';
 8591:     my $startform =
 8592:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 8593:                                             $curr->{'rolelog_start_date'},undef,
 8594:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8595:     my $endform =
 8596:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 8597:                                             $curr->{'rolelog_end_date'},undef,
 8598:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8599:     my %lt = &rolechg_contexts($context,$crstype);
 8600:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 8601:                '<table><tr><td>'.&mt('After:').
 8602:                '</td><td>'.$startform.'</td></tr>'.
 8603:                '<tr><td>'.&mt('Before:').'</td>'.
 8604:                '<td>'.$endform.'</td></tr></table>'.
 8605:                '</td>'.
 8606:                '<td>&nbsp;&nbsp;</td>'.
 8607:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 8608:                '<select name="role"><option value="any"';
 8609:     if ($curr->{'role'} eq 'any') {
 8610:         $output .= ' selected="selected"';
 8611:     }
 8612:     $output .= '>'.&mt('Any').'</option>'."\n";
 8613:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 8614:     foreach my $role (@roles) {
 8615:         my $plrole;
 8616:         if ($role eq 'cr') {
 8617:             $plrole = &mt('Custom Role');
 8618:         } else {
 8619:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8620:         }
 8621:         my $selstr = '';
 8622:         if ($role eq $curr->{'role'}) {
 8623:             $selstr = ' selected="selected"';
 8624:         }
 8625:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 8626:     }
 8627:     $output .= '</select></td>'.
 8628:                '<td>&nbsp;&nbsp;</td>'.
 8629:                '<td valign="top"><b>'.
 8630:                &mt('Context:').'</b><br /><select name="chgcontext">';
 8631:     my @posscontexts;
 8632:     if ($context eq 'course') {
 8633:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype','ltienroll');
 8634:     } elsif ($context eq 'domain') {
 8635:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 8636:     } else {
 8637:         @posscontexts = ('any','author','coauthor','domain');
 8638:     }
 8639:     foreach my $chgtype (@posscontexts) {
 8640:         my $selstr = '';
 8641:         if ($curr->{'chgcontext'} eq $chgtype) {
 8642:             $selstr = ' selected="selected"';
 8643:         }
 8644:         if ($context eq 'course') {
 8645:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 8646:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 8647:             }
 8648:         }
 8649:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 8650:     }
 8651:     my @possapprovals = ('any','none','domain','user');
 8652:     my %apptxt = &approval_types();
 8653:     $output .= '</select></td>'.
 8654:                '<td>&nbsp;&nbsp;</td>'.
 8655:                '<td valign="top"><b>'.
 8656:                &mt('Approvals:').'</b><br /><select name="approvals">';
 8657:     foreach my $approval (@possapprovals) {
 8658:         my $selstr = '';
 8659:         if ($curr->{'approvals'} eq $approval) {
 8660:             $selstr = ' selected="selected"';
 8661:         }    
 8662:         $output .= '<option value="'.$approval.'"'.$selstr.'>'.$apptxt{$approval}.'</option>';
 8663:     }
 8664:     $output .= '</select></td></tr></table>';
 8665: 
 8666:     # Update Display button
 8667:     $output .= '<p>'
 8668:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8669:               .'</p>';
 8670: 
 8671:     # Server version info
 8672:     my $needsrev = '2.11.0';
 8673:     if ($context eq 'course') {
 8674:         $needsrev = '2.7.0';
 8675:     }
 8676:     
 8677:     $output .= '<p class="LC_info">'
 8678:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 8679:                   ,$needsrev);
 8680:     if ($version) {
 8681:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 8682:     }
 8683:     $output .= '</p><hr />';
 8684:     return $output;
 8685: }
 8686: 
 8687: sub rolechg_contexts {
 8688:     my ($context,$crstype) = @_;
 8689:     my %lt;
 8690:     if ($context eq 'course') {
 8691:         %lt = &Apache::lonlocal::texthash (
 8692:                                              any          => 'Any',
 8693:                                              automated    => 'Automated Enrollment',
 8694:                                              chgtype      => 'Enrollment Type/Lock Change',
 8695:                                              updatenow    => 'Roster Update',
 8696:                                              createcourse => 'Course Creation',
 8697:                                              course       => 'User Management in course',
 8698:                                              domain       => 'User Management in domain',
 8699:                                              selfenroll   => 'Self-enrolled',
 8700:                                              requestcourses => 'Course Request',
 8701:                                              ltienroll    => 'Enrollment via LTI',
 8702:                                          );
 8703:         if ($crstype eq 'Community') {
 8704:             $lt{'createcourse'} = &mt('Community Creation');
 8705:             $lt{'course'} = &mt('User Management in community');
 8706:             $lt{'requestcourses'} = &mt('Community Request');
 8707:         }
 8708:     } elsif ($context eq 'domain') {
 8709:         %lt = &Apache::lonlocal::texthash (
 8710:                                              any           => 'Any',
 8711:                                              domain        => 'User Management in domain',
 8712:                                              requestauthor => 'Authoring Request',
 8713:                                              server        => 'Command line script (DC role)',
 8714:                                              domconfig     => 'Self-enrolled',
 8715:                                          );
 8716:     } else {
 8717:         %lt = &Apache::lonlocal::texthash (
 8718:                                              any    => 'Any',
 8719:                                              domain => 'User Management in domain',
 8720:                                              author => 'User Management by author',
 8721:                                              coauthor => 'User Management by coauthor',
 8722:                                          );
 8723:     } 
 8724:     return %lt;
 8725: }
 8726: 
 8727: sub approval_types {
 8728:     return &Apache::lonlocal::texthash (
 8729:                                           any => 'Any',
 8730:                                           none => 'No approval needed',
 8731:                                           user => 'Role recipient approval',
 8732:                                           domain => 'Domain coordinator approval',
 8733:                                        );
 8734: }
 8735: 
 8736: sub print_helpdeskaccess_display {
 8737:     my ($r,$permission,$brcrum) = @_;
 8738:     my $formname = 'helpdeskaccess';
 8739:     my $helpitem = 'Course_Helpdesk_Access';
 8740:     push (@{$brcrum},
 8741:              {href => '/adm/createuser?action=helpdesk',
 8742:               text => 'Helpdesk Access',
 8743:               help => $helpitem});
 8744:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8745:     my $args = { bread_crumbs           => $brcrum,
 8746:                  bread_crumbs_component => $bread_crumbs_component};
 8747: 
 8748:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8749:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8750:     my $confname = $cdom.'-domainconfig';
 8751:     my $crstype = &Apache::loncommon::course_type();
 8752: 
 8753:     my @accesstypes = ('all','dh','da','none');
 8754:     my ($numstatustypes,@jsarray);
 8755:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8756:     if (ref($types) eq 'ARRAY') {
 8757:         if (@{$types} > 0) {
 8758:             $numstatustypes = scalar(@{$types});
 8759:             push(@accesstypes,'status');
 8760:             @jsarray = ('bystatus');
 8761:         }
 8762:     }
 8763:     my %customroles = &get_domain_customroles($cdom,$confname);
 8764:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8765:     if (keys(%domhelpdesk)) {
 8766:        push(@accesstypes,('inc','exc'));
 8767:        push(@jsarray,('notinc','notexc'));
 8768:     }
 8769:     push(@jsarray,'privs');
 8770:     my $hiddenstr = join("','",@jsarray);
 8771:     my $rolestr = join("','",sort(keys(%customroles)));
 8772: 
 8773:     my $jscript;
 8774:     my (%settings,%overridden);
 8775:     if (keys(%customroles)) {
 8776:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8777:                                 $types,\%customroles,\%settings,\%overridden);
 8778:         my %jsfull=();
 8779:         my %jslevels= (
 8780:                      course => {},
 8781:                      domain => {},
 8782:                      system => {},
 8783:                     );
 8784:         my %jslevelscurrent=(
 8785:                            course => {},
 8786:                            domain => {},
 8787:                            system => {},
 8788:                           );
 8789:         my (%privs,%jsprivs);
 8790:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 8791:         foreach my $priv (keys(%jsfull)) {
 8792:             if ($jslevels{'course'}{$priv}) {
 8793:                 $jsprivs{$priv} = 1;
 8794:             }
 8795:         }
 8796:         my (%elements,%stored);
 8797:         foreach my $role (keys(%customroles)) {
 8798:             $elements{$role.'_access'} = 'radio';
 8799:             $elements{$role.'_incrs'} = 'radio';
 8800:             if ($numstatustypes) {
 8801:                 $elements{$role.'_status'} = 'checkbox';
 8802:             }
 8803:             if (keys(%domhelpdesk) > 0) {
 8804:                 $elements{$role.'_staff_inc'} = 'checkbox';
 8805:                 $elements{$role.'_staff_exc'} = 'checkbox';
 8806:             }
 8807:             $elements{$role.'_override'} = 'checkbox';
 8808:             if (ref($settings{$role}) eq 'HASH') {
 8809:                 if ($settings{$role}{'access'} ne '') {
 8810:                     my $curraccess = $settings{$role}{'access'};
 8811:                     $stored{$role.'_access'} = $curraccess;
 8812:                     $stored{$role.'_incrs'} = 1;
 8813:                     if ($curraccess eq 'status') {
 8814:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 8815:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 8816:                         }
 8817:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8818:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 8819:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 8820:                         }
 8821:                     }
 8822:                 } else {
 8823:                     $stored{$role.'_incrs'} = 0;
 8824:                 }
 8825:                 $stored{$role.'_override'} = [];
 8826:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 8827:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 8828:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 8829:                             push(@{$stored{$role.'_override'}},$priv);
 8830:                         }
 8831:                     }
 8832:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 8833:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 8834:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 8835:                                 push(@{$stored{$role.'_override'}},$priv);
 8836:                             }
 8837:                         }
 8838:                     }
 8839:                 }
 8840:             } else {
 8841:                 $stored{$role.'_incrs'} = 0;
 8842:             }
 8843:         }
 8844:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 8845:     }
 8846: 
 8847:     my $js = <<"ENDJS";
 8848: <script type="text/javascript">
 8849: // <![CDATA[
 8850: $jscript;
 8851: 
 8852: function switchRoleTab(caller,role) {
 8853:     if (document.getElementById(role+'_maindiv')) {
 8854:         if (caller.id != 'LC_current_minitab') {
 8855:             if (document.getElementById('LC_current_minitab')) {
 8856:                 document.getElementById('LC_current_minitab').id=null;
 8857:             }
 8858:             var roledivs = Array('$rolestr');
 8859:             if (roledivs.length > 0) {
 8860:                 for (var i=0; i<roledivs.length; i++) {
 8861:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 8862:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 8863:                     }
 8864:                 }
 8865:             }
 8866:             caller.id = 'LC_current_minitab';
 8867:             document.getElementById(role+'_maindiv').style.display='block';
 8868:         }
 8869:     }
 8870:     return false;
 8871: }
 8872: 
 8873: function helpdeskAccess(role) {
 8874:     var curraccess = null;
 8875:     if (document.$formname.elements[role+'_access'].length) {
 8876:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 8877:             if (document.$formname.elements[role+'_access'][i].checked) {
 8878:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 8879:             }
 8880:         }
 8881:     }
 8882:     var shown = Array();
 8883:     var hidden = Array();
 8884:     if (curraccess == 'none') {
 8885:         hidden = Array ('$hiddenstr');
 8886:     } else {
 8887:         if (curraccess == 'status') {
 8888:             shown = Array ('bystatus','privs');
 8889:             hidden = Array ('notinc','notexc');
 8890:         } else {
 8891:             if (curraccess == 'exc') {
 8892:                 shown = Array ('notexc','privs');
 8893:                 hidden = Array ('notinc','bystatus');
 8894:             }
 8895:             if (curraccess == 'inc') {
 8896:                 shown = Array ('notinc','privs');
 8897:                 hidden = Array ('notexc','bystatus');
 8898:             }
 8899:             if (curraccess == 'all') {
 8900:                 shown = Array ('privs');
 8901:                 hidden = Array ('notinc','notexc','bystatus');
 8902:             }
 8903:         }
 8904:     }
 8905:     if (hidden.length > 0) {
 8906:         for (var i=0; i<hidden.length; i++) {
 8907:             if (document.getElementById(role+'_'+hidden[i])) {
 8908:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 8909:             }
 8910:         }
 8911:     }
 8912:     if (shown.length > 0) {
 8913:         for (var i=0; i<shown.length; i++) {
 8914:             if (document.getElementById(role+'_'+shown[i])) {
 8915:                 if (shown[i] == 'privs') {
 8916:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 8917:                 } else {
 8918:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 8919:                 }
 8920:             }
 8921:         }
 8922:     }
 8923:     return;
 8924: }
 8925: 
 8926: function toggleAccess(role) {
 8927:     if ((document.getElementById(role+'_setincrs')) &&
 8928:         (document.getElementById(role+'_setindom'))) {
 8929:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 8930:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 8931:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 8932:                     document.getElementById(role+'_setindom').style.display = 'none';
 8933:                     document.getElementById(role+'_setincrs').style.display = 'block';
 8934:                 } else {
 8935:                     document.getElementById(role+'_setincrs').style.display = 'none';
 8936:                     document.getElementById(role+'_setindom').style.display = 'block';
 8937:                 }
 8938:                 break;
 8939:             }
 8940:         }
 8941:     }
 8942:     return;
 8943: }
 8944: 
 8945: // ]]>
 8946: </script>
 8947: ENDJS
 8948: 
 8949:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 8950: 
 8951:     # print page header
 8952:     $r->print(&header($js,$args));
 8953:     # print form header
 8954:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 8955: 
 8956:     if (keys(%customroles)) {
 8957:         my %lt = &Apache::lonlocal::texthash(
 8958:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 8959:                     'rou'    => 'Role usage',
 8960:                     'whi'    => 'Which helpdesk personnel may use this role?',
 8961:                     'udd'    => 'Use domain default',
 8962:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 8963:                     'dh'     => 'All with domain helpdesk role',
 8964:                     'da'     => 'All with domain helpdesk assistant role',
 8965:                     'none'   => 'None',
 8966:                     'status' => 'Determined based on institutional status',
 8967:                     'inc'    => 'Include all, but exclude specific personnel',
 8968:                     'exc'    => 'Exclude all, but include specific personnel',
 8969:                     'hel'    => 'Helpdesk',
 8970:                     'rpr'    => 'Role privileges',
 8971:                  );
 8972:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 8973:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8974:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 8975:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8976:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8977:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8978:             }
 8979:         }
 8980:         my $count = 0;
 8981:         foreach my $role (sort(keys(%customroles))) {
 8982:             my ($order,$desc,$access_in_dom);
 8983:             if (ref($domcurrent{$role}) eq 'HASH') {
 8984:                 $order = $domcurrent{$role}{'order'};
 8985:                 $desc = $domcurrent{$role}{'desc'};
 8986:                 $access_in_dom = $domcurrent{$role}{'access'};
 8987:             }
 8988:             if ($order eq '') {
 8989:                 $order = $count;
 8990:             }
 8991:             $ordered{$order} = $role;
 8992:             if ($desc ne '') {
 8993:                 $description{$role} = $desc;
 8994:             } else {
 8995:                 $description{$role}= $role;
 8996:             }
 8997:             $count++;
 8998:         }
 8999:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9000:         my @roles_by_num = ();
 9001:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9002:             push(@roles_by_num,$ordered{$item});
 9003:         }
 9004:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 9005:         if ($permission->{'owner'}) {
 9006:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 9007:             $r->print('<input type="hidden" name="state" value="process" />'.
 9008:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 9009:         } else {
 9010:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 9011:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 9012:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 9013:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 9014:             }
 9015:             $disabled = ' disabled="disabled"';
 9016:         }
 9017:         $r->print('</p>');
 9018: 
 9019:         $r->print('<div id="LC_minitab_header"><ul>');
 9020:         my $count = 0;
 9021:         my %visibility;
 9022:         foreach my $role (@roles_by_num) {
 9023:             my $id;
 9024:             if ($count == 0) {
 9025:                 $id=' id="LC_current_minitab"';
 9026:                 $visibility{$role} = ' style="display:block"';
 9027:             } else {
 9028:                 $visibility{$role} = ' style="display:none"';
 9029:             }
 9030:             $count ++;
 9031:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 9032:         }
 9033:         $r->print('</ul></div>');
 9034: 
 9035:         foreach my $role (@roles_by_num) {
 9036:             my %usecheck = (
 9037:                              all => ' checked="checked"',
 9038:                            );
 9039:             my %displaydiv = (
 9040:                                 status => 'none',
 9041:                                 inc    => 'none',
 9042:                                 exc    => 'none',
 9043:                                 priv   => 'block',
 9044:                              );
 9045:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 9046:             if (ref($settings{$role}) eq 'HASH') {
 9047:                 if ($settings{$role}{'access'} ne '') {
 9048:                     $indomvis = ' style="display:none"';
 9049:                     $incrsvis = ' style="display:block"';
 9050:                     $incrscheck = ' checked="checked"';
 9051:                     if ($settings{$role}{'access'} ne 'all') {
 9052:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 9053:                         delete($usecheck{'all'});
 9054:                         if ($settings{$role}{'access'} eq 'status') {
 9055:                             my $access = 'status';
 9056:                             $displaydiv{$access} = 'inline';
 9057:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9058:                                 $selected{$access} = $settings{$role}{$access};
 9059:                             }
 9060:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 9061:                             my $access = $1;
 9062:                             $displaydiv{$access} = 'inline';
 9063:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9064:                                 $selected{$access} = $settings{$role}{$access};
 9065:                             }
 9066:                         } elsif ($settings{$role}{'access'} eq 'none') {
 9067:                             $displaydiv{'priv'} = 'none';
 9068:                         }
 9069:                     }
 9070:                 } else {
 9071:                     $indomcheck = ' checked="checked"';
 9072:                     $indomvis = ' style="display:block"';
 9073:                     $incrsvis = ' style="display:none"';
 9074:                 }
 9075:             } else {
 9076:                 $indomcheck = ' checked="checked"';
 9077:                 $indomvis = ' style="display:block"';
 9078:                 $incrsvis = ' style="display:none"';
 9079:             }
 9080:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 9081:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 9082:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 9083:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9084:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 9085:                       '<span>'.('&nbsp;'x2).
 9086:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9087:                       $lt{'udd'}.'</label><span></p>'.
 9088:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 9089:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 9090:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 9091:             foreach my $access (@accesstypes) {
 9092:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 9093:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 9094:                 if ($access eq 'status') {
 9095:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 9096:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 9097:                                                                         $othertitle,$usertypes,$types,$disabled).
 9098:                               '</div>');
 9099:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 9100:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 9101:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9102:                                                                  \%domhelpdesk,$disabled).
 9103:                               '</div>');
 9104:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 9105:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 9106:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9107:                                                                  \%domhelpdesk,$disabled).
 9108:                               '</div>');
 9109:                 }
 9110:                 $r->print('</p>');
 9111:             }
 9112:             $r->print('</div></fieldset>');
 9113:             my %full=();
 9114:             my %levels= (
 9115:                          course => {},
 9116:                          domain => {},
 9117:                          system => {},
 9118:                         );
 9119:             my %levelscurrent=(
 9120:                                course => {},
 9121:                                domain => {},
 9122:                                system => {},
 9123:                               );
 9124:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9125:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 9126:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 9127:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 9128:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 9129:         }
 9130:         if ($permission->{'owner'}) {
 9131:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 9132:         }
 9133:     } else {
 9134:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 9135:     }
 9136:     # Form Footer
 9137:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 9138:              .'</form>');
 9139:     return;
 9140: }
 9141: 
 9142: sub print_queued_roles {
 9143:     my ($r,$context,$permission,$brcrum) = @_;
 9144:     push (@{$brcrum},
 9145:              {href => '/adm/createuser?action=rolerequests',
 9146:               text => 'Role Requests (other domains)',
 9147:               help => ''});
 9148:     my $bread_crumbs_component = 'Role Requests';
 9149:     my $args = { bread_crumbs           => $brcrum,
 9150:                  bread_crumbs_component => $bread_crumbs_component};
 9151:     # print page header
 9152:     $r->print(&header('',$args));
 9153:     my ($dom,$cnum);
 9154:     $dom = $env{'request.role.domain'};
 9155:     if ($context eq 'course') {
 9156:         if ($env{'request.course.id'}) {
 9157:             if (&Apache::loncommon::course_type() eq 'Community') {
 9158:                 $context = 'community';
 9159:             }
 9160:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9161:         }
 9162:     } elsif ($context eq 'author') {
 9163:         $cnum = $env{'user.name'};
 9164:     }
 9165:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomqueue',$dom,$cnum,$context));
 9166:     return;
 9167: }
 9168: 
 9169: sub print_pendingroles {
 9170:     my ($r,$context,$permission,$brcrum) = @_;
 9171:     push (@{$brcrum},
 9172:              {href => '/adm/createuser?action=queuedroles',
 9173:               text => 'Queued Role Assignments (users in this domain)',
 9174:               help => ''});
 9175:     my $bread_crumbs_component = 'Queued Role Assignments';
 9176:     my $args = { bread_crumbs           => $brcrum,
 9177:                  bread_crumbs_component => $bread_crumbs_component};
 9178:     # print page header
 9179:     $r->print(&header('',$args));
 9180:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomaction',$env{'request.role.domain'},'','domain'));
 9181:     return;
 9182: }
 9183: 
 9184: sub process_pendingroles {
 9185:     my ($r,$context,$permission,$brcrum) = @_;
 9186:     push (@{$brcrum},
 9187:              {href => '/adm/createuser?action=queuedroles',
 9188:               text => 'Queued Role Assignments (users in this domain)',
 9189:               help => ''},
 9190:              {href => '/adm/createuser?action=processrolereq',
 9191:               text => 'Process Queue',
 9192:               help => ''});
 9193:     my $bread_crumbs_component = 'Queued Role Assignments';
 9194:     my $args = { bread_crumbs           => $brcrum,
 9195:                  bread_crumbs_component => $bread_crumbs_component};
 9196:     # print page header
 9197:     $r->print(&header('',$args));
 9198:     $r->print(&Apache::loncoursequeueadmin::update_request_queue('othdombydc',
 9199:                                                                  $env{'request.role.domain'}));
 9200:     return;
 9201: }
 9202: 
 9203: sub domain_adhoc_access {
 9204:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 9205:     my %domusage;
 9206:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 9207:     foreach my $role (keys(%{$roles})) {
 9208:         if (ref($domcurrent->{$role}) eq 'HASH') {
 9209:             my $access = $domcurrent->{$role}{'access'};
 9210:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 9211:                 $access = 'all';
 9212:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 9213:                                                                                           &Apache::lonnet::plaintext('da'));
 9214:             } elsif ($access eq 'status') {
 9215:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 9216:                     my @shown;
 9217:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 9218:                         unless ($type eq 'default') {
 9219:                             if ($usertypes->{$type}) {
 9220:                                 push(@shown,$usertypes->{$type});
 9221:                             }
 9222:                         }
 9223:                     }
 9224:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 9225:                         push(@shown,$othertitle);
 9226:                     }
 9227:                     if (@shown) {
 9228:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 9229:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 9230:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 9231:                     } else {
 9232:                         $domusage{$role} = &mt('No one in the domain');
 9233:                     }
 9234:                 }
 9235:             } elsif ($access eq 'inc') {
 9236:                 my @dominc = ();
 9237:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 9238:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 9239:                         my ($uname,$udom) = split(/:/,$user);
 9240:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9241:                     }
 9242:                     my $showninc = join(', ',@dominc);
 9243:                     if ($showninc ne '') {
 9244:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 9245:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 9246:                     } else {
 9247:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9248:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9249:                     }
 9250:                 }
 9251:             } elsif ($access eq 'exc') {
 9252:                 my @domexc = ();
 9253:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 9254:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 9255:                         my ($uname,$udom) = split(/:/,$user);
 9256:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9257:                     }
 9258:                 }
 9259:                 my $shownexc = join(', ',@domexc);
 9260:                 if ($shownexc ne '') {
 9261:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 9262:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 9263:                 } else {
 9264:                     $domusage{$role} = &mt('No one in the domain');
 9265:                 }
 9266:             } elsif ($access eq 'none') {
 9267:                 $domusage{$role} = &mt('No one in the domain');
 9268:             } elsif ($access eq 'dh') {
 9269:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 9270:             } elsif ($access eq 'da') {
 9271:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 9272:             } elsif ($access eq 'all') {
 9273:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9274:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9275:             }
 9276:         } else {
 9277:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9278:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9279:         }
 9280:     }
 9281:     return %domusage;
 9282: }
 9283: 
 9284: sub get_domain_customroles {
 9285:     my ($cdom,$confname) = @_;
 9286:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 9287:     my %customroles;
 9288:     foreach my $key (keys(%existing)) {
 9289:         if ($key=~/^rolesdef\_(\w+)$/) {
 9290:             my $rolename = $1;
 9291:             my %privs;
 9292:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 9293:             $customroles{$rolename} = \%privs;
 9294:         }
 9295:     }
 9296:     return %customroles;
 9297: }
 9298: 
 9299: sub role_priv_table {
 9300:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 9301:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 9302:                    (ref($levelscurrent) eq 'HASH'));
 9303:     my %lt=&Apache::lonlocal::texthash (
 9304:                     'crl'  => 'Course Level Privilege',
 9305:                     'def'  => 'Domain Defaults',
 9306:                     'ove'  => 'Override in Course',
 9307:                     'ine'  => 'In effect',
 9308:                     'dis'  => 'Disabled',
 9309:                     'ena'  => 'Enabled',
 9310:                    );
 9311:     if ($crstype eq 'Community') {
 9312:         $lt{'ove'} = 'Override in Community',
 9313:     }
 9314:     my @status = ('Disabled','Enabled');
 9315:     my (%on,%off);
 9316:     if (ref($overridden) eq 'HASH') {
 9317:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 9318:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 9319:         }
 9320:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 9321:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 9322:         }
 9323:     }
 9324:     my $output=&Apache::loncommon::start_data_table().
 9325:                &Apache::loncommon::start_data_table_header_row().
 9326:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 9327:                '</th><th>'.$lt{'ine'}.'</th>'.
 9328:                &Apache::loncommon::end_data_table_header_row();
 9329:     foreach my $priv (sort(keys(%{$full}))) {
 9330:         next unless ($levels->{'course'}{$priv});
 9331:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 9332:         my ($default,$ineffect);
 9333:         if ($levelscurrent->{'course'}{$priv}) {
 9334:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9335:             $ineffect = $default;
 9336:         }
 9337:         my ($customstatus,$checked);
 9338:         $output .= &Apache::loncommon::start_data_table_row().
 9339:                    '<td>'.$privtext.'</td>'.
 9340:                    '<td>'.$default.'</td><td>';
 9341:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 9342:             if ($permission->{'owner'}) {
 9343:                 $checked = ' checked="checked"';
 9344:             }
 9345:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 9346:             $ineffect = $customstatus;
 9347:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 9348:             if ($permission->{'owner'}) {
 9349:                 $checked = ' checked="checked"';
 9350:             }
 9351:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9352:             $ineffect = $customstatus;
 9353:         }
 9354:         if ($permission->{'owner'}) {
 9355:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 9356:         } else {
 9357:             $output .= $customstatus;
 9358:         }
 9359:         $output .= '</td><td>'.$ineffect.'</td>'.
 9360:                    &Apache::loncommon::end_data_table_row();
 9361:     }
 9362:     $output .= &Apache::loncommon::end_data_table();
 9363:     return $output;
 9364: }
 9365: 
 9366: sub get_adhocrole_settings {
 9367:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 9368:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 9369:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 9370:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 9371:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 9372:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 9373:             $settings->{$role}{'access'} = $curraccess;
 9374:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 9375:                 my @status = split(/,/,$rest);
 9376:                 my @currstatus;
 9377:                 foreach my $type (@status) {
 9378:                     if ($type eq 'default') {
 9379:                         push(@currstatus,$type);
 9380:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9381:                         push(@currstatus,$type);
 9382:                     }
 9383:                 }
 9384:                 if (@currstatus) {
 9385:                     $settings->{$role}{$curraccess} = \@currstatus;
 9386:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 9387:                     my @personnel = split(/,/,$rest);
 9388:                     $settings->{$role}{$curraccess} = \@personnel;
 9389:                 }
 9390:             }
 9391:         }
 9392:     }
 9393:     foreach my $role (keys(%{$customroles})) {
 9394:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 9395:             my %currentprivs;
 9396:             if (ref($customroles->{$role}) eq 'HASH') {
 9397:                 if (exists($customroles->{$role}{'course'})) {
 9398:                     my %full=();
 9399:                     my %levels= (
 9400:                                   course => {},
 9401:                                   domain => {},
 9402:                                   system => {},
 9403:                                 );
 9404:                     my %levelscurrent=(
 9405:                                         course => {},
 9406:                                         domain => {},
 9407:                                         system => {},
 9408:                                       );
 9409:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 9410:                     %currentprivs = %{$levelscurrent{'course'}};
 9411:                 }
 9412:             }
 9413:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 9414:                 next if ($item eq '');
 9415:                 my ($rule,$rest) = split(/=/,$item);
 9416:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 9417:                 foreach my $priv (split(/:/,$rest)) {
 9418:                     if ($priv ne '') {
 9419:                         if ($rule eq 'off') {
 9420:                             push(@{$overridden->{$role}{'off'}},$priv);
 9421:                             if ($currentprivs{$priv}) {
 9422:                                 push(@{$settings->{$role}{'off'}},$priv);
 9423:                             }
 9424:                         } else {
 9425:                             push(@{$overridden->{$role}{'on'}},$priv);
 9426:                             unless ($currentprivs{$priv}) {
 9427:                                 push(@{$settings->{$role}{'on'}},$priv);
 9428:                             }
 9429:                         }
 9430:                     }
 9431:                 }
 9432:             }
 9433:         }
 9434:     }
 9435:     return;
 9436: }
 9437: 
 9438: sub update_helpdeskaccess {
 9439:     my ($r,$permission,$brcrum) = @_;
 9440:     my $helpitem = 'Course_Helpdesk_Access';
 9441:     push (@{$brcrum},
 9442:              {href => '/adm/createuser?action=helpdesk',
 9443:               text => 'Helpdesk Access',
 9444:               help => $helpitem},
 9445:              {href => '/adm/createuser?action=helpdesk',
 9446:               text => 'Result',
 9447:               help => $helpitem}
 9448:          );
 9449:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 9450:     my $args = { bread_crumbs           => $brcrum,
 9451:                  bread_crumbs_component => $bread_crumbs_component};
 9452: 
 9453:     # print page header
 9454:     $r->print(&header('',$args));
 9455:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 9456:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 9457:         return;
 9458:     }
 9459:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 9460:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9461:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9462:     my $confname = $cdom.'-domainconfig';
 9463:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 9464:     my $crstype = &Apache::loncommon::course_type();
 9465:     my %customroles = &get_domain_customroles($cdom,$confname);
 9466:     my (%settings,%overridden);
 9467:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 9468:                             $types,\%customroles,\%settings,\%overridden);
 9469:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 9470:     my (%changed,%storehash,@todelete);
 9471: 
 9472:     if (keys(%customroles)) {
 9473:         my (%newsettings,@incrs);
 9474:         foreach my $role (keys(%customroles)) {
 9475:             $newsettings{$role} = {
 9476:                                     access => '',
 9477:                                     status => '',
 9478:                                     exc    => '',
 9479:                                     inc    => '',
 9480:                                     on     => '',
 9481:                                     off    => '',
 9482:                                   };
 9483:             my %current;
 9484:             if (ref($settings{$role}) eq 'HASH') {
 9485:                 %current = %{$settings{$role}};
 9486:             }
 9487:             if (ref($overridden{$role}) eq 'HASH') {
 9488:                 $current{'overridden'} = $overridden{$role};
 9489:             }
 9490:             if ($env{'form.'.$role.'_incrs'}) {
 9491:                 my $access = $env{'form.'.$role.'_access'};
 9492:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 9493:                     push(@incrs,$role);
 9494:                     unless ($current{'access'} eq $access) {
 9495:                         $changed{$role}{'access'} = 1;
 9496:                         $storehash{'internal.adhoc.'.$role} = $access;
 9497:                     }
 9498:                     if ($access eq 'status') {
 9499:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 9500:                         my @stored;
 9501:                         my @shownstatus;
 9502:                         if (ref($types) eq 'ARRAY') {
 9503:                             foreach my $type (sort(@statuses)) {
 9504:                                 if ($type eq 'default') {
 9505:                                     push(@stored,$type);
 9506:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9507:                                     push(@stored,$type);
 9508:                                     push(@shownstatus,$usertypes->{$type});
 9509:                                 }
 9510:                             }
 9511:                             if (grep(/^default$/,@statuses)) {
 9512:                                 push(@shownstatus,$othertitle);
 9513:                             }
 9514:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9515:                         }
 9516:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 9517:                         if (ref($current{'status'}) eq 'ARRAY') {
 9518:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 9519:                             if (@diffs) {
 9520:                                 $changed{$role}{'status'} = 1;
 9521:                             }
 9522:                         } elsif (@stored) {
 9523:                             $changed{$role}{'status'} = 1;
 9524:                         }
 9525:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 9526:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 9527:                         my @newspecstaff;
 9528:                         my @stored;
 9529:                         my @currstaff;
 9530:                         foreach my $person (sort(@personnel)) {
 9531:                             if ($domhelpdesk{$person}) {
 9532:                                 push(@stored,$person);
 9533:                             }
 9534:                         }
 9535:                         if (ref($current{$access}) eq 'ARRAY') {
 9536:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 9537:                             if (@diffs) {
 9538:                                 $changed{$role}{$access} = 1;
 9539:                             }
 9540:                         } elsif (@stored) {
 9541:                             $changed{$role}{$access} = 1;
 9542:                         }
 9543:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9544:                         foreach my $person (@stored) {
 9545:                             my ($uname,$udom) = split(/:/,$person);
 9546:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 9547:                         }
 9548:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 9549:                     }
 9550:                     $newsettings{$role}{'access'} = $access;
 9551:                 }
 9552:             } else {
 9553:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 9554:                     $changed{$role}{'access'} = 1;
 9555:                     $newsettings{$role} = {};
 9556:                     push(@todelete,'internal.adhoc.'.$role);
 9557:                 }
 9558:             }
 9559:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 9560:                 if (ref($current{'overridden'}) eq 'HASH') {
 9561:                     push(@todelete,'internal.adhocpriv.'.$role);
 9562:                 }
 9563:             } else {
 9564:                 my %full=();
 9565:                 my %levels= (
 9566:                              course => {},
 9567:                              domain => {},
 9568:                              system => {},
 9569:                             );
 9570:                 my %levelscurrent=(
 9571:                                    course => {},
 9572:                                    domain => {},
 9573:                                    system => {},
 9574:                                   );
 9575:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9576:                 my (@updatedon,@updatedoff,@override);
 9577:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 9578:                 if (@override) {
 9579:                     foreach my $priv (sort(keys(%full))) {
 9580:                         next unless ($levels{'course'}{$priv});
 9581:                         if (grep(/^\Q$priv\E$/,@override)) {
 9582:                             if ($levelscurrent{'course'}{$priv}) {
 9583:                                 push(@updatedoff,$priv);
 9584:                             } else {
 9585:                                 push(@updatedon,$priv);
 9586:                             }
 9587:                         }
 9588:                     }
 9589:                 }
 9590:                 if (@updatedon) {
 9591:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 9592:                 }
 9593:                 if (@updatedoff) {
 9594:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 9595:                 }
 9596:                 if (ref($current{'overridden'}) eq 'HASH') {
 9597:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 9598:                         if (@updatedon) {
 9599:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 9600:                             if (@diffs) {
 9601:                                 $changed{$role}{'on'} = 1;
 9602:                             }
 9603:                         } else {
 9604:                             $changed{$role}{'on'} = 1;
 9605:                         }
 9606:                     } elsif (@updatedon) {
 9607:                         $changed{$role}{'on'} = 1;
 9608:                     }
 9609:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 9610:                         if (@updatedoff) {
 9611:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 9612:                             if (@diffs) {
 9613:                                 $changed{$role}{'off'} = 1;
 9614:                             }
 9615:                         } else {
 9616:                             $changed{$role}{'off'} = 1;
 9617:                         }
 9618:                     } elsif (@updatedoff) {
 9619:                         $changed{$role}{'off'} = 1;
 9620:                     }
 9621:                 } else {
 9622:                     if (@updatedon) {
 9623:                         $changed{$role}{'on'} = 1;
 9624:                     }
 9625:                     if (@updatedoff) {
 9626:                         $changed{$role}{'off'} = 1;
 9627:                     }
 9628:                 }
 9629:                 if (ref($changed{$role}) eq 'HASH') {
 9630:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 9631:                         my $newpriv;
 9632:                         if (@updatedon) {
 9633:                             $newpriv = 'on='.join(':',@updatedon);
 9634:                         }
 9635:                         if (@updatedoff) {
 9636:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 9637:                         }
 9638:                         if ($newpriv eq '') {
 9639:                             push(@todelete,'internal.adhocpriv.'.$role);
 9640:                         } else {
 9641:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 9642:                         }
 9643:                     }
 9644:                 }
 9645:             }
 9646:         }
 9647:         if (@incrs) {
 9648:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 9649:         } elsif (@todelete) {
 9650:             push(@todelete,'internal.adhocaccess');
 9651:         }
 9652:         if (keys(%changed)) {
 9653:             my ($putres,$delres);
 9654:             if (keys(%storehash)) {
 9655:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 9656:                 my %newenvhash;
 9657:                 foreach my $key (keys(%storehash)) {
 9658:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 9659:                 }
 9660:                 &Apache::lonnet::appenv(\%newenvhash);
 9661:             }
 9662:             if (@todelete) {
 9663:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 9664:                 foreach my $key (@todelete) {
 9665:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 9666:                 }
 9667:             }
 9668:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 9669:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9670:                 my (%domcurrent,%ordered,%description,%domusage);
 9671:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9672:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9673:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9674:                     }
 9675:                 }
 9676:                 my $count = 0;
 9677:                 foreach my $role (sort(keys(%customroles))) {
 9678:                     my ($order,$desc);
 9679:                     if (ref($domcurrent{$role}) eq 'HASH') {
 9680:                         $order = $domcurrent{$role}{'order'};
 9681:                         $desc = $domcurrent{$role}{'desc'};
 9682:                     }
 9683:                     if ($order eq '') {
 9684:                         $order = $count;
 9685:                     }
 9686:                     $ordered{$order} = $role;
 9687:                     if ($desc ne '') {
 9688:                         $description{$role} = $desc;
 9689:                     } else {
 9690:                         $description{$role}= $role;
 9691:                     }
 9692:                     $count++;
 9693:                 }
 9694:                 my @roles_by_num = ();
 9695:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9696:                     push(@roles_by_num,$ordered{$item});
 9697:                 }
 9698:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9699:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 9700:                 $r->print('<ul>');
 9701:                 foreach my $role (@roles_by_num) {
 9702:                     next unless (ref($changed{$role}) eq 'HASH');
 9703:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 9704:                               '<ul>');
 9705:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 9706:                         $r->print('<li>');
 9707:                         if ($env{'form.'.$role.'_incrs'}) {
 9708:                             if ($newsettings{$role}{'access'} eq 'all') {
 9709:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 9710:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 9711:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9712:                                               &Apache::lonnet::plaintext('dh')));
 9713:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 9714:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9715:                                               &Apache::lonnet::plaintext('da')));
 9716:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 9717:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9718:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 9719:                                 if ($newsettings{$role}{'status'}) {
 9720:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 9721:                                     if (split(/,/,$rest) > 1) {
 9722:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 9723:                                                       $newsettings{$role}{'status'}));
 9724:                                     } else {
 9725:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 9726:                                                       $newsettings{$role}{'status'}));
 9727:                                     }
 9728:                                 } else {
 9729:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9730:                                 }
 9731:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 9732:                                 if ($newsettings{$role}{'exc'}) {
 9733:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 9734:                                 } else {
 9735:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9736:                                 }
 9737:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 9738:                                 if ($newsettings{$role}{'inc'}) {
 9739:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 9740:                                 } else {
 9741:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 9742:                                 }
 9743:                             }
 9744:                         } else {
 9745:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 9746:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 9747:                         }
 9748:                         $r->print('</li>');
 9749:                     }
 9750:                     unless ($newsettings{$role}{'access'} eq 'none') {
 9751:                         if ($changed{$role}{'off'}) {
 9752:                             if ($newsettings{$role}{'off'}) {
 9753:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 9754:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 9755:                             } else {
 9756:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 9757:                             }
 9758:                         }
 9759:                         if ($changed{$role}{'on'}) {
 9760:                             if ($newsettings{$role}{'on'}) {
 9761:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 9762:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 9763:                             } else {
 9764:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 9765:                             }
 9766:                         }
 9767:                     }
 9768:                     $r->print('</ul></li>');
 9769:                 }
 9770:                 $r->print('</ul>');
 9771:             }
 9772:         } else {
 9773:             $r->print(&mt('No changes made to helpdesk access settings.'));
 9774:         }
 9775:     }
 9776:     return;
 9777: }
 9778: 
 9779: #-------------------------------------------------- functions for &phase_two
 9780: sub user_search_result {
 9781:     my ($context,$srch) = @_;
 9782:     my %allhomes;
 9783:     my %inst_matches;
 9784:     my %srch_results;
 9785:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 9786:     $srch->{'srchterm'} =~ s/\s+/ /g;
 9787:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 9788:         $response = &mt('Invalid search.');
 9789:     }
 9790:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 9791:         $response = &mt('Invalid search.');
 9792:     }
 9793:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 9794:         $response = &mt('Invalid search.');
 9795:     }
 9796:     if ($srch->{'srchterm'} eq '') {
 9797:         $response = &mt('You must enter a search term.');
 9798:     }
 9799:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 9800:         $response = &mt('Your search term must contain more than just spaces.');
 9801:     }
 9802:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 9803:         if (($srch->{'srchdomain'} eq '') || 
 9804: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 9805:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 9806:         }
 9807:     }
 9808:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 9809:         ($srch->{'srchin'} eq 'alc')) {
 9810:         if ($srch->{'srchby'} eq 'uname') {
 9811:             my $unamecheck = $srch->{'srchterm'};
 9812:             if ($srch->{'srchtype'} eq 'contains') {
 9813:                 if ($unamecheck !~ /^\w/) {
 9814:                     $unamecheck = 'a'.$unamecheck; 
 9815:                 }
 9816:             }
 9817:             if ($unamecheck !~ /^$match_username$/) {
 9818:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 9819:             }
 9820:         }
 9821:     }
 9822:     if ($response ne '') {
 9823:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 9824:     }
 9825:     if ($srch->{'srchin'} eq 'instd') {
 9826:         my $instd_chk = &instdirectorysrch_check($srch);
 9827:         if ($instd_chk ne 'ok') {
 9828:             my $domd_chk = &domdirectorysrch_check($srch);
 9829:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 9830:             if ($domd_chk eq 'ok') {
 9831:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 9832:             }
 9833:             $response .= '<br />';
 9834:         }
 9835:     } else {
 9836:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 9837:             my $domd_chk = &domdirectorysrch_check($srch);
 9838:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 9839:                 my $instd_chk = &instdirectorysrch_check($srch);
 9840:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 9841:                 if ($instd_chk eq 'ok') {
 9842:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 9843:                 }
 9844:                 $response .= '<br />';
 9845:             }
 9846:         }
 9847:     }
 9848:     if ($response ne '') {
 9849:         return ($currstate,$response);
 9850:     }
 9851:     if ($srch->{'srchby'} eq 'uname') {
 9852:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 9853:             if ($env{'form.forcenew'}) {
 9854:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 9855:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9856:                     if ($uhome eq 'no_host') {
 9857:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 9858:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 9859:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 9860:                     } else {
 9861:                         $currstate = 'modify';
 9862:                     }
 9863:                 } else {
 9864:                     $currstate = 'modify';
 9865:                 }
 9866:             } else {
 9867:                 if ($srch->{'srchin'} eq 'dom') {
 9868:                     if ($srch->{'srchtype'} eq 'exact') {
 9869:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9870:                         if ($uhome eq 'no_host') {
 9871:                             ($currstate,$response,$forcenewuser) =
 9872:                                 &build_search_response($context,$srch,%srch_results);
 9873:                         } else {
 9874:                             $currstate = 'modify';
 9875:                             if ($env{'form.action'} eq 'accesslogs') {
 9876:                                 $currstate = 'activity';
 9877:                             }
 9878:                             my $uname = $srch->{'srchterm'};
 9879:                             my $udom = $srch->{'srchdomain'};
 9880:                             $srch_results{$uname.':'.$udom} =
 9881:                                 { &Apache::lonnet::get('environment',
 9882:                                                        ['firstname',
 9883:                                                         'lastname',
 9884:                                                         'permanentemail'],
 9885:                                                          $udom,$uname)
 9886:                                 };
 9887:                         }
 9888:                     } else {
 9889:                         %srch_results = &Apache::lonnet::usersearch($srch);
 9890:                         ($currstate,$response,$forcenewuser) =
 9891:                             &build_search_response($context,$srch,%srch_results);
 9892:                     }
 9893:                 } else {
 9894:                     my $courseusers = &get_courseusers();
 9895:                     if ($srch->{'srchtype'} eq 'exact') {
 9896:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 9897:                             $currstate = 'modify';
 9898:                         } else {
 9899:                             ($currstate,$response,$forcenewuser) =
 9900:                                 &build_search_response($context,$srch,%srch_results);
 9901:                         }
 9902:                     } else {
 9903:                         foreach my $user (keys(%$courseusers)) {
 9904:                             my ($cuname,$cudomain) = split(/:/,$user);
 9905:                             if ($cudomain eq $srch->{'srchdomain'}) {
 9906:                                 my $matched = 0;
 9907:                                 if ($srch->{'srchtype'} eq 'begins') {
 9908:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 9909:                                         $matched = 1;
 9910:                                     }
 9911:                                 } else {
 9912:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 9913:                                         $matched = 1;
 9914:                                     }
 9915:                                 }
 9916:                                 if ($matched) {
 9917:                                     $srch_results{$user} = 
 9918: 					{&Apache::lonnet::get('environment',
 9919: 							     ['firstname',
 9920: 							      'lastname',
 9921: 							      'permanentemail'],
 9922: 							      $cudomain,$cuname)};
 9923:                                 }
 9924:                             }
 9925:                         }
 9926:                         ($currstate,$response,$forcenewuser) =
 9927:                             &build_search_response($context,$srch,%srch_results);
 9928:                     }
 9929:                 }
 9930:             }
 9931:         } elsif ($srch->{'srchin'} eq 'alc') {
 9932:             $currstate = 'query';
 9933:         } elsif ($srch->{'srchin'} eq 'instd') {
 9934:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 9935:             if ($dirsrchres eq 'ok') {
 9936:                 ($currstate,$response,$forcenewuser) = 
 9937:                     &build_search_response($context,$srch,%srch_results);
 9938:             } else {
 9939:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9940:                 $response = '<span class="LC_warning">'.
 9941:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9942:                     '</span><br />'.
 9943:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 9944:                     '<br />'; 
 9945:             }
 9946:         }
 9947:     } else {
 9948:         if ($srch->{'srchin'} eq 'dom') {
 9949:             %srch_results = &Apache::lonnet::usersearch($srch);
 9950:             ($currstate,$response,$forcenewuser) = 
 9951:                 &build_search_response($context,$srch,%srch_results); 
 9952:         } elsif ($srch->{'srchin'} eq 'crs') {
 9953:             my $courseusers = &get_courseusers(); 
 9954:             foreach my $user (keys(%$courseusers)) {
 9955:                 my ($uname,$udom) = split(/:/,$user);
 9956:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 9957:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 9958:                 if ($srch->{'srchby'} eq 'lastname') {
 9959:                     if ((($srch->{'srchtype'} eq 'exact') && 
 9960:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 9961:                         (($srch->{'srchtype'} eq 'begins') &&
 9962:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 9963:                         (($srch->{'srchtype'} eq 'contains') &&
 9964:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 9965:                         $srch_results{$user} = {firstname => $names{'firstname'},
 9966:                                             lastname => $names{'lastname'},
 9967:                                             permanentemail => $emails{'permanentemail'},
 9968:                                            };
 9969:                     }
 9970:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 9971:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 9972:                     $srchlast =~ s/\s+$//;
 9973:                     $srchfirst =~ s/^\s+//;
 9974:                     if ($srch->{'srchtype'} eq 'exact') {
 9975:                         if (($names{'lastname'} eq $srchlast) &&
 9976:                             ($names{'firstname'} eq $srchfirst)) {
 9977:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9978:                                                 lastname => $names{'lastname'},
 9979:                                                 permanentemail => $emails{'permanentemail'},
 9980: 
 9981:                                            };
 9982:                         }
 9983:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 9984:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 9985:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 9986:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9987:                                                 lastname => $names{'lastname'},
 9988:                                                 permanentemail => $emails{'permanentemail'},
 9989:                                                };
 9990:                         }
 9991:                     } else {
 9992:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 9993:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 9994:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9995:                                                 lastname => $names{'lastname'},
 9996:                                                 permanentemail => $emails{'permanentemail'},
 9997:                                                };
 9998:                         }
 9999:                     }
10000:                 }
10001:             }
10002:             ($currstate,$response,$forcenewuser) = 
10003:                 &build_search_response($context,$srch,%srch_results); 
10004:         } elsif ($srch->{'srchin'} eq 'alc') {
10005:             $currstate = 'query';
10006:         } elsif ($srch->{'srchin'} eq 'instd') {
10007:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
10008:             if ($dirsrchres eq 'ok') {
10009:                 ($currstate,$response,$forcenewuser) = 
10010:                     &build_search_response($context,$srch,%srch_results);
10011:             } else {
10012:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
10013:                 $response = '<span class="LC_warning">'.
10014:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
10015:                     '</span><br />'.
10016:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
10017:                     '<br />';
10018:             }
10019:         }
10020:     }
10021:     return ($currstate,$response,$forcenewuser,\%srch_results);
10022: }
10023: 
10024: sub domdirectorysrch_check {
10025:     my ($srch) = @_;
10026:     my $response;
10027:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10028:                                              ['directorysrch'],$srch->{'srchdomain'});
10029:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10030:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10031:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
10032:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
10033:         }
10034:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
10035:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10036:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
10037:             }
10038:         }
10039:     }
10040:     return 'ok';
10041: }
10042: 
10043: sub instdirectorysrch_check {
10044:     my ($srch) = @_;
10045:     my $can_search = 0;
10046:     my $response;
10047:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10048:                                              ['directorysrch'],$srch->{'srchdomain'});
10049:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10050:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10051:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
10052:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
10053:         }
10054:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
10055:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10056:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
10057:             }
10058:             my @usertypes = split(/:/,$env{'environment.inststatus'});
10059:             if (!@usertypes) {
10060:                 push(@usertypes,'default');
10061:             }
10062:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
10063:                 foreach my $type (@usertypes) {
10064:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
10065:                         $can_search = 1;
10066:                         last;
10067:                     }
10068:                 }
10069:             }
10070:             if (!$can_search) {
10071:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
10072:                 my @longtypes; 
10073:                 foreach my $item (@usertypes) {
10074:                     if (defined($insttypes->{$item})) { 
10075:                         push (@longtypes,$insttypes->{$item});
10076:                     } elsif ($item eq 'default') {
10077:                         push (@longtypes,&mt('other')); 
10078:                     }
10079:                 }
10080:                 my $insttype_str = join(', ',@longtypes); 
10081:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
10082:             }
10083:         } else {
10084:             $can_search = 1;
10085:         }
10086:     } else {
10087:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
10088:     }
10089:     my %longtext = &Apache::lonlocal::texthash (
10090:                        uname     => 'username',
10091:                        lastfirst => 'last name, first name',
10092:                        lastname  => 'last name',
10093:                        contains  => 'contains',
10094:                        exact     => 'as exact match to',
10095:                        begins    => 'begins with',
10096:                    );
10097:     if ($can_search) {
10098:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
10099:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
10100:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
10101:             }
10102:         } else {
10103:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
10104:         }
10105:     }
10106:     if ($can_search) {
10107:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
10108:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
10109:                 return 'ok';
10110:             } else {
10111:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10112:             }
10113:         } else {
10114:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
10115:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
10116:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
10117:                 return 'ok';
10118:             } else {
10119:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10120:             }
10121:         }
10122:     }
10123: }
10124: 
10125: sub get_courseusers {
10126:     my %advhash;
10127:     my $classlist = &Apache::loncoursedata::get_classlist();
10128:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
10129:     foreach my $role (sort(keys(%coursepersonnel))) {
10130:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
10131: 	    if (!exists($classlist->{$user})) {
10132: 		$classlist->{$user} = [];
10133: 	    }
10134:         }
10135:     }
10136:     return $classlist;
10137: }
10138: 
10139: sub build_search_response {
10140:     my ($context,$srch,%srch_results) = @_;
10141:     my ($currstate,$response,$forcenewuser);
10142:     my %names = (
10143:           'uname'     => 'username',
10144:           'lastname'  => 'last name',
10145:           'lastfirst' => 'last name, first name',
10146:           'crs'       => 'this course',
10147:           'dom'       => 'LON-CAPA domain',
10148:           'instd'     => 'the institutional directory for domain',
10149:     );
10150: 
10151:     my %single = (
10152:                    begins   => 'A match',
10153:                    contains => 'A match',
10154:                    exact    => 'An exact match',
10155:                  );
10156:     my %nomatch = (
10157:                    begins   => 'No match',
10158:                    contains => 'No match',
10159:                    exact    => 'No exact match',
10160:                   );
10161:     if (keys(%srch_results) > 1) {
10162:         $currstate = 'select';
10163:     } else {
10164:         if (keys(%srch_results) == 1) {
10165:             if ($env{'form.action'} eq 'accesslogs') {
10166:                 $currstate = 'activity';
10167:             } else {
10168:                 $currstate = 'modify';
10169:             }
10170:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
10171:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10172:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
10173:             }
10174:         } else { # Search has nothing found. Prepare message to user.
10175:             $response = '<span class="LC_warning">';
10176:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10177:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
10178:                                  '<b>'.$srch->{'srchterm'}.'</b>',
10179:                                  &display_domain_info($srch->{'srchdomain'}));
10180:             } else {
10181:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
10182:                                  '<b>'.$srch->{'srchterm'}.'</b>');
10183:             }
10184:             $response .= '</span>';
10185: 
10186:             if ($srch->{'srchin'} ne 'alc') {
10187:                 $forcenewuser = 1;
10188:                 my $cansrchinst = 0; 
10189:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
10190:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
10191:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
10192:                         if ($domconfig{'directorysrch'}{'available'}) {
10193:                             $cansrchinst = 1;
10194:                         } 
10195:                     }
10196:                 }
10197:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
10198:                      ($srch->{'srchby'} eq 'lastname')) &&
10199:                     ($srch->{'srchin'} eq 'dom')) {
10200:                     if ($cansrchinst) {
10201:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
10202:                     }
10203:                 }
10204:                 if ($srch->{'srchin'} eq 'crs') {
10205:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
10206:                 }
10207:             }
10208:             my $createdom = $env{'request.role.domain'};
10209:             if ($context eq 'requestcrs') {
10210:                 if ($env{'form.coursedom'} ne '') {
10211:                     $createdom = $env{'form.coursedom'};
10212:                 }
10213:             }
10214:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
10215:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
10216:                 my $cancreate =
10217:                     &Apache::lonuserutils::can_create_user($createdom,$context);
10218:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
10219:                 if ($cancreate) {
10220:                     my $showdom = &display_domain_info($createdom); 
10221:                     $response .= '<br /><br />'
10222:                                 .'<b>'.&mt('To add a new user:').'</b>'
10223:                                 .'<br />';
10224:                     if ($context eq 'requestcrs') {
10225:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
10226:                     } else {
10227:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
10228:                     }
10229:                     $response .='<ul><li>'
10230:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
10231:                                 .'</li><li>'
10232:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
10233:                                 .'</li><li>'
10234:                                 .&mt('Provide the proposed username')
10235:                                 .'</li><li>'
10236:                                 .&mt("Click 'Search'")
10237:                                 .'</li></ul><br />';
10238:                 } else {
10239:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
10240:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
10241:                         $response .= '<br /><br />';
10242:                         if ($context eq 'requestcrs') {
10243:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
10244:                         } else {
10245:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
10246:                         }
10247:                         $response .= '<br />'
10248:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
10249:                                         ,' <a'.$helplink.'>'
10250:                                         ,'</a>')
10251:                                      .'<br />';
10252:                     }
10253:                 }
10254:             }
10255:         }
10256:     }
10257:     return ($currstate,$response,$forcenewuser);
10258: }
10259: 
10260: sub display_domain_info {
10261:     my ($dom) = @_;
10262:     my $output = $dom;
10263:     if ($dom ne '') { 
10264:         my $domdesc = &Apache::lonnet::domain($dom,'description');
10265:         if ($domdesc ne '') {
10266:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
10267:         }
10268:     }
10269:     return $output;
10270: }
10271: 
10272: sub crumb_utilities {
10273:     my %elements = (
10274:        crtuser => {
10275:            srchterm => 'text',
10276:            srchin => 'selectbox',
10277:            srchby => 'selectbox',
10278:            srchtype => 'selectbox',
10279:            srchdomain => 'selectbox',
10280:        },
10281:        crtusername => {
10282:            srchterm => 'text',
10283:            srchdomain => 'selectbox',
10284:        },
10285:        docustom => {
10286:            rolename => 'selectbox',
10287:            newrolename => 'textbox',
10288:        },
10289:        studentform => {
10290:            srchterm => 'text',
10291:            srchin => 'selectbox',
10292:            srchby => 'selectbox',
10293:            srchtype => 'selectbox',
10294:            srchdomain => 'selectbox',
10295:        },
10296:     );
10297: 
10298:     my $jsback .= qq|
10299: function backPage(formname,prevphase,prevstate) {
10300:     if (typeof prevphase == 'undefined') {
10301:         formname.phase.value = '';
10302:     }
10303:     else {  
10304:         formname.phase.value = prevphase;
10305:     }
10306:     if (typeof prevstate == 'undefined') {
10307:         formname.currstate.value = '';
10308:     }
10309:     else {
10310:         formname.currstate.value = prevstate;
10311:     }
10312:     formname.submit();
10313: }
10314: |;
10315:     return ($jsback,\%elements);
10316: }
10317: 
10318: sub course_level_table {
10319:     my ($inccourses,$showcredits,$defaultcredits) = @_;
10320:     return unless (ref($inccourses) eq 'HASH');
10321:     my $table = '';
10322: # Custom Roles?
10323: 
10324:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10325:     my %lt=&Apache::lonlocal::texthash(
10326:             'exs'  => "Existing sections",
10327:             'new'  => "Define new section",
10328:             'ssd'  => "Set Start Date",
10329:             'sed'  => "Set End Date",
10330:             'crl'  => "Course Level",
10331:             'act'  => "Activate",
10332:             'rol'  => "Role",
10333:             'ext'  => "Extent",
10334:             'grs'  => "Section",
10335:             'crd'  => "Credits",
10336:             'sta'  => "Start",
10337:             'end'  => "End"
10338:     );
10339: 
10340:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
10341: 	my $thiscourse=$protectedcourse;
10342: 	$thiscourse=~s:_:/:g;
10343: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
10344:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
10345: 	my $area=$coursedata{'description'};
10346:         my $crstype=$coursedata{'type'};
10347: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
10348: 	my ($domain,$cnum)=split(/\//,$thiscourse);
10349:         my %sections_count;
10350:         if (defined($env{'request.course.id'})) {
10351:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
10352:                 %sections_count = 
10353: 		    &Apache::loncommon::get_sections($domain,$cnum);
10354:             }
10355:         }
10356:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
10357: 	foreach my $role (@roles) {
10358:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
10359: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
10360:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
10361:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10362:                                             $plrole,\%sections_count,\%lt,
10363:                                             $showcredits,$defaultcredits,$crstype);
10364:             } elsif ($env{'request.course.sec'} ne '') {
10365:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
10366:                                              $env{'request.course.sec'})) {
10367:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10368:                                                 $plrole,\%sections_count,\%lt,
10369:                                                 $showcredits,$defaultcredits,$crstype);
10370:                 }
10371:             }
10372:         }
10373:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
10374:             foreach my $cust (sort(keys(%customroles))) {
10375:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
10376:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
10377:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10378:                                             $cust,\%sections_count,\%lt,
10379:                                             $showcredits,$defaultcredits,$crstype);
10380:             }
10381: 	}
10382:     }
10383:     return '' if ($table eq ''); # return nothing if there is nothing 
10384:                                  # in the table
10385:     my $result;
10386:     if (!$env{'request.course.id'}) {
10387:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
10388:     }
10389:     $result .= 
10390: &Apache::loncommon::start_data_table().
10391: &Apache::loncommon::start_data_table_header_row().
10392: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10393: '<th>'.$lt{'ext'}.'</th><th>'."\n";
10394:     if ($showcredits) {
10395:         $result .= $lt{'crd'}.'</th>';
10396:     }
10397:     $result .=
10398: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
10399: '<th>'.$lt{'end'}.'</th>'.
10400: &Apache::loncommon::end_data_table_header_row().
10401: $table.
10402: &Apache::loncommon::end_data_table();
10403:     return $result;
10404: }
10405: 
10406: sub course_level_row {
10407:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
10408:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
10409:     my $creditem;
10410:     my $row = &Apache::loncommon::start_data_table_row().
10411:               ' <td><input type="checkbox" name="act_'.
10412:               $protectedcourse.'_'.$role.'" /></td>'."\n".
10413:               ' <td>'.$plrole.'</td>'."\n".
10414:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
10415:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
10416:         $row .= 
10417:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
10418:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
10419:     } else {
10420:         $row .= '<td>&nbsp;</td>';
10421:     }
10422:     if (($role eq 'cc') || ($role eq 'co')) {
10423:         $row .= '<td>&nbsp;</td>';
10424:     } elsif ($env{'request.course.sec'} ne '') {
10425:         $row .= ' <td><input type="hidden" value="'.
10426:                 $env{'request.course.sec'}.'" '.
10427:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
10428:                 $env{'request.course.sec'}.'</td>';
10429:     } else {
10430:         if (ref($sections_count) eq 'HASH') {
10431:             my $currsec = 
10432:                 &Apache::lonuserutils::course_sections($sections_count,
10433:                                                        $protectedcourse.'_'.$role);
10434:             $row .= '<td><table class="LC_createuser">'."\n".
10435:                     '<tr class="LC_section_row">'."\n".
10436:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
10437:                        $currsec.'</td>'."\n".
10438:                      ' <td>&nbsp;&nbsp;</td>'."\n".
10439:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
10440:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
10441:                      '" value="" />'.
10442:                      '<input type="hidden" '.
10443:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
10444:                      '</tr></table></td>'."\n";
10445:         } else {
10446:             $row .= '<td><input type="text" size="10" '.
10447:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
10448:         }
10449:     }
10450:     $row .= <<ENDTIMEENTRY;
10451: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
10452: <a href=
10453: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
10454: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
10455: <a href=
10456: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
10457: ENDTIMEENTRY
10458:     $row .= &Apache::loncommon::end_data_table_row();
10459:     return $row;
10460: }
10461: 
10462: sub course_level_dc {
10463:     my ($dcdom,$showcredits) = @_;
10464:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10465:     my @roles = &Apache::lonuserutils::roles_by_context('course');
10466:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
10467:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
10468:                       '<input type="hidden" name="dccourse" value="" />';
10469:     my $courseform=&Apache::loncommon::selectcourse_link
10470:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
10471:     my $credit_elem;
10472:     if ($showcredits) {
10473:         $credit_elem = 'credits';
10474:     }
10475:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
10476:     my %lt=&Apache::lonlocal::texthash(
10477:                     'rol'  => "Role",
10478:                     'grs'  => "Section",
10479:                     'exs'  => "Existing sections",
10480:                     'new'  => "Define new section", 
10481:                     'sta'  => "Start",
10482:                     'end'  => "End",
10483:                     'ssd'  => "Set Start Date",
10484:                     'sed'  => "Set End Date",
10485:                     'scc'  => "Course/Community",
10486:                     'crd'  => "Credits",
10487:                   );
10488:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
10489:                  &Apache::loncommon::start_data_table().
10490:                  &Apache::loncommon::start_data_table_header_row().
10491:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10492:                  '<th>'.$lt{'grs'}.'</th>'."\n";
10493:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
10494:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
10495:                  &Apache::loncommon::end_data_table_header_row();
10496:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
10497:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
10498:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
10499:                      '<td valign="top"><br /><select name="role">'."\n";
10500:     foreach my $role (@roles) {
10501:         my $plrole=&Apache::lonnet::plaintext($role);
10502:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
10503:     }
10504:     if ( keys(%customroles) > 0) {
10505:         foreach my $cust (sort(keys(%customroles))) {
10506:             my $custrole='cr_cr_'.$env{'user.domain'}.
10507:                     '_'.$env{'user.name'}.'_'.$cust;
10508:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
10509:         }
10510:     }
10511:     $otheritems .= '</select></td><td>'.
10512:                      '<table border="0" cellspacing="0" cellpadding="0">'.
10513:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
10514:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
10515:                      '<td>&nbsp;&nbsp;</td>'.
10516:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
10517:                      '<input type="text" name="newsec" value="" />'.
10518:                      '<input type="hidden" name="section" value="" />'.
10519:                      '<input type="hidden" name="groups" value="" />'.
10520:                      '<input type="hidden" name="crstype" value="" /></td>'.
10521:                      '</tr></table></td>'."\n";
10522:     if ($showcredits) {
10523:         $otheritems .= '<td><br />'."\n".
10524:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
10525:     }
10526:     $otheritems .= <<ENDTIMEENTRY;
10527: <td><br /><input type="hidden" name="start" value='' />
10528: <a href=
10529: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
10530: <td><br /><input type="hidden" name="end" value='' />
10531: <a href=
10532: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
10533: ENDTIMEENTRY
10534:     $otheritems .= &Apache::loncommon::end_data_table_row().
10535:                    &Apache::loncommon::end_data_table()."\n";
10536:     return $cb_jscript.$hiddenitems.$header.$otheritems;
10537: }
10538: 
10539: sub update_selfenroll_config {
10540:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
10541:     return unless (ref($currsettings) eq 'HASH');
10542:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
10543:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10544:     my (%changes,%warning);
10545:     my $curr_types;
10546:     my %noedit;
10547:     unless ($context eq 'domain') {
10548:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
10549:     }
10550:     if (ref($row) eq 'ARRAY') {
10551:         foreach my $item (@{$row}) {
10552:             next if ($noedit{$item});
10553:             if ($item eq 'enroll_dates') {
10554:                 my (%currenrolldate,%newenrolldate);
10555:                 foreach my $type ('start','end') {
10556:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
10557:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
10558:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
10559:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
10560:                     }
10561:                 }
10562:             } elsif ($item eq 'access_dates') {
10563:                 my (%currdate,%newdate);
10564:                 foreach my $type ('start','end') {
10565:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
10566:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
10567:                     if ($newdate{$type} ne $currdate{$type}) {
10568:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
10569:                     }
10570:                 }
10571:             } elsif ($item eq 'types') {
10572:                 $curr_types = $currsettings->{'selfenroll_'.$item};
10573:                 if ($env{'form.selfenroll_all'}) {
10574:                     if ($curr_types ne '*') {
10575:                         $changes{'internal.selfenroll_types'} = '*';
10576:                     } else {
10577:                         next;
10578:                     }
10579:                 } else {
10580:                     my %currdoms;
10581:                     my @entries = split(/;/,$curr_types);
10582:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
10583:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
10584:                     my $newnum = 0;
10585:                     my @latesttypes;
10586:                     foreach my $num (@activations) {
10587:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
10588:                         if (@types > 0) {
10589:                             @types = sort(@types);
10590:                             my $typestr = join(',',@types);
10591:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
10592:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10593:                             $currdoms{$typedom} = 1;
10594:                             $newnum ++;
10595:                         }
10596:                     }
10597:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
10598:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
10599:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
10600:                             if (@types > 0) {
10601:                                 @types = sort(@types);
10602:                                 my $typestr = join(',',@types);
10603:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
10604:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
10605:                                 $currdoms{$typedom} = 1;
10606:                                 $newnum ++;
10607:                             }
10608:                         }
10609:                     }
10610:                     if ($env{'form.selfenroll_newdom'} ne '') {
10611:                         my $typedom = $env{'form.selfenroll_newdom'};
10612:                         if ((!defined($currdoms{$typedom})) && 
10613:                             (&Apache::lonnet::domain($typedom) ne '')) {
10614:                             my $typestr;
10615:                             my ($othertitle,$usertypes,$types) = 
10616:                                 &Apache::loncommon::sorted_inst_types($typedom);
10617:                             my $othervalue = 'any';
10618:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
10619:                                 if (@{$types} > 0) {
10620:                                     my @esc_types = map { &escape($_); } @{$types};
10621:                                     $othervalue = 'other';
10622:                                     $typestr = join(',',(@esc_types,$othervalue));
10623:                                 }
10624:                                 $typestr = $othervalue;
10625:                             } else {
10626:                                 $typestr = $othervalue;
10627:                             } 
10628:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10629:                             $newnum ++ ;
10630:                         }
10631:                     }
10632:                     my $selfenroll_types = join(';',@latesttypes);
10633:                     if ($selfenroll_types ne $curr_types) {
10634:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
10635:                     }
10636:                 }
10637:             } elsif ($item eq 'limit') {
10638:                 my $newlimit = $env{'form.selfenroll_limit'};
10639:                 my $newcap = $env{'form.selfenroll_cap'};
10640:                 $newcap =~s/\s+//g;
10641:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10642:                 $currlimit = 'none' if ($currlimit eq '');
10643:                 my $currcap = $currsettings->{'selfenroll_cap'};
10644:                 if ($newlimit ne $currlimit) {
10645:                     if ($newlimit ne 'none') {
10646:                         if ($newcap =~ /^\d+$/) {
10647:                             if ($newcap ne $currcap) {
10648:                                 $changes{'internal.selfenroll_cap'} = $newcap;
10649:                             }
10650:                             $changes{'internal.selfenroll_limit'} = $newlimit;
10651:                         } else {
10652:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10653:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
10654:                         }
10655:                     } elsif ($currcap ne '') {
10656:                         $changes{'internal.selfenroll_cap'} = '';
10657:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
10658:                     }
10659:                 } elsif ($currlimit ne 'none') {
10660:                     if ($newcap =~ /^\d+$/) {
10661:                         if ($newcap ne $currcap) {
10662:                             $changes{'internal.selfenroll_cap'} = $newcap;
10663:                         }
10664:                     } else {
10665:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10666:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
10667:                     }
10668:                 }
10669:             } elsif ($item eq 'approval') {
10670:                 my (@currnotified,@newnotified);
10671:                 my $currapproval = $currsettings->{'selfenroll_approval'};
10672:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
10673:                 if ($currnotifylist ne '') {
10674:                     @currnotified = split(/,/,$currnotifylist);
10675:                     @currnotified = sort(@currnotified);
10676:                 }
10677:                 my $newapproval = $env{'form.selfenroll_approval'};
10678:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
10679:                 @newnotified = sort(@newnotified);
10680:                 if ($newapproval ne $currapproval) {
10681:                     $changes{'internal.selfenroll_approval'} = $newapproval;
10682:                     if (!$newapproval) {
10683:                         if ($currnotifylist ne '') {
10684:                             $changes{'internal.selfenroll_notifylist'} = '';
10685:                         }
10686:                     } else {
10687:                         my @differences =  
10688:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10689:                         if (@differences > 0) {
10690:                             if (@newnotified > 0) {
10691:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10692:                             } else {
10693:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10694:                             }
10695:                         }
10696:                     }
10697:                 } else {
10698:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10699:                     if (@differences > 0) {
10700:                         if (@newnotified > 0) {
10701:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10702:                         } else {
10703:                             $changes{'internal.selfenroll_notifylist'} = '';
10704:                         }
10705:                     }
10706:                 }
10707:             } else {
10708:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
10709:                 my $newval = $env{'form.selfenroll_'.$item};
10710:                 if ($item eq 'section') {
10711:                     $newval = $env{'form.sections'};
10712:                     if (defined($curr_groups{$newval})) {
10713:                         $newval = $curr_val;
10714:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
10715:                                           &mt('Group names and section names must be distinct');
10716:                     } elsif ($newval eq 'all') {
10717:                         $newval = $curr_val;
10718:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
10719:                     }
10720:                     if ($newval eq '') {
10721:                         $newval = 'none';
10722:                     }
10723:                 }
10724:                 if ($newval ne $curr_val) {
10725:                     $changes{'internal.selfenroll_'.$item} = $newval;
10726:                 }
10727:             }
10728:         }
10729:         if (keys(%warning) > 0) {
10730:             foreach my $item (@{$row}) {
10731:                 if (exists($warning{$item})) {
10732:                     $r->print($warning{$item}.'<br />');
10733:                 }
10734:             } 
10735:         }
10736:         if (keys(%changes) > 0) {
10737:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
10738:             if ($putresult eq 'ok') {
10739:                 if ((exists($changes{'internal.selfenroll_types'})) ||
10740:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
10741:                     (exists($changes{'internal.selfenroll_end_date'}))) {
10742:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
10743:                                                                 $cnum,undef,undef,'Course');
10744:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
10745:                     if (ref($crsinfo{$cid}) eq 'HASH') {
10746:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
10747:                             if (exists($changes{'internal.'.$item})) {
10748:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
10749:                             }
10750:                         }
10751:                         my $crsputresult =
10752:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
10753:                                                          $chome,'notime');
10754:                     }
10755:                 }
10756:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
10757:                 foreach my $item (@{$row}) {
10758:                     my $title = $item;
10759:                     if (ref($lt) eq 'HASH') {
10760:                         $title = $lt->{$item};
10761:                     }
10762:                     if ($item eq 'enroll_dates') {
10763:                         foreach my $type ('start','end') {
10764:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
10765:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
10766:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10767:                                           $title,$type,$newdate).'</li>');
10768:                             }
10769:                         }
10770:                     } elsif ($item eq 'access_dates') {
10771:                         foreach my $type ('start','end') {
10772:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
10773:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
10774:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10775:                                           $title,$type,$newdate).'</li>');
10776:                             }
10777:                         }
10778:                     } elsif ($item eq 'limit') {
10779:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
10780:                             (exists($changes{'internal.selfenroll_cap'}))) {
10781:                             my ($newval,$newcap);
10782:                             if ($changes{'internal.selfenroll_cap'} ne '') {
10783:                                 $newcap = $changes{'internal.selfenroll_cap'}
10784:                             } else {
10785:                                 $newcap = $currsettings->{'selfenroll_cap'};
10786:                             }
10787:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
10788:                                 $newval = &mt('No limit');
10789:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
10790:                                      'allstudents') {
10791:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10792:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10793:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10794:                             } else {
10795:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10796:                                 if ($currlimit eq 'allstudents') {
10797:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10798:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10799:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10800:                                 }
10801:                             }
10802:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10803:                         }
10804:                     } elsif ($item eq 'approval') {
10805:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
10806:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
10807:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
10808:                             my ($newval,$newnotify);
10809:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
10810:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
10811:                             } else {   
10812:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
10813:                             }
10814:                             if (exists($changes{'internal.selfenroll_approval'})) {
10815:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
10816:                                     $changes{'internal.selfenroll_approval'} = '0';
10817:                                 }
10818:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
10819:                             } else {
10820:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
10821:                                 if ($currapproval !~ /^[012]$/) {
10822:                                     $currapproval = 0;
10823:                                 }
10824:                                 $newval = $selfdescs{'approval'}{$currapproval};
10825:                             }
10826:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
10827:                             if ($newnotify) {
10828:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
10829:                             } else {
10830:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
10831:                             }
10832:                             $r->print('</li>'."\n");
10833:                         }
10834:                     } else {
10835:                         if (exists($changes{'internal.selfenroll_'.$item})) {
10836:                             my $newval = $changes{'internal.selfenroll_'.$item};
10837:                             if ($item eq 'types') {
10838:                                 if ($newval eq '') {
10839:                                     $newval = &mt('None');
10840:                                 } elsif ($newval eq '*') {
10841:                                     $newval = &mt('Any user in any domain');
10842:                                 }
10843:                             } elsif ($item eq 'registered') {
10844:                                 if ($newval eq '1') {
10845:                                     $newval = &mt('Yes');
10846:                                 } elsif ($newval eq '0') {
10847:                                     $newval = &mt('No');
10848:                                 }
10849:                             }
10850:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10851:                         }
10852:                     }
10853:                 }
10854:                 $r->print('</ul>');
10855:                 if ($env{'course.'.$cid.'.description'} ne '') {
10856:                     my %newenvhash;
10857:                     foreach my $key (keys(%changes)) {
10858:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
10859:                     }
10860:                     &Apache::lonnet::appenv(\%newenvhash);
10861:                 }
10862:             } else {
10863:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
10864:                           &mt('The error was: [_1].',$putresult));
10865:             }
10866:         } else {
10867:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10868:         }
10869:     } else {
10870:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10871:     }
10872:     my $visactions = &cat_visibility($cdom);
10873:     my ($cathash,%cattype);
10874:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
10875:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10876:         $cathash = $domconfig{'coursecategories'}{'cats'};
10877:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
10878:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
10879:     } else {
10880:         $cathash = {};
10881:         $cattype{'auth'} = 'std';
10882:         $cattype{'unauth'} = 'std';
10883:     }
10884:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
10885:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10886:                   '<br />'.
10887:                   '<br />'.$visactions->{'take'}.'<ul>'.
10888:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
10889:                   '</ul>');
10890:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
10891:         if ($currsettings->{'uniquecode'}) {
10892:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
10893:         } else {
10894:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10895:                   '<br />'.
10896:                   '<br />'.$visactions->{'take'}.'<ul>'.
10897:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
10898:                   '</ul><br />');
10899:         }
10900:     } else {
10901:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
10902:         if (ref($visactions) eq 'HASH') {
10903:             if (!$visible) {
10904:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10905:                           '<br />');
10906:                 if (ref($vismsgs) eq 'ARRAY') {
10907:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
10908:                     foreach my $item (@{$vismsgs}) {
10909:                         $r->print('<li>'.$visactions->{$item}.'</li>');
10910:                     }
10911:                     $r->print('</ul>');
10912:                 }
10913:                 $r->print($cansetvis);
10914:             }
10915:         }
10916:     } 
10917:     return;
10918: }
10919: 
10920: #---------------------------------------------- end functions for &phase_two
10921: 
10922: #--------------------------------- functions for &phase_two and &phase_three
10923: 
10924: #--------------------------end of functions for &phase_two and &phase_three
10925: 
10926: 1;
10927: __END__
10928: 
10929: 

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