File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.477: download - view: text, annotated - select for diffs
Wed May 1 15:18:58 2024 UTC (2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6990: Ability to download tarball of Authoring Space's files/directories.
  Add option to domain's Authoring Space defaults, and capability to override
  for individual author(s).

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.477 2024/05/01 15:18:58 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use Apache::lonviewcoauthors;
   74: use LONCAPA qw(:DEFAULT :match);
   75: use HTML::Entities;
   76: 
   77: my $loginscript; # piece of javascript used in two separate instances
   78: my $authformnop;
   79: my $authformkrb;
   80: my $authformint;
   81: my $authformfsys;
   82: my $authformloc;
   83: my $authformlti;
   84: 
   85: sub initialize_authen_forms {
   86:     my ($dom,$formname,$curr_authtype,$mode,$readonly) = @_;
   87:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   88:     my %param = ( formname => $formname,
   89:                   kerb_def_dom => $krbdefdom,
   90:                   kerb_def_auth => $krbdef,
   91:                   domain => $dom,
   92:                 );
   93:     my %abv_auth = &auth_abbrev();
   94:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix|lti):(.*)$/) {
   95:         my $long_auth = $1;
   96:         my $curr_autharg = $2;
   97:         my %abv_auth = &auth_abbrev();
   98:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   99:         if ($long_auth =~ /^krb(4|5)$/) {
  100:             $param{'curr_kerb_ver'} = $1;
  101:             $param{'curr_autharg'} = $curr_autharg;
  102:         }
  103:         if ($mode eq 'modifyuser') {
  104:             $param{'mode'} = $mode;
  105:         }
  106:     }
  107:     if ($readonly) {
  108:         $param{'readonly'} = 1;
  109:     }
  110:     $loginscript  = &Apache::loncommon::authform_header(%param);
  111:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  112:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  113:     $authformint  = &Apache::loncommon::authform_internal(%param);
  114:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  115:     $authformloc  = &Apache::loncommon::authform_local(%param);
  116:     $authformlti  = &Apache::loncommon::authform_lti(%param);
  117: }
  118: 
  119: sub auth_abbrev {
  120:     my %abv_auth = (
  121:                      krb5      => 'krb',
  122:                      krb4      => 'krb',
  123:                      internal  => 'int',
  124:                      localauth => 'loc',
  125:                      unix      => 'fsys',
  126:                      lti       => 'lti',
  127:                    );
  128:     return %abv_auth;
  129: }
  130: 
  131: # ====================================================
  132: 
  133: sub user_quotas {
  134:     my ($ccuname,$ccdomain,$name) = @_;
  135:     my %lt = &Apache::lonlocal::texthash(
  136:                    'cust'      => "Custom quota",
  137:                    'chqu'      => "Change quota",
  138:     );
  139:     my ($output,$longinsttype);
  140:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  141:     my %titles = &Apache::lonlocal::texthash (
  142:                     portfolio => "Disk space allocated to user's portfolio files",
  143:                     author    => "Disk space allocated to user's Authoring Space",
  144:                  );
  145:     my ($currquota,$quotatype,$inststatus,$defquota) =
  146:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  147:     if ($longinsttype eq '') {
  148:         if ($inststatus ne '') {
  149:             if ($usertypes->{$inststatus} ne '') {
  150:                 $longinsttype = $usertypes->{$inststatus};
  151:             }
  152:         }
  153:     }
  154:     my ($showquota,$custom_on,$custom_off,$defaultinfo,$colspan);
  155:     $custom_on = ' ';
  156:     $custom_off = ' checked="checked" ';
  157:     $colspan = ' colspan="2"';
  158:     if ($quotatype eq 'custom') {
  159:         $custom_on = $custom_off;
  160:         $custom_off = ' ';
  161:         $showquota = $currquota;
  162:         if ($longinsttype eq '') {
  163:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
  164:                               .' MB.',$defquota);
  165:         } else {
  166:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
  167:                                " MB,[_2]as determined by the user's institutional".
  168:                                " affiliation ([_3]).",$defquota,'<br />',$longinsttype);
  169:         }
  170:     } else {
  171:         if ($longinsttype eq '') {
  172:             $defaultinfo = &mt('For this user, the default quota is [_1]'
  173:                               .' MB.',$defquota);
  174:         } else {
  175:             $defaultinfo = &mt("For this user, the default quota of [_1]".
  176:                                " MB,[_2]is determined by the user's institutional".
  177:                                " affiliation ([_3]).",$defquota,'<br />'.$longinsttype);
  178:         }
  179:     }
  180: 
  181:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  182:         $output .= '<tr class="LC_info_row">'."\n".
  183:                    '    <td'.$colspan.'>'.$titles{$name}.'</td>'."\n".
  184:                    '  </tr>'."\n".
  185:                    &Apache::loncommon::start_data_table_row()."\n".
  186:                    '  <td'.$colspan.'><span class="LC_nobreak">'.
  187:                    &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  188:                    $defaultinfo.'</td>'."\n".
  189:                    &Apache::loncommon::end_data_table_row()."\n".
  190:                    &Apache::loncommon::start_data_table_row()."\n".
  191:                    '<td'.$colspan.'><span class="LC_nobreak">'.$lt{'chqu'}.
  192:                    ': <label>'.
  193:                    '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  194:                    'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  195:                    ' /><span class="LC_nobreak">'.
  196:                    &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  197:                    '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  198:                    'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  199:                    ' />'.$lt{'cust'}.':</label>&nbsp;'.
  200:                    '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  201:                    'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  202:                    ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  203:                    &Apache::loncommon::end_data_table_row()."\n";
  204:     }
  205:     return $output;
  206: }
  207: 
  208: sub user_quota_js {
  209:     return  <<"END_SCRIPT";
  210: <script type="text/javascript">
  211: // <![CDATA[
  212: function quota_changes(caller,context) {
  213:     var customoff = document.getElementById('custom_'+context+'quota_off');
  214:     var customon = document.getElementById('custom_'+context+'quota_on');
  215:     var number = document.getElementById(context+'quota');
  216:     if (caller == "custom") {
  217:         if (customoff) {
  218:             if (customoff.checked) {
  219:                 number.value = "";
  220:             }
  221:         }
  222:     }
  223:     if (caller == "quota") {
  224:         if (customon) {
  225:             customon.checked = true;
  226:         }
  227:     }
  228:     return;
  229: }
  230: // ]]>
  231: </script>
  232: END_SCRIPT
  233: 
  234: }
  235: 
  236: sub set_custom_js {
  237:     return  <<"END_SCRIPT";
  238: 
  239: <script type="text/javascript">
  240: // <![CDATA[
  241: function toggleCustom(form,item,name) {
  242:     if (document.getElementById(item)) {
  243:         var divid = document.getElementById(item);
  244:         var radioname = form.elements[name];
  245:         if (radioname) {
  246:             if (radioname.length > 0) {
  247:                 var setvis;
  248:                 var RegExp = /^customtext_(aboutme|blog|portfolio|portaccess|timezone|webdav)\$/;
  249:                 for (var i=0; i<radioname.length; i++) {
  250:                     if (radioname[i].checked == true) {
  251:                         if (radioname[i].value == 1) {
  252:                             if (RegExp.test(item)) {
  253:                                 divid.style.display = 'inline';
  254:                             } else {
  255:                                 divid.style.display = 'block';
  256:                             }
  257:                             setvis = 1;
  258:                         }
  259:                         break;
  260:                     }
  261:                 }
  262:                 if (!setvis) {
  263:                     divid.style.display = 'none';
  264:                 }
  265:             }
  266:         }
  267:     }
  268:     return;
  269: }
  270: // ]]>
  271: </script>
  272: 
  273: END_SCRIPT
  274: 
  275: }
  276: 
  277: sub build_tools_display {
  278:     my ($ccuname,$ccdomain,$context) = @_;
  279:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  280:         $colspan,$isadv,%domconfig,@defaulteditors,@customeditors,@custommanagers,
  281:         @possmanagers);
  282:     my %lt = &Apache::lonlocal::texthash (
  283:                    'blog'       => "Personal User Blog",
  284:                    'aboutme'    => "Personal Information Page",
  285:                    'webdav'     => "WebDAV access to Authoring Spaces (https)",
  286:                    'editors'    => "Available Editors",
  287:                    'managers'   => "Co-authors who can add/revoke roles",
  288:                    'archive'    => "Managers can download tar.gz file of Authoring Space", 
  289:                    'portfolio'  => "Personal User Portfolio",
  290:                    'portaccess' => "Portfolio Shareable",
  291:                    'timezone'   => "Can set Time Zone",
  292:                    'avai'       => "Available",
  293:                    'cusa'       => "availability",
  294:                    'chse'       => "Change setting",
  295:                    'usde'       => "Use default",
  296:                    'uscu'       => "Use custom",
  297:                    'official'   => 'Can request creation of official courses',
  298:                    'unofficial' => 'Can request creation of unofficial courses',
  299:                    'community'  => 'Can request creation of communities',
  300:                    'textbook'   => 'Can request creation of textbook courses',
  301:                    'placement'  => 'Can request creation of placement tests',
  302:                    'lti'        => 'Can request creation of LTI courses',
  303:                    'requestauthor'  => 'Can request author space',
  304:                    'edit'       => 'Standard editor (Edit)',
  305:                    'xml'        => 'Text editor (EditXML)',
  306:                    'daxe'       => 'Daxe editor (Daxe)',
  307:     );
  308:     $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  309:     if ($context eq 'requestcourses') {
  310:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  311:                       'requestcourses.official','requestcourses.unofficial',
  312:                       'requestcourses.community','requestcourses.textbook',
  313:                       'requestcourses.placement','requestcourses.lti');
  314:         @usertools = ('official','unofficial','community','textbook','placement','lti');
  315:         @options =('norequest','approval','autolimit','validate');
  316:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  317:         %reqtitles = &courserequest_titles();
  318:         %reqdisplay = &courserequest_display();
  319:         %domconfig =
  320:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  321:     } elsif ($context eq 'requestauthor') {
  322:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'requestauthor');
  323:         @usertools = ('requestauthor');
  324:         @options =('norequest','approval','automatic');
  325:         %reqtitles = &requestauthor_titles();
  326:         %reqdisplay = &requestauthor_display();
  327:         %domconfig =
  328:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  329:     } elsif ($context eq 'authordefaults') {
  330:         %domconfig =
  331:             &Apache::lonnet::get_dom('configuration',['quotas','authordefaults'],$ccdomain);
  332:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,'tools.webdav',
  333:                                                     'authoreditors','authormanagers',
  334:                                                     'authorarchive','domcoord.author');
  335:         @usertools = ('webdav','editors','managers','archive');
  336:         $colspan = ' colspan="2"';
  337:     } else {
  338:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  339:                           'tools.aboutme','tools.portfolio','tools.blog',
  340:                           'tools.timezone','tools.portaccess');
  341:         @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
  342:         $colspan = ' colspan="2"';
  343:     }
  344:     foreach my $item (@usertools) {
  345:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  346:             $currdisp,$custdisp,$custradio,$onclick,$customsty,$editorsty);
  347:         $cust_off = 'checked="checked" ';
  348:         $tool_on = 'checked="checked" ';
  349:         unless (($context eq 'authordefaults') || ($item eq 'webdav')) {
  350:             $curr_access =
  351:                 &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  352:                                                   $context,\%userenv,'',
  353:                                                   {'is_adv' => $isadv});
  354:         }
  355:         if ($context eq 'requestauthor') {
  356:             if ($userenv{$context} ne '') {
  357:                 $cust_on = ' checked="checked" ';
  358:                 $cust_off = '';
  359:             }
  360:         } elsif ($context eq 'authordefaults') {
  361:             if (($item eq 'editors') || ($item eq 'archive')) {
  362:                 if ($userenv{'author'.$item} ne '') {
  363:                     $cust_on = ' checked="checked" ';
  364:                     $cust_off = '';
  365:                 }
  366:             } elsif ($item eq 'webdav') {
  367:                 if ($userenv{'tools.'.$item} ne '') {
  368:                     $cust_on = ' checked="checked" ';
  369:                     $cust_off = '';
  370:                 }
  371:             }
  372:         } elsif ($userenv{$context.'.'.$item} ne '') {
  373:             $cust_on = ' checked="checked" ';
  374:             $cust_off = '';
  375:         }
  376:         if ($context eq 'requestcourses') {
  377:             if ($userenv{$context.'.'.$item} eq '') {
  378:                 $custom_access = &mt('Currently from default setting.');
  379:                 $customsty = ' style="display:none;"';
  380:             } else {
  381:                 $custom_access = &mt('Currently from custom setting.');
  382:                 $customsty = ' style="display:block;"';
  383:             }
  384:         } elsif ($context eq 'requestauthor') {
  385:             if ($userenv{$context} eq '') {
  386:                 $custom_access = &mt('Currently from default setting.');
  387:                 $customsty = ' style="display:none;"';
  388:             } else {
  389:                 $custom_access = &mt('Currently from custom setting.');
  390:                 $customsty = ' style="display:block;"';
  391:             }
  392:         } elsif ($item eq 'editors') {
  393:             if ($userenv{'author'.$item} eq '') {
  394:                 if (ref($domconfig{'authordefaults'}{'editors'}) eq 'ARRAY') {
  395:                     @defaulteditors = @{$domconfig{'authordefaults'}{'editors'}};
  396:                 } else {
  397:                     @defaulteditors = ('edit','xml');
  398:                 }
  399:                 $custom_access = &mt('Can use: [_1]',
  400:                                                join(', ', map { $lt{$_} } @defaulteditors));
  401:                 $editorsty = ' style="display:none;"';
  402:             } else {
  403:                 $custom_access = &mt('Currently from custom setting.');
  404:                 foreach my $editor (split(/,/,$userenv{'author'.$item})) {
  405:                     if ($editor =~ /^(edit|daxe|xml)$/) {
  406:                         push(@customeditors,$editor);
  407:                     }
  408:                 }
  409:                 if (@customeditors) {
  410:                     if (@customeditors > 1) {
  411:                         $custom_access .= '<br /><span>';
  412:                     } else {
  413:                         $custom_access .= ' <span class="LC_nobreak">';
  414:                     }
  415:                     $custom_access .= &mt('Can use: [_1]',
  416:                                           join(', ', map { $lt{$_} } @customeditors)).
  417:                                       '</span>';
  418:                 } else {
  419:                     $custom_access .= ' '.&mt('No available editors');
  420:                 }
  421:                 $editorsty = ' style="display:block;"';
  422:             }
  423:         } elsif ($item eq 'managers') {
  424:             my %ca_roles = &Apache::lonnet::get_my_roles($ccuname,$ccdomain,undef,
  425:                                                          ['active','future'],['ca']);
  426:             if (keys(%ca_roles)) {
  427:                 foreach my $entry (sort(keys(%ca_roles))) {
  428:                     if ($entry =~ /^($match_username\:$match_domain):ca$/) {
  429:                         my $user = $1;
  430:                         unless ($user eq "$ccuname:$ccdomain") {
  431:                             push(@possmanagers,$user);
  432:                         }
  433:                     }
  434:                 }
  435:             }
  436:             if ($userenv{'author'.$item} eq '') {
  437:                 $custom_access = &mt('Currently author manages co-author roles');
  438:             } else {
  439:                 if (keys(%ca_roles)) {
  440:                     foreach my $user (split(/,/,$userenv{'author'.$item})) {
  441:                         if ($user =~ /^($match_username):($match_domain)$/) {
  442:                             if (exists($ca_roles{$user.':ca'})) {
  443:                                 unless ($user eq "$ccuname:$ccdomain") {
  444:                                     push(@custommanagers,$user);
  445:                                 }
  446:                             }
  447:                         }
  448:                     }
  449:                 }
  450:                 if (@custommanagers) {
  451:                     $custom_access = &mt('Co-authors who manage co-author roles: [_1]',
  452:                                          join(', ',@custommanagers));
  453:                 } else {
  454:                     $custom_access = &mt('Currently author manages co-author roles');
  455:                 }
  456:             }
  457:         } else {
  458:             my $current = $userenv{$context.'.'.$item};
  459:             if ($item eq 'webdav') {
  460:                 $current = $userenv{'tools.webdav'};
  461:             }
  462:             if ($current eq '') {
  463:                 $custom_access =
  464:                     &mt('Availability determined currently from default setting.');
  465:                 if (!$curr_access) {
  466:                     $tool_off = 'checked="checked" ';
  467:                     $tool_on = '';
  468:                 }
  469:                 $customsty = ' style="display:none;"';
  470:             } else {
  471:                 $custom_access =
  472:                     &mt('Availability determined currently from custom setting.');
  473:                 if ($current == 0) {
  474:                     $tool_off = 'checked="checked" ';
  475:                     $tool_on = '';
  476:                 }
  477:                 $customsty = ' style="display:inline;"';
  478:             }
  479:         }
  480:         $output .= '  <tr class="LC_info_row">'."\n".
  481:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  482:                    '  </tr>'."\n".
  483:                    &Apache::loncommon::start_data_table_row()."\n";
  484:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  485:             my ($curroption,$currlimit);
  486:             my $envkey = $context.'.'.$item;
  487:             if ($context eq 'requestauthor') {
  488:                 $envkey = $context;
  489:             }
  490:             if ($userenv{$envkey} ne '') {
  491:                 $curroption = $userenv{$envkey};
  492:             } else {
  493:                 my (@inststatuses);
  494:                 if ($context eq 'requestcourses') {
  495:                     $curroption =
  496:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  497:                                                                       $isadv,$ccdomain,$item,
  498:                                                                       \@inststatuses,\%domconfig);
  499:                 } else {
  500:                      $curroption = 
  501:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  502:                                                                        $isadv,$ccdomain,undef,
  503:                                                                        \@inststatuses,\%domconfig);
  504:                 }
  505:             }
  506:             if (!$curroption) {
  507:                 $curroption = 'norequest';
  508:             }
  509:             my $name = 'crsreq_'.$item;
  510:             if ($context eq 'requestauthor') {
  511:                 $name = $item;
  512:             }
  513:             $onclick = ' onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');"';
  514:             if ($curroption =~ /^autolimit=(\d*)$/) {
  515:                 $currlimit = $1;
  516:                 if ($currlimit eq '') {
  517:                     $currdisp = &mt('Yes, automatic creation');
  518:                 } else {
  519:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  520:                 }
  521:             } else {
  522:                 $currdisp = $reqdisplay{$curroption};
  523:             }
  524:             $custdisp = '<fieldset id="customtext_'.$item.'"'.$customsty.'>';
  525:             foreach my $option (@options) {
  526:                 my $val = $option;
  527:                 if ($option eq 'norequest') {
  528:                     $val = 0;
  529:                 }
  530:                 if ($option eq 'validate') {
  531:                     my $canvalidate = 0;
  532:                     if (ref($validations{$item}) eq 'HASH') {
  533:                         if ($validations{$item}{'_custom_'}) {
  534:                             $canvalidate = 1;
  535:                         }
  536:                     }
  537:                     next if (!$canvalidate);
  538:                 }
  539:                 my $checked = '';
  540:                 if ($option eq $curroption) {
  541:                     $checked = ' checked="checked"';
  542:                 } elsif ($option eq 'autolimit') {
  543:                     if ($curroption =~ /^autolimit/) {
  544:                         $checked = ' checked="checked"';
  545:                     }
  546:                 }
  547:                 if ($option eq 'autolimit') {
  548:                     $custdisp .= '<br />';
  549:                 }
  550:                 $custdisp .= '<span class="LC_nobreak"><label>'.
  551:                              '<input type="radio" name="'.$name.'" '.
  552:                              'value="'.$val.'"'.$checked.' />'.
  553:                              $reqtitles{$option}.'</label>&nbsp;';
  554:                 if ($option eq 'autolimit') {
  555:                     $custdisp .= '<input type="text" name="'.$name.
  556:                                  '_limit" size="1" '.
  557:                                  'value="'.$currlimit.'" />&nbsp;'.
  558:                                  $reqtitles{'unlimited'}.'</span>';
  559:                 } else {
  560:                     $custdisp .= '</span>';
  561:                 }
  562:                 $custdisp .= ' ';
  563:             }
  564:             $custdisp .= '</fieldset>';
  565:             $custradio = '<br />'.$custdisp;
  566:         } elsif ($item eq 'editors') {
  567:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  568:                        &Apache::loncommon::end_data_table_row()."\n";
  569:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  570:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  571:                           '<td'.$colspan.'><span class="LC_nobreak">'.
  572:                           $lt{'chse'}.': <label>'.
  573:                           '<input type="radio" name="custom'.$item.'" value="0" '.
  574:                           $cust_off.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  575:                           $lt{'usde'}.'</label>'.('&nbsp;' x3).
  576:                           '<label><input type="radio" name="custom'.$item.'" value="1" '.
  577:                           $cust_on.' onclick="toggleCustom(this.form,'."'customtext_$item','custom$item'".');" />'.
  578:                           $lt{'uscu'}.'</label></span><br />'.
  579:                           '<fieldset id="customtext_'.$item.'"'.$editorsty.'>';
  580:                 foreach my $editor ('edit','xml','daxe') {
  581:                     my $checked;
  582:                     if ($userenv{'author'.$item} eq '') {
  583:                         if (grep(/^\Q$editor\E$/,@defaulteditors)) {
  584:                             $checked = ' checked="checked"';
  585:                         }
  586:                     } elsif (grep(/^\Q$editor\E$/,@customeditors)) {
  587:                         $checked = ' checked="checked"';
  588:                     }
  589:                     $output .= '<span style="LC_nobreak"><label>'.
  590:                                '<input type="checkbox" name="custom_editor" '.
  591:                                'value="'.$editor.'"'.$checked.' />'.
  592:                                $lt{$editor}.'</label></span> ';
  593:                 }
  594:                 $output .= '</fieldset></td>'.
  595:                            &Apache::loncommon::end_data_table_row()."\n";
  596:             }
  597:         } elsif ($item eq 'managers') {
  598:             $output .= '<td'.$colspan.'>'.$custom_access.'</td>'."\n".
  599:                        &Apache::loncommon::end_data_table_row()."\n";
  600:             unless ((&Apache::lonnet::allowed('udp',$ccdomain)) ||
  601:                     (($userenv{'domcoord.author'} eq 'blocked') &&
  602:                      (($env{'user.name'} ne $ccuname) || ($env{'user.domain'} ne $ccdomain)))) {
  603:                 $output .=
  604:                     &Apache::loncommon::start_data_table_row()."\n".
  605:                     '<td'.$colspan.'>';
  606:                 if (@possmanagers) {
  607:                     $output .= &mt('Select manager(s)').': ';
  608:                     foreach my $user (@possmanagers) {
  609:                         my $checked;
  610:                         if (grep(/^\Q$user\E$/,@custommanagers)) {
  611:                             $checked = ' checked="checked"';
  612:                         }
  613:                         $output .= '<span style="LC_nobreak"><label>'.
  614:                                    '<input type="checkbox" name="custommanagers" '.
  615:                                    'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
  616:                                    $user.'</label></span> ';
  617:                     }
  618:                 } else {
  619:                     $output .= &mt('No co-author roles assignable as manager');
  620:                 }
  621:                 $output .= '</td>'.
  622:                            &Apache::loncommon::end_data_table_row()."\n";
  623:             }
  624:         } else {
  625:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  626:             my $name = $context.'_'.$item;
  627:             $onclick = 'onclick="javascript:toggleCustom(this.form,'."'customtext_$item','custom$item'".');" ';
  628:             $custdisp = '<span class="LC_nobreak"><label>'.
  629:                         '<input type="radio" name="'.$name.'"'.
  630:                         ' value="1" '.$tool_on.$onclick.'/>'.&mt('On').'</label>&nbsp;<label>'.
  631:                         '<input type="radio" name="'.$name.'" value="0" '.
  632:                         $tool_off.$onclick.'/>'.&mt('Off').'</label></span>';
  633:             $custradio = '<span id="customtext_'.$item.'"'.$customsty.' class="LC_nobreak">'.
  634:                          '--'.$lt{'cusa'}.':&nbsp;'.$custdisp.'</span>';
  635:         }
  636:         unless (($item eq 'editors') || ($item eq 'managers')) {
  637:             $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  638:                        $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  639:                        &Apache::loncommon::end_data_table_row()."\n";
  640:             unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  641:                 $output .=
  642:                    &Apache::loncommon::start_data_table_row()."\n".
  643:                    '<td><span class="LC_nobreak">'.
  644:                    $lt{'chse'}.': <label>'.
  645:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  646:                    $cust_off.$onclick.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  647:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  648:                    $cust_on.$onclick.'/>'.$lt{'uscu'}.'</label></span>';
  649:                 if ($colspan) {
  650:                     $output .= '</td><td>';
  651:                 }
  652:                 $output .= $custradio.'</td>'.
  653:                            &Apache::loncommon::end_data_table_row()."\n";
  654:             }
  655:         }
  656:     }
  657:     return $output;
  658: }
  659: 
  660: sub coursereq_externaluser {
  661:     my ($ccuname,$ccdomain,$cdom) = @_;
  662:     my (@usertools,@options,%validations,%userenv,$output);
  663:     my %lt = &Apache::lonlocal::texthash (
  664:                    'official'   => 'Can request creation of official courses',
  665:                    'unofficial' => 'Can request creation of unofficial courses',
  666:                    'community'  => 'Can request creation of communities',
  667:                    'textbook'   => 'Can request creation of textbook courses',
  668:                    'placement'  => 'Can request creation of placement tests',
  669:     );
  670: 
  671:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  672:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  673:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  674:                       'reqcrsotherdom.placement');
  675:     @usertools = ('official','unofficial','community','textbook','placement');
  676:     @options = ('approval','validate','autolimit');
  677:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  678:     my $optregex = join('|',@options);
  679:     my %reqtitles = &courserequest_titles();
  680:     foreach my $item (@usertools) {
  681:         my ($curroption,$currlimit,$tooloff);
  682:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  683:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  684:             foreach my $req (@curr) {
  685:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  686:                     $curroption = $1;
  687:                     $currlimit = $2;
  688:                     last;
  689:                 }
  690:             }
  691:             if (!$curroption) {
  692:                 $curroption = 'norequest';
  693:                 $tooloff = ' checked="checked"';
  694:             }
  695:         } else {
  696:             $curroption = 'norequest';
  697:             $tooloff = ' checked="checked"';
  698:         }
  699:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  700:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  701:                   '<table><tr><td valign="top">'."\n".
  702:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  703:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  704:                   '</label></td>';
  705:         foreach my $option (@options) {
  706:             if ($option eq 'validate') {
  707:                 my $canvalidate = 0;
  708:                 if (ref($validations{$item}) eq 'HASH') {
  709:                     if ($validations{$item}{'_external_'}) {
  710:                         $canvalidate = 1;
  711:                     }
  712:                 }
  713:                 next if (!$canvalidate);
  714:             }
  715:             my $checked = '';
  716:             if ($option eq $curroption) {
  717:                 $checked = ' checked="checked"';
  718:             }
  719:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  720:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  721:                        '" value="'.$option.'"'.$checked.' />'.
  722:                        $reqtitles{$option}.'</label>';
  723:             if ($option eq 'autolimit') {
  724:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  725:                            $item.'_limit" size="1" '.
  726:                            'value="'.$currlimit.'" /></span>'.
  727:                            '<br />'.$reqtitles{'unlimited'};
  728:             } else {
  729:                 $output .= '</span>';
  730:             }
  731:             $output .= '</td>';
  732:         }
  733:         $output .= '</td></tr></table></td>'."\n".
  734:                    &Apache::loncommon::end_data_table_row()."\n";
  735:     }
  736:     return $output;
  737: }
  738: 
  739: sub domainrole_req {
  740:     my ($ccuname,$ccdomain) = @_;
  741:     return '<br /><h3>'.
  742:            &mt('Can Request Assignment of Domain Roles?').
  743:            '</h3>'."\n".
  744:            &Apache::loncommon::start_data_table().
  745:            &build_tools_display($ccuname,$ccdomain,
  746:                                 'requestauthor').
  747:            &Apache::loncommon::end_data_table();
  748: }
  749: 
  750: sub authoring_defaults {
  751:     my ($ccuname,$ccdomain) = @_;
  752:     return '<br /><h3>'.
  753:            &mt('Authoring Space defaults (if role assigned)').
  754:            '</h3>'."\n".
  755:            &Apache::loncommon::start_data_table().
  756:            &build_tools_display($ccuname,$ccdomain,
  757:                                 'authordefaults').
  758:            &user_quotas($ccuname,$ccdomain,'author').
  759:            &Apache::loncommon::end_data_table();
  760: }
  761: 
  762: sub courserequest_titles {
  763:     my %titles = &Apache::lonlocal::texthash (
  764:                                    official   => 'Official',
  765:                                    unofficial => 'Unofficial',
  766:                                    community  => 'Communities',
  767:                                    textbook   => 'Textbook',
  768:                                    placement  => 'Placement Tests',
  769:                                    lti        => 'LTI Provider',
  770:                                    norequest  => 'Not allowed',
  771:                                    approval   => 'Approval by Dom. Coord.',
  772:                                    validate   => 'With validation',
  773:                                    autolimit  => 'Numerical limit',
  774:                                    unlimited  => '(blank for unlimited)',
  775:                  );
  776:     return %titles;
  777: }
  778: 
  779: sub courserequest_display {
  780:     my %titles = &Apache::lonlocal::texthash (
  781:                                    approval   => 'Yes, need approval',
  782:                                    validate   => 'Yes, with validation',
  783:                                    norequest  => 'No',
  784:    );
  785:    return %titles;
  786: }
  787: 
  788: sub requestauthor_titles {
  789:     my %titles = &Apache::lonlocal::texthash (
  790:                                    norequest  => 'Not allowed',
  791:                                    approval   => 'Approval by Dom. Coord.',
  792:                                    automatic  => 'Automatic approval',
  793:                  );
  794:     return %titles;
  795: 
  796: }
  797: 
  798: sub requestauthor_display {
  799:     my %titles = &Apache::lonlocal::texthash (
  800:                                    approval   => 'Yes, need approval',
  801:                                    automatic  => 'Yes, automatic approval',
  802:                                    norequest  => 'No',
  803:    );
  804:    return %titles;
  805: }
  806: 
  807: sub requestchange_display {
  808:     my %titles = &Apache::lonlocal::texthash (
  809:                                    approval   => "availability set to 'on' (approval required)", 
  810:                                    automatic  => "availability set to 'on' (automatic approval)",
  811:                                    norequest  => "availability set to 'off'",
  812:    );
  813:    return %titles;
  814: }
  815: 
  816: sub curr_requestauthor {
  817:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  818:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  819:     if ($uname eq '' || $udom eq '') {
  820:         $uname = $env{'user.name'};
  821:         $udom = $env{'user.domain'};
  822:         $isadv = $env{'user.adv'};
  823:     }
  824:     my (%userenv,%settings,$val);
  825:     my @options = ('automatic','approval');
  826:     %userenv =
  827:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  828:     if ($userenv{'requestauthor'}) {
  829:         $val = $userenv{'requestauthor'};
  830:         @{$inststatuses} = ('_custom_');
  831:     } else {
  832:         my %alltasks;
  833:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  834:             %settings = %{$domconfig->{'requestauthor'}};
  835:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  836:                 $val = $settings{'_LC_adv'};
  837:                 @{$inststatuses} = ('_LC_adv_');
  838:             } else {
  839:                 if ($userenv{'inststatus'} ne '') {
  840:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  841:                 } else {
  842:                     @{$inststatuses} = ('default');
  843:                 }
  844:                 foreach my $status (@{$inststatuses}) {
  845:                     if (exists($settings{$status})) {
  846:                         my $value = $settings{$status};
  847:                         next unless ($value);
  848:                         unless (exists($alltasks{$value})) {
  849:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  850:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  851:                                     push(@{$alltasks{$value}},$status);
  852:                                 }
  853:                             } else {
  854:                                 @{$alltasks{$value}} = ($status);
  855:                             }
  856:                         }
  857:                     }
  858:                 }
  859:                 foreach my $option (@options) {
  860:                     if ($alltasks{$option}) {
  861:                         $val = $option;
  862:                         last;
  863:                     }
  864:                 }
  865:             }
  866:         }
  867:     }
  868:     return $val;
  869: }
  870: 
  871: # =================================================================== Phase one
  872: 
  873: sub print_username_entry_form {
  874:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  875:         $permission) = @_;
  876:     my $defdom=$env{'request.role.domain'};
  877:     my $formtoset = 'crtuser';
  878:     if (exists($env{'form.startrolename'})) {
  879:         $formtoset = 'docustom';
  880:         $env{'form.rolename'} = $env{'form.startrolename'};
  881:     } elsif ($env{'form.origform'} eq 'crtusername') {
  882:         $formtoset =  $env{'form.origform'};
  883:     }
  884: 
  885:     my ($jsback,$elements) = &crumb_utilities();
  886: 
  887:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  888:         '<script type="text/javascript">'."\n".
  889:         '// <![CDATA['."\n".
  890:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  891:         '// ]]>'."\n".
  892:         '</script>'."\n";
  893: 
  894:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  895:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  896:         && (&Apache::lonnet::allowed('mcr','/'))) {
  897:         $jscript .= &customrole_javascript();
  898:     }
  899:     my $helpitem = 'Course_Change_Privileges';
  900:     if ($env{'form.action'} eq 'custom') {
  901:         if ($context eq 'course') {
  902:             $helpitem = 'Course_Editing_Custom_Roles';
  903:         } elsif ($context eq 'domain') {
  904:             $helpitem = 'Domain_Editing_Custom_Roles';
  905:         }
  906:     } elsif ($env{'form.action'} eq 'singlestudent') {
  907:         $helpitem = 'Course_Add_Student';
  908:     } elsif ($env{'form.action'} eq 'accesslogs') {
  909:         $helpitem = 'Domain_User_Access_Logs';
  910:     } elsif ($context eq 'author') {
  911:         $helpitem = 'Author_Change_Privileges';
  912:     } elsif ($context eq 'domain') {
  913:         if ($permission->{'cusr'}) {
  914:             $helpitem = 'Domain_Change_Privileges';
  915:         } elsif ($permission->{'view'}) {
  916:             $helpitem = 'Domain_View_Privileges';
  917:         } else {
  918:             undef($helpitem);
  919:         }
  920:     }
  921:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  922:     if ($env{'form.action'} eq 'custom') {
  923:         push(@{$brcrum},
  924:                  {href=>"javascript:backPage(document.crtuser)",       
  925:                   text=>"Pick custom role",
  926:                   help => $helpitem,}
  927:                  );
  928:     } else {
  929:         push (@{$brcrum},
  930:                   {href => "javascript:backPage(document.crtuser)",
  931:                    text => $breadcrumb_text{'search'},
  932:                    help => $helpitem,
  933:                    faq  => 282,
  934:                    bug  => 'Instructor Interface',}
  935:                   );
  936:     }
  937:     my %loaditems = (
  938:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  939:                     );
  940:     my $args = {bread_crumbs           => $brcrum,
  941:                 bread_crumbs_component => 'User Management',
  942:                 add_entries            => \%loaditems,};
  943:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  944: 
  945:     my %lt=&Apache::lonlocal::texthash(
  946:                     'srst' => 'Search for a user and enroll as a student',
  947:                     'srme' => 'Search for a user and enroll as a member',
  948:                     'srad' => 'Search for a user and modify/add user information or roles',
  949:                     'srvu' => 'Search for a user and view user information and roles',
  950:                     'srva' => 'Search for a user and view access log information',
  951: 		    'usr'  => "Username",
  952:                     'dom'  => "Domain",
  953:                     'ecrp' => "Define or Edit Custom Role",
  954:                     'nr'   => "role name",
  955:                     'cre'  => "Next",
  956: 				       );
  957: 
  958:     if ($env{'form.action'} eq 'custom') {
  959:         if (&Apache::lonnet::allowed('mcr','/')) {
  960:             my $newroletext = &mt('Define new custom role:');
  961:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  962:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  963:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  964:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  965:                       &Apache::loncommon::start_data_table().
  966:                       &Apache::loncommon::start_data_table_row().
  967:                       '<td>');
  968:             if (keys(%existingroles) > 0) {
  969:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  970:             } else {
  971:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  972:             }
  973:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  974:                       &Apache::loncommon::end_data_table_row());
  975:             if (keys(%existingroles) > 0) {
  976:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  977:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  978:                           &mt('View/Modify existing role:').'</b></label></td>'.
  979:                           '<td align="center"><br />'.
  980:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  981:                           '<option value="" selected="selected">'.
  982:                           &mt('Select'));
  983:                 foreach my $role (sort(keys(%existingroles))) {
  984:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  985:                 }
  986:                 $r->print('</select>'.
  987:                           '</td>'.
  988:                           &Apache::loncommon::end_data_table_row());
  989:             }
  990:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  991:                       '<input name="customeditor" type="submit" value="'.
  992:                       $lt{'cre'}.'" /></p>'.
  993:                       '</form>');
  994:         }
  995:     } else {
  996:         my $actiontext = $lt{'srad'};
  997:         my $fixeddom;
  998:         if ($env{'form.action'} eq 'singlestudent') {
  999:             if ($crstype eq 'Community') {
 1000:                 $actiontext = $lt{'srme'};
 1001:             } else {
 1002:                 $actiontext = $lt{'srst'};
 1003:             }
 1004:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1005:             $actiontext = $lt{'srva'};
 1006:             $fixeddom = 1;
 1007:         } elsif (($env{'form.action'} eq 'singleuser') &&
 1008:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
 1009:             $actiontext = $lt{'srvu'};
 1010:             $fixeddom = 1;
 1011:         }
 1012:         $r->print("<h3>$actiontext</h3>");
 1013:         if ($env{'form.origform'} ne 'crtusername') {
 1014:             if ($response) {
 1015:                $r->print("\n<div>$response</div>".
 1016:                          '<br clear="all" />');
 1017:             }
 1018:         }
 1019:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
 1020:     }
 1021: }
 1022: 
 1023: sub customrole_javascript {
 1024:     my $js = <<"END";
 1025: <script type="text/javascript">
 1026: // <![CDATA[
 1027: 
 1028: function setCustomFields() {
 1029:     if (document.docustom.customroleaction.length > 0) {
 1030:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1031:             if (document.docustom.customroleaction[i].checked) {
 1032:                 if (document.docustom.customroleaction[i].value == 'new') {
 1033:                     document.docustom.rolename.selectedIndex = 0;
 1034:                 } else {
 1035:                     document.docustom.newrolename.value = '';
 1036:                 }
 1037:             }
 1038:         }
 1039:     }
 1040:     return;
 1041: }
 1042: 
 1043: function setCustomAction(caller) {
 1044:     if (document.docustom.customroleaction.length > 0) {
 1045:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
 1046:             if (document.docustom.customroleaction[i].value == caller) {
 1047:                 document.docustom.customroleaction[i].checked = true;
 1048:             }
 1049:         }
 1050:     }
 1051:     setCustomFields();
 1052:     return;
 1053: }
 1054: 
 1055: // ]]>
 1056: </script>
 1057: END
 1058:     return $js;
 1059: }
 1060: 
 1061: sub entry_form {
 1062:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
 1063:     my ($usertype,$inexact);
 1064:     if (ref($srch) eq 'HASH') {
 1065:         if (($srch->{'srchin'} eq 'dom') &&
 1066:             ($srch->{'srchby'} eq 'uname') &&
 1067:             ($srch->{'srchtype'} eq 'exact') &&
 1068:             ($srch->{'srchdomain'} ne '') &&
 1069:             ($srch->{'srchterm'} ne '')) {
 1070:             my (%curr_rules,%got_rules);
 1071:             my ($rules,$ruleorder) =
 1072:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
 1073:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
 1074:         } else {
 1075:             $inexact = 1;
 1076:         }
 1077:     }
 1078:     my ($cancreate,$noinstd);
 1079:     if ($env{'form.action'} eq 'accesslogs') {
 1080:         $noinstd = 1;
 1081:     } else {
 1082:         $cancreate =
 1083:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
 1084:     }
 1085:     my ($userpicker,$cansearch) = 
 1086:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
 1087:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
 1088:     my $srchbutton = &mt('Search');
 1089:     if ($env{'form.action'} eq 'singlestudent') {
 1090:         $srchbutton = &mt('Search and Enroll');
 1091:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1092:         $srchbutton = &mt('Search');
 1093:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
 1094:         $srchbutton = &mt('Search or Add New User');
 1095:     }
 1096:     my $output;
 1097:     if ($cansearch) {
 1098:         $output = <<"ENDBLOCK";
 1099: <form action="/adm/createuser" method="post" name="crtuser">
 1100: <input type="hidden" name="action" value="$env{'form.action'}" />
 1101: <input type="hidden" name="phase" value="get_user_info" />
 1102: $userpicker
 1103: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 1104: </form>
 1105: ENDBLOCK
 1106:     } else {
 1107:         $output = '<p>'.$userpicker.'</p>';
 1108:     }
 1109:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
 1110:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1111:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
 1112:         my $defdom=$env{'request.role.domain'};
 1113:         my ($trusted,$untrusted);
 1114:         if ($context eq 'course') {
 1115:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
 1116:         } elsif ($context eq 'author') {
 1117:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
 1118:         } elsif ($context eq 'domain') {
 1119:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
 1120:         }
 1121:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
 1122:         my %lt=&Apache::lonlocal::texthash(
 1123:                   'enro' => 'Enroll one student',
 1124:                   'enrm' => 'Enroll one member',
 1125:                   'admo' => 'Add/modify a single user',
 1126:                   'crea' => 'create new user if required',
 1127:                   'uskn' => "username is known",
 1128:                   'crnu' => 'Create a new user',
 1129:                   'usr'  => 'Username',
 1130:                   'dom'  => 'in domain',
 1131:                   'enrl' => 'Enroll',
 1132:                   'cram'  => 'Create/Modify user',
 1133:         );
 1134:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
 1135:         my ($title,$buttontext,$showresponse);
 1136:         if ($env{'form.action'} eq 'singlestudent') {
 1137:             if ($crstype eq 'Community') {
 1138:                 $title = $lt{'enrm'};
 1139:             } else {
 1140:                 $title = $lt{'enro'};
 1141:             }
 1142:             $buttontext = $lt{'enrl'};
 1143:         } else {
 1144:             $title = $lt{'admo'};
 1145:             $buttontext = $lt{'cram'};
 1146:         }
 1147:         if ($cancreate) {
 1148:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
 1149:         } else {
 1150:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
 1151:         }
 1152:         if ($env{'form.origform'} eq 'crtusername') {
 1153:             $showresponse = $responsemsg;
 1154:         }
 1155:         $output .= <<"ENDDOCUMENT";
 1156: <br />
 1157: <form action="/adm/createuser" method="post" name="crtusername">
 1158: <input type="hidden" name="action" value="$env{'form.action'}" />
 1159: <input type="hidden" name="phase" value="createnewuser" />
 1160: <input type="hidden" name="srchtype" value="exact" />
 1161: <input type="hidden" name="srchby" value="uname" />
 1162: <input type="hidden" name="srchin" value="dom" />
 1163: <input type="hidden" name="forcenewuser" value="1" />
 1164: <input type="hidden" name="origform" value="crtusername" />
 1165: <h3>$title</h3>
 1166: $showresponse
 1167: <table>
 1168:  <tr>
 1169:   <td>$lt{'usr'}:</td>
 1170:   <td><input type="text" size="15" name="srchterm" /></td>
 1171:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
 1172:   <td>&nbsp;$sellink&nbsp;</td>
 1173:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
 1174:  </tr>
 1175: </table>
 1176: </form>
 1177: ENDDOCUMENT
 1178:     }
 1179:     return $output;
 1180: }
 1181: 
 1182: sub user_modification_js {
 1183:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
 1184:     
 1185:     return <<END;
 1186: <script type="text/javascript" language="Javascript">
 1187: // <![CDATA[
 1188: 
 1189:     $pjump_def
 1190:     $dc_setcourse_code
 1191: 
 1192:     function dateset() {
 1193:         eval("document.cu."+document.cu.pres_marker.value+
 1194:             ".value=document.cu.pres_value.value");
 1195:         modalWindow.close();
 1196:     }
 1197: 
 1198:     $nondc_setsection_code
 1199: // ]]>
 1200: </script>
 1201: END
 1202: }
 1203: 
 1204: # =================================================================== Phase two
 1205: sub print_user_selection_page {
 1206:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
 1207:     my @fields = ('username','domain','lastname','firstname','permanentemail');
 1208:     my $sortby = $env{'form.sortby'};
 1209: 
 1210:     if (!grep(/^\Q$sortby\E$/,@fields)) {
 1211:         $sortby = 'lastname';
 1212:     }
 1213: 
 1214:     my ($jsback,$elements) = &crumb_utilities();
 1215: 
 1216:     my $jscript = (<<ENDSCRIPT);
 1217: <script type="text/javascript">
 1218: // <![CDATA[
 1219: function pickuser(uname,udom) {
 1220:     document.usersrchform.seluname.value=uname;
 1221:     document.usersrchform.seludom.value=udom;
 1222:     document.usersrchform.phase.value="userpicked";
 1223:     document.usersrchform.submit();
 1224: }
 1225: 
 1226: $jsback
 1227: // ]]>
 1228: </script>
 1229: ENDSCRIPT
 1230: 
 1231:     my %lt=&Apache::lonlocal::texthash(
 1232:                                        'usrch'          => "User Search to add/modify roles",
 1233:                                        'stusrch'        => "User Search to enroll student",
 1234:                                        'memsrch'        => "User Search to enroll member",
 1235:                                        'srcva'          => "Search for a user and view access log information",
 1236:                                        'usrvu'          => "User Search to view user roles",
 1237:                                        'usel'           => "Select a user to add/modify roles",
 1238:                                        'suvr'           => "Select a user to view roles",
 1239:                                        'stusel'         => "Select a user to enroll as a student",
 1240:                                        'memsel'         => "Select a user to enroll as a member",
 1241:                                        'vacsel'         => "Select a user to view access log",
 1242:                                        'username'       => "username",
 1243:                                        'domain'         => "domain",
 1244:                                        'lastname'       => "last name",
 1245:                                        'firstname'      => "first name",
 1246:                                        'permanentemail' => "permanent e-mail",
 1247:                                       );
 1248:     if ($context eq 'requestcrs') {
 1249:         $r->print('<div>');
 1250:     } else {
 1251:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1252:         my $helpitem;
 1253:         if ($env{'form.action'} eq 'singleuser') {
 1254:             $helpitem = 'Course_Change_Privileges';
 1255:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1256:             $helpitem = 'Course_Add_Student';
 1257:         } elsif ($context eq 'author') {
 1258:             $helpitem = 'Author_Change_Privileges';
 1259:         } elsif ($context eq 'domain') {
 1260:             $helpitem = 'Domain_Change_Privileges';
 1261:         }
 1262:         push (@{$brcrum},
 1263:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1264:                    text => $breadcrumb_text{'search'},
 1265:                    faq  => 282,
 1266:                    bug  => 'Instructor Interface',},
 1267:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1268:                    text => $breadcrumb_text{'userpicked'},
 1269:                    faq  => 282,
 1270:                    bug  => 'Instructor Interface',
 1271:                    help => $helpitem}
 1272:                   );
 1273:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1274:         if ($env{'form.action'} eq 'singleuser') {
 1275:             my $readonly;
 1276:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1277:                 $readonly = 1;
 1278:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1279:             } else {
 1280:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1281:             }
 1282:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1283:             if ($readonly) {
 1284:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1285:             } else {
 1286:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1287:             }
 1288:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1289:             $r->print($jscript."<b>");
 1290:             if ($crstype eq 'Community') {
 1291:                 $r->print($lt{'memsrch'});
 1292:             } else {
 1293:                 $r->print($lt{'stusrch'});
 1294:             }
 1295:             $r->print("</b><br />");
 1296:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1297:             $r->print('</form><h3>');
 1298:             if ($crstype eq 'Community') {
 1299:                 $r->print($lt{'memsel'});
 1300:             } else {
 1301:                 $r->print($lt{'stusel'});
 1302:             }
 1303:             $r->print('</h3>');
 1304:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1305:             $r->print("<b>$lt{'srcva'}</b><br />");
 1306:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1307:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1308:         }
 1309:     }
 1310:     $r->print('<form name="usersrchform" method="post" action="">'.
 1311:               &Apache::loncommon::start_data_table()."\n".
 1312:               &Apache::loncommon::start_data_table_header_row()."\n".
 1313:               ' <th> </th>'."\n");
 1314:     foreach my $field (@fields) {
 1315:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1316:                   "'".$field."'".';document.usersrchform.submit();">'.
 1317:                   $lt{$field}.'</a></th>'."\n");
 1318:     }
 1319:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1320: 
 1321:     my @sorted_users = sort {
 1322:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1323:             ||
 1324:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1325:             ||
 1326:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1327: 	    ||
 1328: 	lc($a) cmp lc($b)
 1329:         } (keys(%$srch_results));
 1330: 
 1331:     foreach my $user (@sorted_users) {
 1332:         my ($uname,$udom) = split(/:/,$user);
 1333:         my $onclick;
 1334:         if ($context eq 'requestcrs') {
 1335:             $onclick =
 1336:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1337:                                                "'$srch_results->{$user}->{firstname}',".
 1338:                                                "'$srch_results->{$user}->{lastname}',".
 1339:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1340:         } else {
 1341:             $onclick =
 1342:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1343:         }
 1344:         $r->print(&Apache::loncommon::start_data_table_row().
 1345:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1346:                   $onclick.' /></td>'.
 1347:                   '<td><tt>'.$uname.'</tt></td>'.
 1348:                   '<td><tt>'.$udom.'</tt></td>');
 1349:         foreach my $field ('lastname','firstname','permanentemail') {
 1350:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1351:         }
 1352:         $r->print(&Apache::loncommon::end_data_table_row());
 1353:     }
 1354:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1355:     if (ref($srcharray) eq 'ARRAY') {
 1356:         foreach my $item (@{$srcharray}) {
 1357:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1358:         }
 1359:     }
 1360:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1361:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1362:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1363:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1364:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1365:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1366:     if ($context eq 'requestcrs') {
 1367:         $r->print($opener_elements.'</form></div>');
 1368:     } else {
 1369:         $r->print($response.'</form>');
 1370:     }
 1371: }
 1372: 
 1373: sub print_user_query_page {
 1374:     my ($r,$caller,$brcrum) = @_;
 1375: # FIXME - this is for a network-wide name search (similar to catalog search)
 1376: # To use frames with similar behavior to catalog/portfolio search.
 1377: # To be implemented. 
 1378:     return;
 1379: }
 1380: 
 1381: sub print_user_modification_page {
 1382:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1383:         $brcrum,$showcredits) = @_;
 1384:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1385:         my $usermsg = &mt('No username and/or domain provided.');
 1386:         $env{'form.phase'} = '';
 1387: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1388:                                    $permission);
 1389:         return;
 1390:     }
 1391:     my ($form,$formname);
 1392:     if ($env{'form.action'} eq 'singlestudent') {
 1393:         $form = 'document.enrollstudent';
 1394:         $formname = 'enrollstudent';
 1395:     } else {
 1396:         $form = 'document.cu';
 1397:         $formname = 'cu';
 1398:     }
 1399:     my %abv_auth = &auth_abbrev();
 1400:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1401:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1402:     if ($uhome eq 'no_host') {
 1403:         my $usertype;
 1404:         my ($rules,$ruleorder) =
 1405:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1406:             $usertype =
 1407:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1408:                                                       \%curr_rules,\%got_rules);
 1409:         my $cancreate =
 1410:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1411:                                                    $usertype);
 1412:         if (!$cancreate) {
 1413:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1414:             my %usertypetext = (
 1415:                 official   => 'institutional',
 1416:                 unofficial => 'non-institutional',
 1417:             );
 1418:             my $response;
 1419:             if ($env{'form.origform'} eq 'crtusername') {
 1420:                 $response = '<span class="LC_warning">'.
 1421:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1422:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1423:                             '</span><br />';
 1424:             }
 1425:             $response .= '<p class="LC_warning">'
 1426:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1427:                         .' ';
 1428:             if ($context eq 'domain') {
 1429:                 $response .= &mt('Please contact a [_1] for assistance.',
 1430:                                  &Apache::lonnet::plaintext('dc'));
 1431:             } else {
 1432:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1433:                                 ,'<a href="'.$helplink.'">','</a>');
 1434:             }
 1435:             $response .= '</p><br />';
 1436:             $env{'form.phase'} = '';
 1437:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1438:                                        $permission);
 1439:             return;
 1440:         }
 1441:         $newuser = 1;
 1442:         my $checkhash;
 1443:         my $checks = { 'username' => 1 };
 1444:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1445:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1446:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1447:         if (ref($alerts{'username'}) eq 'HASH') {
 1448:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1449:                 my $domdesc =
 1450:                     &Apache::lonnet::domain($ccdomain,'description');
 1451:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1452:                     my $userchkmsg;
 1453:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1454:                         $userchkmsg = 
 1455:                             &Apache::loncommon::instrule_disallow_msg('username',
 1456:                                                                  $domdesc,1).
 1457:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1458:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1459:                             'username');
 1460:                     }
 1461:                     $env{'form.phase'} = '';
 1462:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1463:                                                $permission);
 1464:                     return;
 1465:                 }
 1466:             }
 1467:         }
 1468:     } else {
 1469:         $newuser = 0;
 1470:     }
 1471:     if ($response) {
 1472:         $response = '<br />'.$response;
 1473:     }
 1474: 
 1475:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1476:     my $dc_setcourse_code = '';
 1477:     my $nondc_setsection_code = '';                                        
 1478:     my %loaditem;
 1479: 
 1480:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1481: 
 1482:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
 1483:                                     $crstype,$groupslist,$newuser,
 1484:                                     $formname,\%loaditem,$permission);
 1485:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1486:     my $helpitem = 'Course_Change_Privileges';
 1487:     if ($env{'form.action'} eq 'singlestudent') {
 1488:         $helpitem = 'Course_Add_Student';
 1489:     } elsif ($context eq 'author') {
 1490:         $helpitem = 'Author_Change_Privileges';
 1491:     } elsif ($context eq 'domain') {
 1492:         $helpitem = 'Domain_Change_Privileges';
 1493:         $js .= &set_custom_js();
 1494:     }
 1495:     push (@{$brcrum},
 1496:         {href => "javascript:backPage($form)",
 1497:          text => $breadcrumb_text{'search'},
 1498:          faq  => 282,
 1499:          bug  => 'Instructor Interface',});
 1500:     if ($env{'form.phase'} eq 'userpicked') {
 1501:        push(@{$brcrum},
 1502:               {href => "javascript:backPage($form,'get_user_info','select')",
 1503:                text => $breadcrumb_text{'userpicked'},
 1504:                faq  => 282,
 1505:                bug  => 'Instructor Interface',});
 1506:     }
 1507:     push(@{$brcrum},
 1508:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1509:              text => $breadcrumb_text{'modify'},
 1510:              faq  => 282,
 1511:              bug  => 'Instructor Interface',
 1512:              help => $helpitem});
 1513:     my $args = {'add_entries'           => \%loaditem,
 1514:                 'bread_crumbs'          => $brcrum,
 1515:                 'bread_crumbs_component' => 'User Management'};
 1516:     if ($env{'form.popup'}) {
 1517:         $args->{'no_nav_bar'} = 1;
 1518:     }
 1519:     if (($context eq 'domain') && ($env{'request.role.domain'} eq $ccdomain)) {
 1520:         my @toggles;
 1521:         if (&Apache::lonnet::allowed('cau',$ccdomain)) {
 1522:             my ($isadv,$isauthor) =
 1523:                 &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1524:             unless ($isauthor) {
 1525:                 push(@toggles,'requestauthor');
 1526:             }
 1527:             push(@toggles,('webdav','editors'));
 1528:         }
 1529:         if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1530:             push(@toggles,('aboutme','blog','portfolio','portaccess','timezone'));
 1531:         }
 1532:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1533:             push(@toggles,('official','unofficial','community','textbook','placement','lti'));
 1534:         }
 1535:         if (@toggles) {
 1536:             my $onload;
 1537:             foreach my $item (@toggles) {
 1538:                 $onload .= "toggleCustom(document.cu,'customtext_$item','custom$item');";
 1539:             }
 1540:             $args->{'add_entries'} = {
 1541:                                        'onload' => $onload,
 1542:                                      };
 1543:         }
 1544:     }
 1545:     my $start_page =
 1546:         &Apache::loncommon::start_page('User Management',$js,$args);
 1547: 
 1548:     my $forminfo =<<"ENDFORMINFO";
 1549: <form action="/adm/createuser" method="post" name="$formname">
 1550: <input type="hidden" name="phase" value="update_user_data" />
 1551: <input type="hidden" name="ccuname" value="$ccuname" />
 1552: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1553: <input type="hidden" name="pres_value"  value="" />
 1554: <input type="hidden" name="pres_type"   value="" />
 1555: <input type="hidden" name="pres_marker" value="" />
 1556: ENDFORMINFO
 1557:     my (%inccourses,$roledom,$defaultcredits);
 1558:     if ($context eq 'course') {
 1559:         $inccourses{$env{'request.course.id'}}=1;
 1560:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1561:         if ($showcredits) {
 1562:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1563:         }
 1564:     } elsif ($context eq 'author') {
 1565:         $roledom = $env{'request.role.domain'};
 1566:     } elsif ($context eq 'domain') {
 1567:         foreach my $key (keys(%env)) {
 1568:             $roledom = $env{'request.role.domain'};
 1569:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1570:                 $inccourses{$1.'_'.$2}=1;
 1571:             }
 1572:         }
 1573:     } else {
 1574:         foreach my $key (keys(%env)) {
 1575: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1576: 	        $inccourses{$1.'_'.$2}=1;
 1577:             }
 1578:         }
 1579:     }
 1580:     my $title = '';
 1581:     my $need_quota_js;
 1582:     if ($newuser) {
 1583:         my ($portfolioform,$domroleform);
 1584:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1585:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1586:             # Current user has quota or user tools modification privileges
 1587:             $portfolioform = '<br /><h3>'.
 1588:                              &mt('User Tools').
 1589:                              '</h3>'."\n".
 1590:                              &Apache::loncommon::start_data_table();
 1591:             if (&Apache::lonnet::allowed('mut',$ccdomain)) {
 1592:                 $portfolioform .= &build_tools_display($ccuname,$ccdomain,'tools');
 1593:             }
 1594:             if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1595:                 $portfolioform .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1596:                 $need_quota_js = 1;
 1597:             }
 1598:             $portfolioform .= &Apache::loncommon::end_data_table();
 1599:         }
 1600:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1601:             ($ccdomain eq $env{'request.role.domain'})) {
 1602:             $domroleform = &domainrole_req($ccuname,$ccdomain).
 1603:                            &authoring_defaults($ccuname,$ccdomain);
 1604:             $need_quota_js = 1;
 1605:         }
 1606:         my $readonly;
 1607:         unless ($permission->{'cusr'}) {
 1608:             $readonly = 1;
 1609:         }
 1610:         &initialize_authen_forms($ccdomain,$formname,'','',$readonly);
 1611:         my %lt=&Apache::lonlocal::texthash(
 1612:                 'lg'             => 'Login Data',
 1613:                 'hs'             => "Home Server",
 1614:         );
 1615: 	$r->print(<<ENDTITLE);
 1616: $start_page
 1617: $response
 1618: $forminfo
 1619: <script type="text/javascript" language="Javascript">
 1620: // <![CDATA[
 1621: $loginscript
 1622: // ]]>
 1623: </script>
 1624: <input type='hidden' name='makeuser' value='1' />
 1625: ENDTITLE
 1626:         if ($env{'form.action'} eq 'singlestudent') {
 1627:             if ($crstype eq 'Community') {
 1628:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1629:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1630:             } else {
 1631:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1632:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1633:             }
 1634:         } else {
 1635:                 $title = &mt('Create New User [_1] in domain [_2]',
 1636:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1637:         }
 1638:         $r->print('<h2>'.$title.'</h2>'."\n");
 1639:         $r->print('<div class="LC_left_float">');
 1640:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1641:                                          $inst_results{$ccuname.':'.$ccdomain},$readonly));
 1642:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1643:         my ($home_server_pick,$numlib) = 
 1644:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1645:                                                       'default','hide');
 1646:         if ($numlib > 1) {
 1647:             $r->print("
 1648: <br />
 1649: $lt{'hs'}: $home_server_pick
 1650: <br />");
 1651:         } else {
 1652:             $r->print($home_server_pick);
 1653:         }
 1654:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1655:             $r->print('<br /><h3>'.
 1656:                       &mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1657:                       &Apache::loncommon::start_data_table().
 1658:                       &build_tools_display($ccuname,$ccdomain,
 1659:                                            'requestcourses').
 1660:                       &Apache::loncommon::end_data_table());
 1661:         }
 1662:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1663:                   $lt{'lg'}.'</h3>');
 1664:         my ($fixedauth,$varauth,$authmsg); 
 1665:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1666:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1667:             my ($rules,$ruleorder) = 
 1668:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1669:             if (ref($rules) eq 'HASH') {
 1670:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1671:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1672:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1673:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1674:                     } else { 
 1675:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1676:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1677:                         if ($authtype =~ /^krb(4|5)$/) {
 1678:                             my $ver = $1;
 1679:                             if ($authparm ne '') {
 1680:                                 $fixedauth = <<"KERB"; 
 1681: <input type="hidden" name="login" value="krb" />
 1682: <input type="hidden" name="krbver" value="$ver" />
 1683: <input type="hidden" name="krbarg" value="$authparm" />
 1684: KERB
 1685:                             }
 1686:                         } else {
 1687:                             $fixedauth = 
 1688: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1689:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1690:                                 $fixedauth .=    
 1691: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1692:                             } else {
 1693:                                 if ($authtype eq 'int') {
 1694:                                     $varauth = '<br />'.
 1695: &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>';
 1696:                                 } elsif ($authtype eq 'loc') {
 1697:                                     $varauth = '<br />'.
 1698: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1699:                                 } else {
 1700:                                     $varauth =
 1701: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1702:                                 }
 1703:                             }
 1704:                         }
 1705:                     }
 1706:                 } else {
 1707:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1708:                 }
 1709:             }
 1710:             if ($authmsg) {
 1711:                 $r->print(<<ENDAUTH);
 1712: $fixedauth
 1713: $authmsg
 1714: $varauth
 1715: ENDAUTH
 1716:             }
 1717:         } else {
 1718:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1719:         }
 1720:         $r->print($portfolioform.$domroleform);
 1721:         if ($env{'form.action'} eq 'singlestudent') {
 1722:             $r->print(&date_sections_select($context,$newuser,$formname,
 1723:                                             $permission,$crstype,$ccuname,
 1724:                                             $ccdomain,$showcredits));
 1725:         }
 1726:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1727:     } else { # user already exists
 1728: 	$r->print($start_page.$forminfo);
 1729:         if ($env{'form.action'} eq 'singlestudent') {
 1730:             if ($crstype eq 'Community') {
 1731:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1732:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1733:             } else {
 1734:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1735:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1736:             }
 1737:         } else {
 1738:             if ($permission->{'cusr'}) {
 1739:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1740:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1741:             } else {
 1742:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1743:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1744:             }
 1745:         }
 1746:         $r->print('<h2>'.$title.'</h2>'."\n");
 1747:         $r->print('<div class="LC_left_float">');
 1748:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1749:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1750:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1751:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1752:             $r->print('<br /><h3>'.&mt('Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1753:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1754:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1755:                 $r->print(&Apache::loncommon::start_data_table());
 1756:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1757:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1758:                 } else {
 1759:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1760:                                                       $env{'request.role.domain'}));
 1761:                 }
 1762:                 $r->print(&Apache::loncommon::end_data_table());
 1763:             } else {
 1764:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1765:                               &Apache::lonnet::domain($ccdomain,'description')));
 1766:             }
 1767:         }
 1768:         $r->print('</div>');
 1769:         my @order = ('auth','quota','tools','requestauthor','authordefaults');
 1770:         my %user_text;
 1771:         my ($isadv,$isauthor) = 
 1772:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1773:         if (((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1774:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1775:             ($env{'request.role.domain'} eq $ccdomain)) {
 1776:             if (!$isauthor) {
 1777:                 $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1778:             }
 1779:             $user_text{'authordefaults'} = &authoring_defaults($ccuname,$ccdomain);
 1780:             if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 1781:                 $need_quota_js = 1;
 1782:             }
 1783:         }
 1784:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1785:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1786:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1787:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1788:             $user_text{'quota'} = '<br /><h3>'.&mt('User Tools').'</h3>'."\n".
 1789:                                   &Apache::loncommon::start_data_table();
 1790:             if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1791:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1792:                 $user_text{'quota'} .= &build_tools_display($ccuname,$ccdomain,'tools');
 1793:             }
 1794:             # Current user has quota modification privileges
 1795:             if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1796:                 (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1797:                 $user_text{'quota'} .= &user_quotas($ccuname,$ccdomain,'portfolio');
 1798:                 $need_quota_js = 1;
 1799:             }
 1800:             $user_text{'quota'} .= &Apache::loncommon::end_data_table();
 1801:         }
 1802:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1803:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1804:                 my %lt=&Apache::lonlocal::texthash(
 1805:                     'dska'  => "Disk quotas for user's portfolio",
 1806:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
 1807:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1808:                 );
 1809:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1810: <h3>$lt{'dska'}</h3>
 1811: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1812: ENDNOPORTPRIV
 1813:             }
 1814:         }
 1815:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1816:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1817:                 my %lt=&Apache::lonlocal::texthash(
 1818:                     'utav'  => "User Tools Availability",
 1819:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, Personal Information Page, or Time Zone settings for this user.",
 1820:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1821:                 );
 1822:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1823: <h3>$lt{'utav'}</h3>
 1824: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1825: ENDNOTOOLSPRIV
 1826:             }
 1827:         }
 1828:         my $gotdiv = 0; 
 1829:         foreach my $item (@order) {
 1830:             if ($user_text{$item} ne '') {
 1831:                 unless ($gotdiv) {
 1832:                     $r->print('<div class="LC_left_float">');
 1833:                     $gotdiv = 1;
 1834:                 }
 1835:                 $r->print('<br />'.$user_text{$item});
 1836:             }
 1837:         }
 1838:         if ($env{'form.action'} eq 'singlestudent') {
 1839:             unless ($gotdiv) {
 1840:                 $r->print('<div class="LC_left_float">');
 1841:             }
 1842:             my $credits;
 1843:             if ($showcredits) {
 1844:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1845:                 if ($credits eq '') {
 1846:                     $credits = $defaultcredits;
 1847:                 }
 1848:             }
 1849:             $r->print(&date_sections_select($context,$newuser,$formname,
 1850:                                             $permission,$crstype,$ccuname,
 1851:                                             $ccdomain,$showcredits));
 1852:         }
 1853:         if ($gotdiv) {
 1854:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1855:         }
 1856:         my $statuses;
 1857:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1858:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1859:             $statuses = ['active'];
 1860:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1861:                  ($env{'request.course.sec'} &&
 1862:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1863:             $statuses = ['active'];
 1864:         }
 1865:         if ($env{'form.action'} ne 'singlestudent') {
 1866:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1867:                                     $roledom,$crstype,$showcredits,$statuses);
 1868:         }
 1869:     } ## End of new user/old user logic
 1870:     if ($env{'form.action'} eq 'singlestudent') {
 1871:         my $btntxt;
 1872:         if ($crstype eq 'Community') {
 1873:             $btntxt = &mt('Enroll Member');
 1874:         } else {
 1875:             $btntxt = &mt('Enroll Student');
 1876:         }
 1877:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1878:     } elsif ($permission->{'cusr'}) {
 1879:         $r->print('<div class="LC_left_float">'.
 1880:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1881:         my $addrolesdisplay = 0;
 1882:         if ($context eq 'domain' || $context eq 'author') {
 1883:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1884:         }
 1885:         if ($context eq 'domain') {
 1886:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1887:             if (!$addrolesdisplay) {
 1888:                 $addrolesdisplay = $add_domainroles;
 1889:             }
 1890:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1891:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1892:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1893:         } elsif ($context eq 'author') {
 1894:             if ($addrolesdisplay) {
 1895:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1896:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1897:                 if ($newuser) {
 1898:                     $r->print(' onclick="auth_check()" \>'."\n");
 1899:                 } else {
 1900:                     $r->print(' onclick="this.form.submit()" \>'."\n");
 1901:                 }
 1902:             } else {
 1903:                 $r->print('</fieldset></div>'.
 1904:                           '<div class="LC_clear_float_footer"></div>'.
 1905:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1906:                           &mt('Back to previous page').'</a>');
 1907:             }
 1908:         } else {
 1909:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1910:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1911:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1912:         }
 1913:     }
 1914:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1915:     $r->print('<input type="hidden" name="currstate" value="" />');
 1916:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1917:     if ($need_quota_js) {
 1918:         $r->print(&user_quota_js());
 1919:     }
 1920:     return;
 1921: }
 1922: 
 1923: sub singleuser_breadcrumb {
 1924:     my ($crstype,$context,$domain) = @_;
 1925:     my %breadcrumb_text;
 1926:     if ($env{'form.action'} eq 'singlestudent') {
 1927:         if ($crstype eq 'Community') {
 1928:             $breadcrumb_text{'search'} = 'Enroll a member';
 1929:         } else {
 1930:             $breadcrumb_text{'search'} = 'Enroll a student';
 1931:         }
 1932:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1933:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1934:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1935:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1936:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1937:         $breadcrumb_text{'activity'} = 'Activity';
 1938:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1939:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1940:         $breadcrumb_text{'search'} = "View user's roles";
 1941:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1942:         $breadcrumb_text{'modify'} = 'User roles';
 1943:     } else {
 1944:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1945:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1946:         $breadcrumb_text{'modify'} = 'Set user role';
 1947:     }
 1948:     return %breadcrumb_text;
 1949: }
 1950: 
 1951: sub date_sections_select {
 1952:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1953:         $showcredits) = @_;
 1954:     my $credits;
 1955:     if ($showcredits) {
 1956:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1957:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1958:         if ($credits eq '') {
 1959:             $credits = $defaultcredits;
 1960:         }
 1961:     }
 1962:     my $cid = $env{'request.course.id'};
 1963:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1964:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1965:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1966:                                                   undef,$formname,$permission);
 1967:     my $rowtitle = 'Section';
 1968:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1969:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1970:                                               $permission,$context,'',$crstype,
 1971:                                               $showcredits,$credits);
 1972:     my $output = $date_table.$secbox;
 1973:     return $output;
 1974: }
 1975: 
 1976: sub validation_javascript {
 1977:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1978:         $loaditem,$permission) = @_;
 1979:     my $dc_setcourse_code = '';
 1980:     my $nondc_setsection_code = '';
 1981:     if ($context eq 'domain') {
 1982:         if ((ref($permission) eq 'HASH') && ($permission->{'cusr'})) {
 1983:             my $dcdom = $env{'request.role.domain'};
 1984:             $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1985:             $dc_setcourse_code =
 1986:                 &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1987:         }
 1988:     } else {
 1989:         my $checkauth; 
 1990:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1991:             $checkauth = 1;
 1992:         }
 1993:         if ($context eq 'course') {
 1994:             $nondc_setsection_code =
 1995:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1996:                                                               undef,$checkauth,
 1997:                                                               $crstype);
 1998:         }
 1999:         if ($checkauth) {
 2000:             $nondc_setsection_code .= 
 2001:                 &Apache::lonuserutils::verify_authen($formname,$context);
 2002:         }
 2003:     }
 2004:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 2005:                                    $nondc_setsection_code,$groupslist);
 2006:     my ($jsback,$elements) = &crumb_utilities();
 2007:     $js .= "\n".
 2008:            '<script type="text/javascript">'."\n".
 2009:            '// <![CDATA['."\n".
 2010:            $jsback."\n".
 2011:            '// ]]>'."\n".
 2012:            '</script>'."\n";
 2013:     return $js;
 2014: }
 2015: 
 2016: sub display_existing_roles {
 2017:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 2018:         $showcredits,$statuses) = @_;
 2019:     my $now=time;
 2020:     my $showall = 1;
 2021:     my ($showexpired,$showactive);
 2022:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 2023:         $showall = 0;
 2024:         if (grep(/^expired$/,@{$statuses})) {
 2025:             $showexpired = 1;
 2026:         }
 2027:         if (grep(/^active$/,@{$statuses})) {
 2028:             $showactive = 1;
 2029:         }
 2030:         if ($showexpired && $showactive) {
 2031:             $showall = 1;
 2032:         }
 2033:     }
 2034:     my %lt=&Apache::lonlocal::texthash(
 2035:                     'rer'  => "Existing Roles",
 2036:                     'rev'  => "Revoke",
 2037:                     'del'  => "Delete",
 2038:                     'ren'  => "Re-Enable",
 2039:                     'rol'  => "Role",
 2040:                     'ext'  => "Extent",
 2041:                     'crd'  => "Credits",
 2042:                     'sta'  => "Start",
 2043:                     'end'  => "End",
 2044:                                        );
 2045:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 2046:     if ($context eq 'course' || $context eq 'author') {
 2047:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 2048:         my %roleshash = 
 2049:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 2050:                               ['active','previous','future'],\@roles,$roledom,1);
 2051:         foreach my $key (keys(%roleshash)) {
 2052:             my ($start,$end) = split(':',$roleshash{$key});
 2053:             next if ($start eq '-1' || $end eq '-1');
 2054:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 2055:             if ($context eq 'course') {
 2056:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 2057:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 2058:             } elsif ($context eq 'author') {
 2059:                 if ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2060:                     my ($audom,$auname) = ($1,$2);
 2061:                     next unless (($rnum eq $auname) && ($rdom eq $audom));
 2062:                 } else {
 2063:                     next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 2064:                 }
 2065:             }
 2066:             my ($newkey,$newvalue,$newrole);
 2067:             $newkey = '/'.$rdom.'/'.$rnum;
 2068:             if ($sec ne '') {
 2069:                 $newkey .= '/'.$sec;
 2070:             }
 2071:             $newvalue = $role;
 2072:             if ($role =~ /^cr/) {
 2073:                 $newrole = 'cr';
 2074:             } else {
 2075:                 $newrole = $role;
 2076:             }
 2077:             $newkey .= '_'.$newrole;
 2078:             if ($start ne '' && $end ne '') {
 2079:                 $newvalue .= '_'.$end.'_'.$start;
 2080:             } elsif ($end ne '') {
 2081:                 $newvalue .= '_'.$end;
 2082:             }
 2083:             $rolesdump{$newkey} = $newvalue;
 2084:         }
 2085:     } else {
 2086:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 2087:     }
 2088:     # Build up table of user roles to allow revocation and re-enabling of roles.
 2089:     my ($tmp) = keys(%rolesdump);
 2090:     return if ($tmp =~ /^(con_lost|error)/i);
 2091:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 2092:                                 my $b1=join('_',(split('_',$b))[1,0]);
 2093:                                 return $a1 cmp $b1;
 2094:                             } keys(%rolesdump)) {
 2095:         next if ($area =~ /^rolesdef/);
 2096:         my $envkey=$area;
 2097:         my $role = $rolesdump{$area};
 2098:         my $thisrole=$area;
 2099:         $area =~ s/\_\w\w$//;
 2100:         my ($role_code,$role_end_time,$role_start_time) =
 2101:             split(/_/,$role);
 2102:         my $active=1;
 2103:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 2104:         if ($active) {
 2105:             next unless($showall || $showactive);
 2106:         } else {
 2107:             next unless($showall || $showexpired);
 2108:         }
 2109: # Is this a custom role? Get role owner and title.
 2110:         my ($croleudom,$croleuname,$croletitle)=
 2111:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 2112:         my $allowed=0;
 2113:         my $delallowed=0;
 2114:         my $sortkey=$role_code;
 2115:         my $class='Unknown';
 2116:         my $credits='';
 2117:         my $csec;
 2118:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 2119:             $class='Course';
 2120:             my ($coursedom,$coursedir) = ($1,$2);
 2121:             my $cid = $1.'_'.$2;
 2122:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 2123:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 2124:             my %coursedata=
 2125:                 &Apache::lonnet::coursedescription($cid);
 2126:             if ($coursedir =~ /^$match_community$/) {
 2127:                 $class='Community';
 2128:             }
 2129:             $sortkey.="\0$coursedom";
 2130:             my $carea;
 2131:             if (defined($coursedata{'description'})) {
 2132:                 $carea=$coursedata{'description'}.
 2133:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 2134:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 2135:                 $sortkey.="\0".$coursedata{'description'};
 2136:             } else {
 2137:                 if ($class eq 'Community') {
 2138:                     $carea=&mt('Unavailable community').': '.$area;
 2139:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 2140:                 } else {
 2141:                     $carea=&mt('Unavailable course').': '.$area;
 2142:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 2143:                 }
 2144:             }
 2145:             $sortkey.="\0$coursedir";
 2146:             $inccourses->{$cid}=1;
 2147:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 2148:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 2149:                 $credits =
 2150:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 2151:                                       $coursedom,$coursedir);
 2152:                 if ($credits eq '') {
 2153:                     $credits = $defaultcredits;
 2154:                 }
 2155:             }
 2156:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 2157:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2158:                 $allowed=1;
 2159:             }
 2160:             unless ($allowed) {
 2161:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 2162:                 if ($isowner) {
 2163:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 2164:                         $allowed = 1;
 2165:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 2166:                         $allowed = 1;
 2167:                     }
 2168:                 }
 2169:             } 
 2170:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 2171:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 2172:                 $delallowed=1;
 2173:             }
 2174: # - custom role. Needs more info, too
 2175:             if ($croletitle) {
 2176:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 2177:                     $allowed=1;
 2178:                     $thisrole.='.'.$role_code;
 2179:                 }
 2180:             }
 2181:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 2182:                 $csec = $2;
 2183:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 2184:                 $sortkey.="\0$csec";
 2185:                 if (!$allowed) {
 2186:                     if ($env{'request.course.sec'} eq $csec) {
 2187:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 2188:                             $allowed = 1;
 2189:                         }
 2190:                     }
 2191:                 }
 2192:             }
 2193:             $area=$carea;
 2194:         } else {
 2195:             $sortkey.="\0".$area;
 2196:             # Determine if current user is able to revoke privileges
 2197:             if ($area=~m{^/($match_domain)/}) {
 2198:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 2199:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 2200:                    $allowed=1;
 2201:                 }
 2202:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 2203:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 2204:                     ($role_code ne 'dc')) {
 2205:                     $delallowed=1;
 2206:                 }
 2207:             } else {
 2208:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 2209:                     $allowed=1;
 2210:                 }
 2211:             }
 2212:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 2213:                 $class='Authoring Space';
 2214:             } elsif ($role_code eq 'su') {
 2215:                 $class='System';
 2216:             } else {
 2217:                 $class='Domain';
 2218:             }
 2219:         }
 2220:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 2221:             $area=~m{/($match_domain)/($match_username)};
 2222:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 2223:                 $allowed=1;
 2224:             } elsif (&Apache::lonuserutils::coauthorpriv($2,$1)) {
 2225:                 $allowed=1;
 2226:             } else {
 2227:                 $allowed=0;
 2228:             }
 2229:         }
 2230:         my $row = '';
 2231:         if ($showall) {
 2232:             $row.= '<td>';
 2233:             if (($active) && ($allowed)) {
 2234:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 2235:             } else {
 2236:                 if ($active) {
 2237:                     $row.='&nbsp;';
 2238:                 } else {
 2239:                     $row.=&mt('expired or revoked');
 2240:                 }
 2241:             }
 2242:             $row.='</td><td>';
 2243:             if ($allowed && !$active) {
 2244:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 2245:             } else {
 2246:                 $row.='&nbsp;';
 2247:             }
 2248:             $row.='</td><td>';
 2249:             if ($delallowed) {
 2250:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 2251:             } else {
 2252:                 $row.='&nbsp;';
 2253:             }
 2254:             $row.= '</td>';
 2255:         }
 2256:         my $plaintext='';
 2257:         if (!$croletitle) {
 2258:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 2259:             if (($showcredits) && ($credits ne '')) {
 2260:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 2261:                               '<span class="LC_fontsize_small">'.
 2262:                               &mt('Credits: [_1]',$credits).
 2263:                               '</span></span>';
 2264:             }
 2265:         } else {
 2266:             $plaintext=
 2267:                 &mt('Custom role [_1][_2]defined by [_3]',
 2268:                         '"'.$croletitle.'"',
 2269:                         '<br />',
 2270:                         $croleuname.':'.$croleudom);
 2271:         }
 2272:         $row.= '<td>'.$plaintext.'</td>'.
 2273:                '<td>'.$area.'</td>'.
 2274:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 2275:                                             : '&nbsp;' ).'</td>'.
 2276:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 2277:                                             : '&nbsp;' ).'</td>';
 2278:         $sortrole{$sortkey}=$envkey;
 2279:         $roletext{$envkey}=$row;
 2280:         $roleclass{$envkey}=$class;
 2281:         if ($allowed) {
 2282:             $rolepriv{$envkey}='edit';
 2283:         } else {
 2284:             if ($context eq 'domain') {
 2285:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 2286:                     ($envkey=~m{^/$ccdomain/})) {
 2287:                     $rolepriv{$envkey}='view';
 2288:                 }
 2289:             } elsif ($context eq 'course') {
 2290:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 2291:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2292:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2293:                     $rolepriv{$envkey}='view';
 2294:                 }
 2295:             }
 2296:         }
 2297:     } # end of foreach        (table building loop)
 2298: 
 2299:     my $rolesdisplay = 0;
 2300:     my %output = ();
 2301:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2302:         $output{$type} = '';
 2303:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2304:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2305:                  $output{$type}.=
 2306:                       &Apache::loncommon::start_data_table_row().
 2307:                       $roletext{$sortrole{$which}}.
 2308:                       &Apache::loncommon::end_data_table_row();
 2309:             }
 2310:         }
 2311:         unless($output{$type} eq '') {
 2312:             $output{$type} = '<tr class="LC_info_row">'.
 2313:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2314:                       $output{$type};
 2315:             $rolesdisplay = 1;
 2316:         }
 2317:     }
 2318:     if ($rolesdisplay == 1) {
 2319:         my $contextrole='';
 2320:         if ($env{'request.course.id'}) {
 2321:             if (&Apache::loncommon::course_type() eq 'Community') {
 2322:                 $contextrole = &mt('Existing Roles in this Community');
 2323:             } else {
 2324:                 $contextrole = &mt('Existing Roles in this Course');
 2325:             }
 2326:         } elsif ($env{'request.role'} =~ /^au\./) {
 2327:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2328:         } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)/$}) {
 2329:             $contextrole = &mt('Existing Co-Author Roles in [_1] Authoring Space',
 2330:                                '<i>'.$1.'_'.$2.'</i>');
 2331:         } else {
 2332:             if ($showall) {
 2333:                 $contextrole = &mt('Existing Roles in this Domain');
 2334:             } elsif ($showactive) {
 2335:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2336:             } elsif ($showexpired) {
 2337:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2338:             }
 2339:         }
 2340:         $r->print('<div class="LC_left_float">'.
 2341: '<fieldset><legend>'.$contextrole.'</legend>'.
 2342: &Apache::loncommon::start_data_table("LC_createuser").
 2343: &Apache::loncommon::start_data_table_header_row());
 2344:         if ($showall) {
 2345:             $r->print(
 2346: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2347:             );
 2348:         } elsif ($showexpired) {
 2349:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2350:         }
 2351:         $r->print(
 2352: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2353: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2354: &Apache::loncommon::end_data_table_header_row());
 2355:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2356:             if ($output{$type}) {
 2357:                 $r->print($output{$type}."\n");
 2358:             }
 2359:         }
 2360:         $r->print(&Apache::loncommon::end_data_table().
 2361:                   '</fieldset></div>');
 2362:     }
 2363:     return;
 2364: }
 2365: 
 2366: sub new_coauthor_roles {
 2367:     my ($r,$ccuname,$ccdomain) = @_;
 2368:     my $addrolesdisplay = 0;
 2369:     #
 2370:     # Co-Author
 2371:     #
 2372:     my ($cuname,$cudom);
 2373:     if (($env{'request.role'} eq "au./$env{'user.domain'}/") ||
 2374:         ($env{'request.role'} eq "dc./$env{'user.domain'}/")) {
 2375:         $cuname=$env{'user.name'};
 2376:         $cudom=$env{'request.role.domain'};
 2377:         # No sense in assigning co-author role to yourself
 2378:         if ((&Apache::lonuserutils::authorpriv($cuname,$cudom)) &&
 2379:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2380:             $addrolesdisplay = 1;
 2381:         }
 2382:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2383:         ($cudom,$cuname) = ($1,$2);
 2384:         if ((&Apache::lonuserutils::coauthorpriv($cuname,$cudom)) &&
 2385:             ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain) &&
 2386:             ($cudom ne $ccdomain || $cuname ne $ccuname)) {
 2387:             $addrolesdisplay = 1;
 2388:         }
 2389:     }
 2390:     if ($addrolesdisplay) {
 2391:         my %lt=&Apache::lonlocal::texthash(
 2392:                     'cs'   => "Authoring Space",
 2393:                     'act'  => "Activate",
 2394:                     'rol'  => "Role",
 2395:                     'ext'  => "Extent",
 2396:                     'sta'  => "Start",
 2397:                     'end'  => "End",
 2398:                     'cau'  => "Co-Author",
 2399:                     'caa'  => "Assistant Co-Author",
 2400:                     'ssd'  => "Set Start Date",
 2401:                     'sed'  => "Set End Date"
 2402:                                        );
 2403:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2404:                   &Apache::loncommon::start_data_table()."\n".
 2405:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2406:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2407:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2408:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2409:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2410:                   &Apache::loncommon::start_data_table_row().'
 2411:            <td>
 2412:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2413:            </td>
 2414:            <td>'.$lt{'cau'}.'</td>
 2415:            <td>'.$cudom.'_'.$cuname.'</td>
 2416:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2417:              <a href=
 2418: "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>
 2419: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2420: <a href=
 2421: "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".
 2422:               &Apache::loncommon::end_data_table_row()."\n".
 2423:               &Apache::loncommon::start_data_table_row()."\n".
 2424: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2425: <td>'.$lt{'caa'}.'</td>
 2426: <td>'.$cudom.'_'.$cuname.'</td>
 2427: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2428: <a href=
 2429: "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>
 2430: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2431: <a href=
 2432: "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".
 2433:              &Apache::loncommon::end_data_table_row()."\n".
 2434:              &Apache::loncommon::end_data_table());
 2435:     } elsif ($env{'request.role'} =~ /^au\./) {
 2436:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2437:                                                 $env{'request.role.domain'}))) {
 2438:             $r->print('<span class="LC_error">'.
 2439:                       &mt('You do not have privileges to assign co-author roles.').
 2440:                       '</span>');
 2441:         } elsif (($env{'user.name'} eq $ccuname) &&
 2442:              ($env{'user.domain'} eq $ccdomain)) {
 2443:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2444:         }
 2445:     } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 2446:         if (!(&Apache::lonuserutils::coauthorpriv($2,$1))) {
 2447:             $r->print('<span class="LC_error">'.
 2448:                       &mt('You do not have privileges to assign co-author roles.').
 2449:                       '</span>');
 2450:         } elsif (($env{'user.name'} eq $ccuname) &&
 2451:              ($env{'user.domain'} eq $ccdomain)) {
 2452:             $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'));
 2453:         } elsif (($cudom eq $ccdomain) && ($cuname eq $ccuname)) {
 2454:             $r->print(&mt("Assigning a co-author or assistant co-author role to an Authoring Space's author is not permitted"));
 2455:         }
 2456:     }
 2457:     return $addrolesdisplay;;
 2458: }
 2459: 
 2460: sub new_domain_roles {
 2461:     my ($r,$ccdomain) = @_;
 2462:     my $addrolesdisplay = 0;
 2463:     #
 2464:     # Domain level
 2465:     #
 2466:     my $num_domain_level = 0;
 2467:     my $domaintext =
 2468:     '<h4>'.&mt('Domain Level').'</h4>'.
 2469:     &Apache::loncommon::start_data_table().
 2470:     &Apache::loncommon::start_data_table_header_row().
 2471:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2472:     &mt('Extent').'</th>'.
 2473:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2474:     &Apache::loncommon::end_data_table_header_row();
 2475:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2476:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2477:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2478:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2479:         foreach my $role (@allroles) {
 2480:             next if ($role eq 'ad');
 2481:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2482:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2483:                if ($role eq 'dc') {
 2484:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2485:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2486:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2487:                        next unless ($uintdom eq $intdom);
 2488:                    }
 2489:                }
 2490:                my $plrole=&Apache::lonnet::plaintext($role);
 2491:                my %lt=&Apache::lonlocal::texthash(
 2492:                     'ssd'  => "Set Start Date",
 2493:                     'sed'  => "Set End Date"
 2494:                                        );
 2495:                $num_domain_level ++;
 2496:                $domaintext .=
 2497: &Apache::loncommon::start_data_table_row().
 2498: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2499: <td>'.$plrole.'</td>
 2500: <td>'.$thisdomain.'</td>
 2501: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2502: <a href=
 2503: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2504: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2505: <a href=
 2506: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2507: &Apache::loncommon::end_data_table_row();
 2508:             }
 2509:         }
 2510:     }
 2511:     $domaintext.= &Apache::loncommon::end_data_table();
 2512:     if ($num_domain_level > 0) {
 2513:         $r->print($domaintext);
 2514:         $addrolesdisplay = 1;
 2515:     }
 2516:     return $addrolesdisplay;
 2517: }
 2518: 
 2519: sub user_authentication {
 2520:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2521:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2522:     my $outcome;
 2523:     my %lt=&Apache::lonlocal::texthash(
 2524:                    'err'   => "ERROR",
 2525:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2526:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2527:                    'sldb'  => "Please specify login data below",
 2528:                    'ld'    => "Login Data"
 2529:     );
 2530:     # Check for a bad authentication type
 2531:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2532:         # bad authentication scheme
 2533:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2534:             &initialize_authen_forms($ccdomain,$formname);
 2535: 
 2536:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2537:             $outcome = <<ENDBADAUTH;
 2538: <script type="text/javascript" language="Javascript">
 2539: // <![CDATA[
 2540: $loginscript
 2541: // ]]>
 2542: </script>
 2543: <span class="LC_error">$lt{'err'}:
 2544: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2545: <h3>$lt{'ld'}</h3>
 2546: $choices
 2547: ENDBADAUTH
 2548:         } else {
 2549:             # This user is not allowed to modify the user's
 2550:             # authentication scheme, so just notify them of the problem
 2551:             $outcome = <<ENDBADAUTH;
 2552: <span class="LC_error"> $lt{'err'}: 
 2553: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2554: </span>
 2555: ENDBADAUTH
 2556:         }
 2557:     } else { # Authentication type is valid
 2558:         
 2559:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2560:         my ($authformcurrent,$can_modify,@authform_others) =
 2561:             &modify_login_block($ccdomain,$currentauth);
 2562:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2563:             # Current user has login modification privileges
 2564:             $outcome =
 2565:                        '<script type="text/javascript" language="Javascript">'."\n".
 2566:                        '// <![CDATA['."\n".
 2567:                        $loginscript."\n".
 2568:                        '// ]]>'."\n".
 2569:                        '</script>'."\n".
 2570:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2571:                        &Apache::loncommon::start_data_table().
 2572:                        &Apache::loncommon::start_data_table_row().
 2573:                        '<td>'.$authformnop;
 2574:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2575:                 $outcome .= '</td>'."\n".
 2576:                             &Apache::loncommon::end_data_table_row().
 2577:                             &Apache::loncommon::start_data_table_row().
 2578:                             '<td>'.$authformcurrent.'</td>'.
 2579:                             &Apache::loncommon::end_data_table_row()."\n";
 2580:             } else {
 2581:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2582:                             &Apache::loncommon::end_data_table_row()."\n";
 2583:             }
 2584:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2585:                 foreach my $item (@authform_others) { 
 2586:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2587:                                 '<td>'.$item.'</td>'.
 2588:                                 &Apache::loncommon::end_data_table_row()."\n";
 2589:                 }
 2590:             }
 2591:             $outcome .= &Apache::loncommon::end_data_table();
 2592:         } else {
 2593:             if (($currentauth =~ /^internal:/) &&
 2594:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2595:                 $outcome = <<"ENDJS";
 2596: <script type="text/javascript">
 2597: // <![CDATA[
 2598: function togglePwd(form) {
 2599:     if (form.newintpwd.length) {
 2600:         if (document.getElementById('LC_ownersetpwd')) {
 2601:             for (var i=0; i<form.newintpwd.length; i++) {
 2602:                 if (form.newintpwd[i].checked) {
 2603:                     if (form.newintpwd[i].value == 1) {
 2604:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2605:                     } else {
 2606:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2607:                     }
 2608:                 }
 2609:             }
 2610:         }
 2611:     }
 2612: }
 2613: // ]]>
 2614: </script>
 2615: ENDJS
 2616: 
 2617:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2618:                             &Apache::loncommon::start_data_table().
 2619:                             &Apache::loncommon::start_data_table_row().
 2620:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2621:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2622:                             &mt('No').'</label>'.('&nbsp;'x2).
 2623:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2624:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2625:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2626:                             '<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>'.
 2627:                             &Apache::loncommon::end_data_table_row().
 2628:                             &Apache::loncommon::end_data_table();
 2629:             }
 2630:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2631:                 # Current user has rights to view domain preferences for user's domain
 2632:                 my $result;
 2633:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2634:                     my ($krbver,$krbrealm) = ($1,$2);
 2635:                     if ($krbrealm eq '') {
 2636:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2637:                     } else {
 2638:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2639:                                       $krbrealm,$krbver);
 2640:                     }
 2641:                 } elsif ($currentauth =~ /^internal:/) {
 2642:                     $result = &mt('Currently internally authenticated.');
 2643:                 } elsif ($currentauth =~ /^localauth:/) {
 2644:                     $result = &mt('Currently using local (institutional) authentication.');
 2645:                 } elsif ($currentauth =~ /^unix:/) {
 2646:                     $result = &mt('Currently Filesystem Authenticated.');
 2647:                 } elsif ($currentauth =~ /^lti:/) {
 2648:                     $result = &mt('Currently LTI authenticated.');
 2649:                 }
 2650:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2651:                            &Apache::loncommon::start_data_table().
 2652:                            &Apache::loncommon::start_data_table_row().
 2653:                            '<td>'.$result.'</td>'.
 2654:                            &Apache::loncommon::end_data_table_row()."\n".
 2655:                            &Apache::loncommon::end_data_table();
 2656:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2657:                 my %lt=&Apache::lonlocal::texthash(
 2658:                            'ccld'  => "Change Current Login Data",
 2659:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2660:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2661:                 );
 2662:                 $outcome .= <<ENDNOPRIV;
 2663: <h3>$lt{'ccld'}</h3>
 2664: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2665: <input type="hidden" name="login" value="nochange" />
 2666: ENDNOPRIV
 2667:             }
 2668:         }
 2669:     }  ## End of "check for bad authentication type" logic
 2670:     return $outcome;
 2671: }
 2672: 
 2673: sub modify_login_block {
 2674:     my ($dom,$currentauth) = @_;
 2675:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2676:     my ($authnum,%can_assign) =
 2677:         &Apache::loncommon::get_assignable_auth($dom);
 2678:     my ($authformcurrent,@authform_others,$show_override_msg);
 2679:     if ($currentauth=~/^krb(4|5):/) {
 2680:         $authformcurrent=$authformkrb;
 2681:         if ($can_assign{'int'}) {
 2682:             push(@authform_others,$authformint);
 2683:         }
 2684:         if ($can_assign{'loc'}) {
 2685:             push(@authform_others,$authformloc);
 2686:         }
 2687:         if ($can_assign{'lti'}) {
 2688:             push(@authform_others,$authformlti);
 2689:         }
 2690:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2691:             $show_override_msg = 1;
 2692:         }
 2693:     } elsif ($currentauth=~/^internal:/) {
 2694:         $authformcurrent=$authformint;
 2695:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2696:             push(@authform_others,$authformkrb);
 2697:         }
 2698:         if ($can_assign{'loc'}) {
 2699:             push(@authform_others,$authformloc);
 2700:         }
 2701:         if ($can_assign{'lti'}) {
 2702:             push(@authform_others,$authformlti);
 2703:         }
 2704:         if ($can_assign{'int'}) {
 2705:             $show_override_msg = 1;
 2706:         }
 2707:     } elsif ($currentauth=~/^unix:/) {
 2708:         $authformcurrent=$authformfsys;
 2709:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2710:             push(@authform_others,$authformkrb);
 2711:         }
 2712:         if ($can_assign{'int'}) {
 2713:             push(@authform_others,$authformint);
 2714:         }
 2715:         if ($can_assign{'loc'}) {
 2716:             push(@authform_others,$authformloc);
 2717:         }
 2718:         if ($can_assign{'lti'}) {
 2719:             push(@authform_others,$authformlti);
 2720:         }
 2721:         if ($can_assign{'fsys'}) {
 2722:             $show_override_msg = 1;
 2723:         }
 2724:     } elsif ($currentauth=~/^localauth:/) {
 2725:         $authformcurrent=$authformloc;
 2726:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2727:             push(@authform_others,$authformkrb);
 2728:         }
 2729:         if ($can_assign{'int'}) {
 2730:             push(@authform_others,$authformint);
 2731:         }
 2732:         if ($can_assign{'lti'}) {
 2733:             push(@authform_others,$authformlti);
 2734:         }
 2735:         if ($can_assign{'loc'}) {
 2736:             $show_override_msg = 1;
 2737:         }
 2738:     } elsif ($currentauth=~/^lti:/) {
 2739:         $authformcurrent=$authformlti;
 2740:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2741:             push(@authform_others,$authformkrb);
 2742:         }
 2743:         if ($can_assign{'int'}) {
 2744:             push(@authform_others,$authformint);
 2745:         }
 2746:         if ($can_assign{'loc'}) {
 2747:             push(@authform_others,$authformloc);
 2748:         }
 2749:     }
 2750:     if ($show_override_msg) {
 2751:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2752:                            '</td></tr>'."\n".
 2753:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2754:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2755:                            '<td align="right"><span class="LC_cusr_emph">'.
 2756:                             &mt('will override current values').
 2757:                             '</span></td></tr></table>';
 2758:     }
 2759:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2760: }
 2761: 
 2762: sub personal_data_display {
 2763:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$readonly,$rolesarray,$now,
 2764:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2765:     my ($output,%userenv,%canmodify,%canmodify_status,$disabled);
 2766:     my @userinfo = ('firstname','middlename','lastname','generation',
 2767:                     'permanentemail','id');
 2768:     my $rowcount = 0;
 2769:     my $editable = 0;
 2770:     my %textboxsize = (
 2771:                        firstname      => '15',
 2772:                        middlename     => '15',
 2773:                        lastname       => '15',
 2774:                        generation     => '5',
 2775:                        permanentemail => '25',
 2776:                        id             => '15',
 2777:                       );
 2778: 
 2779:     my %lt=&Apache::lonlocal::texthash(
 2780:                 'pd'             => "Personal Data",
 2781:                 'firstname'      => "First Name",
 2782:                 'middlename'     => "Middle Name",
 2783:                 'lastname'       => "Last Name",
 2784:                 'generation'     => "Generation",
 2785:                 'permanentemail' => "Permanent e-mail address",
 2786:                 'id'             => "Student/Employee ID",
 2787:                 'lg'             => "Login Data",
 2788:                 'inststatus'     => "Affiliation",
 2789:                 'email'          => 'E-mail address',
 2790:                 'valid'          => 'Validation',
 2791:                 'username'       => 'Username',
 2792:     );
 2793: 
 2794:     %canmodify_status =
 2795:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2796:                                                    ['inststatus'],$rolesarray);
 2797:     if (!$newuser) {
 2798:         # Get the users information
 2799:         %userenv = &Apache::lonnet::get('environment',
 2800:                    ['firstname','middlename','lastname','generation',
 2801:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2802:         %canmodify =
 2803:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2804:                                                        \@userinfo,$rolesarray);
 2805:     } elsif ($context eq 'selfcreate') {
 2806:         if ($newuser eq 'email') {
 2807:             if (ref($emailusername) eq 'HASH') {
 2808:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2809:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2810:                     @userinfo = ();
 2811:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2812:                         foreach my $field (@{$infofields}) { 
 2813:                             if ($emailusername->{$usertype}->{$field}) {
 2814:                                 push(@userinfo,$field);
 2815:                                 $canmodify{$field} = 1;
 2816:                                 unless ($textboxsize{$field}) {
 2817:                                     $textboxsize{$field} = 25;
 2818:                                 }
 2819:                                 unless ($lt{$field}) {
 2820:                                     $lt{$field} = $infotitles->{$field};
 2821:                                 }
 2822:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2823:                                     $lt{$field} .= '<b>*</b>';
 2824:                                 }
 2825:                             }
 2826:                         }
 2827:                     }
 2828:                 }
 2829:             }
 2830:         } else {
 2831:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2832:                                                $inst_results,$rolesarray);
 2833:         }
 2834:     } elsif ($readonly) {
 2835:         $disabled = ' disabled="disabled"';
 2836:     }
 2837: 
 2838:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2839:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2840:               &Apache::lonhtmlcommon::start_pick_box();
 2841:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2842:         my $size = 25;
 2843:         if ($condition) {
 2844:             if ($condition =~ /^\@[^\@]+$/) {
 2845:                 $size = 10;
 2846:             } else {
 2847:                 undef($condition);
 2848:             }
 2849:         } 
 2850:         if ($excluded) {
 2851:             unless ($excluded =~ /^\@[^\@]+$/) {
 2852:                 undef($condition);
 2853:             }
 2854:         }
 2855:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2856:                                                      'LC_oddrow_value')."\n".
 2857:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2858:         if ($condition) {
 2859:             $output .= $condition;
 2860:         } elsif ($excluded) {
 2861:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2862:                                                                      $excluded).'</span>';
 2863:         }
 2864:         if ($usernameset eq 'first') {
 2865:             $output .= '<br /><span style="font-size: smaller">';
 2866:             if ($condition) {
 2867:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2868:                                       $condition);
 2869:             } else {
 2870:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2871:             }
 2872:             $output .= '</span>';
 2873:         }
 2874:         $rowcount ++;
 2875:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2876:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="new-password" />';
 2877:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="new-password" />';
 2878:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2879:                                                     'LC_pick_box_title',
 2880:                                                     'LC_oddrow_value')."\n".
 2881:                    $upassone."\n".
 2882:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2883:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2884:                                                      'LC_pick_box_title',
 2885:                                                      'LC_oddrow_value')."\n".
 2886:                    $upasstwo.
 2887:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2888:         if ($usernameset eq 'free') {
 2889:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2890:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2891:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2892:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2893:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2894:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2895:                        &mt('No').'</label></span>'."\n".
 2896:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2897:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2898:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2899:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2900:             $rowcount ++;
 2901:         }
 2902:     }
 2903:     foreach my $item (@userinfo) {
 2904:         my $rowtitle = $lt{$item};
 2905:         my $hiderow = 0;
 2906:         if ($item eq 'generation') {
 2907:             $rowtitle = $genhelp.$rowtitle;
 2908:         }
 2909:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2910:         if ($newuser) {
 2911:             if (ref($inst_results) eq 'HASH') {
 2912:                 if ($inst_results->{$item} ne '') {
 2913:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2914:                 } else {
 2915:                     if ($context eq 'selfcreate') {
 2916:                         if ($canmodify{$item}) {
 2917:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2918:                             $editable ++;
 2919:                         } else {
 2920:                             $hiderow = 1;
 2921:                         }
 2922:                     } else {
 2923:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2924:                     }
 2925:                 }
 2926:             } else {
 2927:                 if ($context eq 'selfcreate') {
 2928:                     if ($canmodify{$item}) {
 2929:                         if ($newuser eq 'email') {
 2930:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2931:                         } else {
 2932:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2933:                         }
 2934:                         $editable ++;
 2935:                     } else {
 2936:                         $hiderow = 1;
 2937:                     }
 2938:                 } else {
 2939:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value=""'.$disabled.' />';
 2940:                 }
 2941:             }
 2942:         } else {
 2943:             if ($canmodify{$item}) {
 2944:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2945:                 if (($item eq 'id') && (!$newuser)) {
 2946:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2947:                 }
 2948:             } else {
 2949:                 $row .= $userenv{$item};
 2950:             }
 2951:         }
 2952:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2953:         if (!$hiderow) {
 2954:             $output .= $row;
 2955:             $rowcount ++;
 2956:         }
 2957:     }
 2958:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2959:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2960:         if (ref($types) eq 'ARRAY') {
 2961:             if (@{$types} > 0) {
 2962:                 my ($hiderow,$shown);
 2963:                 if ($canmodify_status{'inststatus'}) {
 2964:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2965:                 } else {
 2966:                     if ($userenv{'inststatus'} eq '') {
 2967:                         $hiderow = 1;
 2968:                     } else {
 2969:                         my @showitems;
 2970:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2971:                             if (exists($usertypes->{$item})) {
 2972:                                 push(@showitems,$usertypes->{$item});
 2973:                             } else {
 2974:                                 push(@showitems,$item);
 2975:                             }
 2976:                         }
 2977:                         if (@showitems) {
 2978:                             $shown = join(', ',@showitems);
 2979:                         } else {
 2980:                             $hiderow = 1;
 2981:                         }
 2982:                     }
 2983:                 }
 2984:                 if (!$hiderow) {
 2985:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2986:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2987:                     if ($context eq 'selfcreate') {
 2988:                         $rowcount ++;
 2989:                     }
 2990:                     $output .= $row;
 2991:                 }
 2992:             }
 2993:         }
 2994:     }
 2995:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2996:         if ($captchaform) {
 2997:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2998:                                                          'LC_pick_box_title')."\n".
 2999:                        $captchaform."\n".'<br /><br />'.
 3000:                        &Apache::lonhtmlcommon::row_closure(1); 
 3001:             $rowcount ++;
 3002:         }
 3003:         if ($showsubmit) {
 3004:             my $submit_text = &mt('Create account');
 3005:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 3006:                        '<br /><input type="submit" name="createaccount" value="'.
 3007:                        $submit_text.'" />';
 3008:             if ($usertype ne '') {
 3009:                 $output .= '<input type="hidden" name="type" value="'.
 3010:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 3011:             }
 3012:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 3013:         }
 3014:     }
 3015:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 3016:     if (wantarray) {
 3017:         if ($context eq 'selfcreate') {
 3018:             return($output,$rowcount,$editable);
 3019:         } else {
 3020:             return $output;
 3021:         }
 3022:     } else {
 3023:         return $output;
 3024:     }
 3025: }
 3026: 
 3027: sub pick_inst_statuses {
 3028:     my ($curr,$usertypes,$types) = @_;
 3029:     my ($output,$rem,@currtypes);
 3030:     if ($curr ne '') {
 3031:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 3032:     }
 3033:     my $numinrow = 2;
 3034:     if (ref($types) eq 'ARRAY') {
 3035:         $output = '<table>';
 3036:         my $lastcolspan; 
 3037:         for (my $i=0; $i<@{$types}; $i++) {
 3038:             if (defined($usertypes->{$types->[$i]})) {
 3039:                 my $rem = $i%($numinrow);
 3040:                 if ($rem == 0) {
 3041:                     if ($i<@{$types}-1) {
 3042:                         if ($i > 0) { 
 3043:                             $output .= '</tr>';
 3044:                         }
 3045:                         $output .= '<tr>';
 3046:                     }
 3047:                 } elsif ($i==@{$types}-1) {
 3048:                     my $colsleft = $numinrow - $rem;
 3049:                     if ($colsleft > 1) {
 3050:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 3051:                     }
 3052:                 }
 3053:                 my $check = ' ';
 3054:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 3055:                     $check = ' checked="checked" ';
 3056:                 }
 3057:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 3058:                            '<span class="LC_nobreak"><label>'.
 3059:                            '<input type="checkbox" name="inststatus" '.
 3060:                            'value="'.$types->[$i].'"'.$check.'/>'.
 3061:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 3062:             }
 3063:         }
 3064:         $output .= '</tr></table>';
 3065:     }
 3066:     return $output;
 3067: }
 3068: 
 3069: sub selfcreate_canmodify {
 3070:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 3071:     if (ref($inst_results) eq 'HASH') {
 3072:         my @inststatuses = &get_inststatuses($inst_results);
 3073:         if (@inststatuses == 0) {
 3074:             @inststatuses = ('default');
 3075:         }
 3076:         $rolesarray = \@inststatuses;
 3077:     }
 3078:     my %canmodify =
 3079:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 3080:                                                    $rolesarray);
 3081:     return %canmodify;
 3082: }
 3083: 
 3084: sub get_inststatuses {
 3085:     my ($insthashref) = @_;
 3086:     my @inststatuses = ();
 3087:     if (ref($insthashref) eq 'HASH') {
 3088:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 3089:             @inststatuses = @{$insthashref->{'inststatus'}};
 3090:         }
 3091:     }
 3092:     return @inststatuses;
 3093: }
 3094: 
 3095: # ================================================================= Phase Three
 3096: sub update_user_data {
 3097:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 3098:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 3099:                                           $env{'form.ccdomain'});
 3100:     # Error messages
 3101:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 3102:     my $end       = '</span><br /><br />';
 3103:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 3104:                     "'$env{'form.prevphase'}','modify')".'" />'.
 3105:                     &mt('Return to previous page').'</a>'.
 3106:                     &Apache::loncommon::end_page();
 3107:     my $now = time;
 3108:     my $title;
 3109:     if (exists($env{'form.makeuser'})) {
 3110: 	$title='Set Privileges for New User';
 3111:     } else {
 3112:         $title='Modify User Privileges';
 3113:     }
 3114:     my $newuser = 0;
 3115:     my ($jsback,$elements) = &crumb_utilities();
 3116:     my $jscript = '<script type="text/javascript">'."\n".
 3117:                   '// <![CDATA['."\n".
 3118:                   $jsback."\n".
 3119:                   '// ]]>'."\n".
 3120:                   '</script>'."\n";
 3121:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 3122:     push (@{$brcrum},
 3123:              {href => "javascript:backPage(document.userupdate)",
 3124:               text => $breadcrumb_text{'search'},
 3125:               faq  => 282,
 3126:               bug  => 'Instructor Interface',}
 3127:              );
 3128:     if ($env{'form.prevphase'} eq 'userpicked') {
 3129:         push(@{$brcrum},
 3130:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 3131:                 text => $breadcrumb_text{'userpicked'},
 3132:                 faq  => 282,
 3133:                 bug  => 'Instructor Interface',});
 3134:     }
 3135:     my $helpitem = 'Course_Change_Privileges';
 3136:     if ($env{'form.action'} eq 'singlestudent') {
 3137:         $helpitem = 'Course_Add_Student';
 3138:     } elsif ($context eq 'author') {
 3139:         $helpitem = 'Author_Change_Privileges';
 3140:     } elsif ($context eq 'domain') {
 3141:         $helpitem = 'Domain_Change_Privileges';
 3142:     }
 3143:     push(@{$brcrum}, 
 3144:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 3145:              text => $breadcrumb_text{'modify'},
 3146:              faq  => 282,
 3147:              bug  => 'Instructor Interface',},
 3148:             {href => "/adm/createuser",
 3149:              text => "Result",
 3150:              faq  => 282,
 3151:              bug  => 'Instructor Interface',
 3152:              help => $helpitem});
 3153:     my $args = {bread_crumbs          => $brcrum,
 3154:                 bread_crumbs_component => 'User Management'};
 3155:     if ($env{'form.popup'}) {
 3156:         $args->{'no_nav_bar'} = 1;
 3157:     }
 3158:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 3159:     $r->print(&update_result_form($uhome));
 3160:     # Check Inputs
 3161:     if (! $env{'form.ccuname'} ) {
 3162: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 3163: 	return;
 3164:     }
 3165:     if (  $env{'form.ccuname'} ne 
 3166: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 3167: 	$r->print($error.&mt('Invalid login name.').'  '.
 3168: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 3169: 		  $end.$rtnlink);
 3170: 	return;
 3171:     }
 3172:     if (! $env{'form.ccdomain'}       ) {
 3173: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 3174: 	return;
 3175:     }
 3176:     if (  $env{'form.ccdomain'} ne
 3177: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 3178: 	$r->print($error.&mt('Invalid domain name.').'  '.
 3179: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 3180: 		  $end.$rtnlink);
 3181: 	return;
 3182:     }
 3183:     if ($uhome eq 'no_host') {
 3184:         $newuser = 1;
 3185:     }
 3186:     if (! exists($env{'form.makeuser'})) {
 3187:         # Modifying an existing user, so check the validity of the name
 3188:         if ($uhome eq 'no_host') {
 3189:             $r->print(
 3190:                 $error
 3191:                .'<p class="LC_error">'
 3192:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 3193:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 3194:                .'</p>');
 3195:             return;
 3196:         }
 3197:     }
 3198:     # Determine authentication method and password for the user being modified
 3199:     my $amode='';
 3200:     my $genpwd='';
 3201:     if ($env{'form.login'} eq 'krb') {
 3202: 	$amode='krb';
 3203: 	$amode.=$env{'form.krbver'};
 3204: 	$genpwd=$env{'form.krbarg'};
 3205:     } elsif ($env{'form.login'} eq 'int') {
 3206: 	$amode='internal';
 3207: 	$genpwd=$env{'form.intarg'};
 3208:     } elsif ($env{'form.login'} eq 'fsys') {
 3209: 	$amode='unix';
 3210: 	$genpwd=$env{'form.fsysarg'};
 3211:     } elsif ($env{'form.login'} eq 'loc') {
 3212: 	$amode='localauth';
 3213: 	$genpwd=$env{'form.locarg'};
 3214: 	$genpwd=" " if (!$genpwd);
 3215:     } elsif ($env{'form.login'} eq 'lti') {
 3216:         $amode='lti';
 3217:         $genpwd=" ";
 3218:     } elsif (($env{'form.login'} eq 'nochange') ||
 3219:              ($env{'form.login'} eq ''        )) { 
 3220:         # There is no need to tell the user we did not change what they
 3221:         # did not ask us to change.
 3222:         # If they are creating a new user but have not specified login
 3223:         # information this will be caught below.
 3224:     } else {
 3225:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 3226:             return;
 3227:     }
 3228: 
 3229:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 3230:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 3231:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 3232:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 3233: 
 3234:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 3235:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3236:     my @usertools = ('aboutme','blog','portfolio','portaccess','timezone');
 3237:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 3238:     my @requestauthor = ('requestauthor');
 3239:     my @authordefaults = ('webdav','editors','archive');
 3240:     my ($othertitle,$usertypes,$types) = 
 3241:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 3242:     my %canmodify_status =
 3243:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 3244:                                                    ['inststatus']);
 3245:     if ($env{'form.makeuser'}) {
 3246: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 3247:         # Check for the authentication mode and password
 3248:         if (! $amode || ! $genpwd) {
 3249: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 3250: 	    return;
 3251: 	}
 3252:         # Determine desired host
 3253:         my $desiredhost = $env{'form.hserver'};
 3254:         if (lc($desiredhost) eq 'default') {
 3255:             $desiredhost = undef;
 3256:         } else {
 3257:             my %home_servers = 
 3258: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 3259:             if (! exists($home_servers{$desiredhost})) {
 3260:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 3261:                 return;
 3262:             }
 3263:         }
 3264:         # Check ID format
 3265:         my %checkhash;
 3266:         my %checks = ('id' => 1);
 3267:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 3268:             'newuser' => $newuser, 
 3269:             'id' => $env{'form.cid'},
 3270:         );
 3271:         if ($env{'form.cid'} ne '') {
 3272:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 3273:                                           \%rulematch,\%inst_results,\%curr_rules);
 3274:             if (ref($alerts{'id'}) eq 'HASH') {
 3275:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3276:                     my $domdesc =
 3277:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 3278:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 3279:                         my $userchkmsg;
 3280:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 3281:                             $userchkmsg  = 
 3282:                                 &Apache::loncommon::instrule_disallow_msg('id',
 3283:                                                                     $domdesc,1).
 3284:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 3285:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 3286:                         }
 3287:                         $r->print($error.&mt('Invalid ID format').$end.
 3288:                                   $userchkmsg.$rtnlink);
 3289:                         return;
 3290:                     }
 3291:                 }
 3292:             }
 3293:         }
 3294:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 3295: 	# Call modifyuser
 3296: 	my $result = &Apache::lonnet::modifyuser
 3297: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 3298:              $amode,$genpwd,$env{'form.cfirstname'},
 3299:              $env{'form.cmiddlename'},$env{'form.clastname'},
 3300:              $env{'form.cgeneration'},undef,$desiredhost,
 3301:              $env{'form.cpermanentemail'});
 3302: 	$r->print(&mt('Generating user').': '.$result);
 3303:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 3304:                                                $env{'form.ccdomain'});
 3305:         my (%changeHash,%newcustom,%changed,%changedinfo);
 3306:         if ($uhome ne 'no_host') {
 3307:             if ($context eq 'domain') {
 3308:                 foreach my $name ('portfolio','author') {
 3309:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3310:                         if ($env{'form.'.$name.'quota'} eq '') {
 3311:                             $newcustom{$name.'quota'} = 0;
 3312:                         } else {
 3313:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 3314:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 3315:                         }
 3316:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 3317:                             $changed{$name.'quota'} = 1;
 3318:                         }
 3319:                     }
 3320:                 }
 3321:                 foreach my $item (@usertools) {
 3322:                     if ($env{'form.custom'.$item} == 1) {
 3323:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3324:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3325:                                                      \%changeHash,'tools');
 3326:                     }
 3327:                 }
 3328:                 foreach my $item (@requestcourses) {
 3329:                     if ($env{'form.custom'.$item} == 1) {
 3330:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3331:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3332:                             $newcustom{$item} .= '=';
 3333:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3334:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3335:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3336:                             }
 3337:                         }
 3338:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3339:                                                       \%changeHash,'requestcourses');
 3340:                     }
 3341:                 }
 3342:                 if ($env{'form.customrequestauthor'} == 1) {
 3343:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3344:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3345:                                                     $newcustom{'requestauthor'},
 3346:                                                     \%changeHash,'requestauthor');
 3347:                 }
 3348:                 if ($env{'form.customeditors'} == 1) {
 3349:                     my @editors;
 3350:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 3351:                     if (@posseditors) {
 3352:                         foreach my $editor (@posseditors) {
 3353:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 3354:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 3355:                                     push(@editors,$editor);
 3356:                                 }
 3357:                             }
 3358:                         }
 3359:                     }
 3360:                     if (@editors) {
 3361:                         @editors = sort(@editors);
 3362:                         $changed{'editors'} = &tool_admin('editors',join(',',@editors),
 3363:                                                           \%changeHash,'authordefaults');
 3364:                     }
 3365:                 }
 3366:                 if ($env{'form.customwebdav'} == 1) {
 3367:                     $newcustom{'webdav'} = $env{'form.authordefaults_webdav'};
 3368:                     $changed{'webdav'} = &tool_admin('webdav',$newcustom{'webdav'},
 3369:                                                   \%changeHash,'authordefaults');
 3370:                 }
 3371:                 if ($env{'for.customarchive'} == 1) {
 3372:                     $newcustom{'archive'} = $env{'form.authordefaults_archive'};
 3373:                     $changed{'archive'} = &tool_admin('archive',$newcustom{'archive'},
 3374:                                                   \%changeHash,'authordefaults');
 3375: 
 3376:                 }
 3377:             }
 3378:             if ($canmodify_status{'inststatus'}) {
 3379:                 if (exists($env{'form.inststatus'})) {
 3380:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3381:                     if (@inststatuses > 0) {
 3382:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3383:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3384:                     }
 3385:                 }
 3386:             }
 3387:             if (keys(%changed)) {
 3388:                 foreach my $item (@userinfo) {
 3389:                     $changeHash{$item}  = $env{'form.c'.$item};
 3390:                 }
 3391:                 my $chgresult =
 3392:                      &Apache::lonnet::put('environment',\%changeHash,
 3393:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3394:             }
 3395:         }
 3396:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3397:                   &Apache::lonnet::hostname($uhome));
 3398:     } elsif (($env{'form.login'} ne 'nochange') &&
 3399:              ($env{'form.login'} ne ''        )) {
 3400: 	# Modify user privileges
 3401:         if (! $amode || ! $genpwd) {
 3402: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3403: 	    return;
 3404: 	}
 3405: 	# Only allow authentication modification if the person has authority
 3406: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3407: 	    $r->print('Modifying authentication: '.
 3408:                       &Apache::lonnet::modifyuserauth(
 3409: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3410:                        $amode,$genpwd));
 3411:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3412: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3413: 	} else {
 3414: 	    # Okay, this is a non-fatal error.
 3415: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3416: 	}
 3417:     } elsif (($env{'form.intarg'} ne '') &&
 3418:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3419:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3420:         $r->print('Modifying authentication: '.
 3421:                   &Apache::lonnet::modifyuserauth(
 3422:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3423:                   'internal',$env{'form.intarg'}));
 3424:     }
 3425:     $r->rflush(); # Finish display of header before time consuming actions start
 3426:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3427:     ##
 3428:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3429:     if ($context eq 'course') {
 3430:         ($cnum,$cdom) =
 3431:             &Apache::lonuserutils::get_course_identity();
 3432:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3433:         if ($showcredits) {
 3434:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3435:         }
 3436:     }
 3437:     if (! $env{'form.makeuser'} ) {
 3438:         # Check for need to change
 3439:         my %userenv = &Apache::lonnet::get
 3440:             ('environment',['firstname','middlename','lastname','generation',
 3441:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3442:              'tools.aboutme','tools.blog','tools.webdav',
 3443:              'tools.portfolio','tools.timezone','tools.portaccess',
 3444:              'authormanagers','authoreditors','authorarchive','requestauthor',
 3445:              'requestcourses.official','requestcourses.unofficial',
 3446:              'requestcourses.community','requestcourses.textbook',
 3447:              'requestcourses.placement','requestcourses.lti',
 3448:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3449:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3450:              'reqcrsotherdom.placement','domcoord.author'],
 3451:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3452:         my ($tmp) = keys(%userenv);
 3453:         if ($tmp =~ /^(con_lost|error)/i) { 
 3454:             %userenv = ();
 3455:         }
 3456:         unless (($userenv{'domcoord.author'} eq 'blocked') &&
 3457:                 (($env{'user.name'} ne $env{'form.ccuname'}) ||
 3458:                  ($env{'user.domain'} ne $env{'form.ccdomain'}))) {
 3459:             push(@authordefaults,'managers');
 3460:         }
 3461:         my $no_forceid_alert;
 3462:         # Check to see if user information can be changed
 3463:         my %domconfig =
 3464:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3465:                                      $env{'form.ccdomain'});
 3466:         my @statuses = ('active','future');
 3467:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3468:         my ($auname,$audom);
 3469:         if ($context eq 'author') {
 3470:             $auname = $env{'user.name'};
 3471:             $audom = $env{'user.domain'};     
 3472:         }
 3473:         foreach my $item (keys(%roles)) {
 3474:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3475:             if ($context eq 'course') {
 3476:                 if ($cnum ne '' && $cdom ne '') {
 3477:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3478:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3479:                             push(@userroles,$role);
 3480:                         }
 3481:                     }
 3482:                 }
 3483:             } elsif ($context eq 'author') {
 3484:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3485:                     if (!grep(/^\Q$role\E$/,@userroles)) {
 3486:                         push(@userroles,$role);
 3487:                     }
 3488:                 }
 3489:             }
 3490:         }
 3491:         if ($env{'form.action'} eq 'singlestudent') {
 3492:             if (!grep(/^st$/,@userroles)) {
 3493:                 push(@userroles,'st');
 3494:             }
 3495:         } else {
 3496:             # Check for course or co-author roles being activated or re-enabled
 3497:             if ($context eq 'author' || $context eq 'course') {
 3498:                 foreach my $key (keys(%env)) {
 3499:                     if ($context eq 'author') {
 3500:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3501:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3502:                                 push(@userroles,$1);
 3503:                             }
 3504:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3505:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3506:                                 push(@userroles,$1);
 3507:                             }
 3508:                         }
 3509:                     } elsif ($context eq 'course') {
 3510:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3511:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3512:                                 push(@userroles,$1);
 3513:                             }
 3514:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3515:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3516:                                 push(@userroles,$1);
 3517:                             }
 3518:                         }
 3519:                     }
 3520:                 }
 3521:             }
 3522:         }
 3523:         #Check to see if we can change personal data for the user 
 3524:         my (@mod_disallowed,@longroles);
 3525:         foreach my $role (@userroles) {
 3526:             if ($role eq 'cr') {
 3527:                 push(@longroles,'Custom');
 3528:             } else {
 3529:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3530:             }
 3531:         }
 3532:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3533:         foreach my $item (@userinfo) {
 3534:             # Strip leading and trailing whitespace
 3535:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3536:             if (!$canmodify{$item}) {
 3537:                 if (defined($env{'form.c'.$item})) {
 3538:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3539:                         push(@mod_disallowed,$item);
 3540:                     }
 3541:                 }
 3542:                 $env{'form.c'.$item} = $userenv{$item};
 3543:             }
 3544:         }
 3545:         # Check to see if we can change the Student/Employee ID
 3546:         my $forceid = $env{'form.forceid'};
 3547:         my $recurseid = $env{'form.recurseid'};
 3548:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3549:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3550:                                             $env{'form.ccuname'});
 3551:         if (($uidhash{$env{'form.ccuname'}}) && 
 3552:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3553:             (!$forceid)) {
 3554:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3555:                 $env{'form.cid'} = $userenv{'id'};
 3556:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3557:                                    .'<br />'
 3558:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3559:                                    .'<br />'."\n";
 3560:             }
 3561:         }
 3562:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3563:             my $checkhash;
 3564:             my $checks = { 'id' => 1 };
 3565:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3566:                    { 'newuser' => $newuser,
 3567:                      'id'  => $env{'form.cid'}, 
 3568:                    };
 3569:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3570:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3571:             if (ref($alerts{'id'}) eq 'HASH') {
 3572:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3573:                    $env{'form.cid'} = $userenv{'id'};
 3574:                 }
 3575:             }
 3576:         }
 3577:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3578:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3579:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3580:             %oldsettingstatus,%newsettingstatus);
 3581:         @disporder = ('inststatus');
 3582:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3583:             push(@disporder,('requestcourses','requestauthor','authordefaults'));
 3584:         } else {
 3585:             push(@disporder,'reqcrsotherdom');
 3586:         }
 3587:         push(@disporder,('quota','tools'));
 3588:         $oldinststatus = $userenv{'inststatus'};
 3589:         foreach my $name ('portfolio','author') {
 3590:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3591:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3592:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3593:         }
 3594:         my %canshow;
 3595:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3596:             $canshow{'quota'} = 1;
 3597:         }
 3598:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3599:             $canshow{'tools'} = 1;
 3600:         }
 3601:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3602:             $canshow{'requestcourses'} = 1;
 3603:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3604:             $canshow{'reqcrsotherdom'} = 1;
 3605:         }
 3606:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3607:             $canshow{'inststatus'} = 1;
 3608:         }
 3609:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3610:             $canshow{'requestauthor'} = 1;
 3611:             $canshow{'authordefaults'} = 1;
 3612:         }
 3613:         my (%changeHash,%changed);
 3614:         if ($oldinststatus eq '') {
 3615:             $oldsettings{'inststatus'} = $othertitle; 
 3616:         } else {
 3617:             if (ref($usertypes) eq 'HASH') {
 3618:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3619:             } else {
 3620:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3621:             }
 3622:         }
 3623:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3624:         if ($canmodify_status{'inststatus'}) {
 3625:             $canshow{'inststatus'} = 1;
 3626:             if (exists($env{'form.inststatus'})) {
 3627:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3628:                 if (@inststatuses > 0) {
 3629:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3630:                     $changeHash{'inststatus'} = $newinststatus;
 3631:                     if ($newinststatus ne $oldinststatus) {
 3632:                         $changed{'inststatus'} = $newinststatus;
 3633:                         foreach my $name ('portfolio','author') {
 3634:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3635:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3636:                         }
 3637:                     }
 3638:                     if (ref($usertypes) eq 'HASH') {
 3639:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3640:                     } else {
 3641:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3642:                     }
 3643:                 }
 3644:             } else {
 3645:                 $newinststatus = '';
 3646:                 $changeHash{'inststatus'} = $newinststatus;
 3647:                 $newsettings{'inststatus'} = $othertitle;
 3648:                 if ($newinststatus ne $oldinststatus) {
 3649:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3650:                     foreach my $name ('portfolio','author') {
 3651:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3652:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3653:                     }
 3654:                 }
 3655:             }
 3656:         } elsif ($context ne 'selfcreate') {
 3657:             $canshow{'inststatus'} = 1;
 3658:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3659:         }
 3660:         foreach my $name ('portfolio','author') {
 3661:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3662:         }
 3663:         if ($context eq 'domain') {
 3664:             foreach my $name ('portfolio','author') {
 3665:                 if ($userenv{$name.'quota'} ne '') {
 3666:                     $oldquota{$name} = $userenv{$name.'quota'};
 3667:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3668:                         if ($env{'form.'.$name.'quota'} eq '') {
 3669:                             $newquota{$name} = 0;
 3670:                         } else {
 3671:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3672:                             $newquota{$name} =~ s/[^\d\.]//g;
 3673:                         }
 3674:                         if ($newquota{$name} != $oldquota{$name}) {
 3675:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3676:                                 $changed{$name.'quota'} = 1;
 3677:                             }
 3678:                         }
 3679:                     } else {
 3680:                         if (&quota_admin('',\%changeHash,$name)) {
 3681:                             $changed{$name.'quota'} = 1;
 3682:                             $newquota{$name} = $newdefquota{$name};
 3683:                             $newisdefault{$name} = 1;
 3684:                         }
 3685:                     }
 3686:                 } else {
 3687:                     $oldisdefault{$name} = 1;
 3688:                     $oldquota{$name} = $olddefquota{$name};
 3689:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3690:                         if ($env{'form.'.$name.'quota'} eq '') {
 3691:                             $newquota{$name} = 0;
 3692:                         } else {
 3693:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3694:                             $newquota{$name} =~ s/[^\d\.]//g;
 3695:                         }
 3696:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3697:                             $changed{$name.'quota'} = 1;
 3698:                         }
 3699:                     } else {
 3700:                         $newquota{$name} = $newdefquota{$name};
 3701:                         $newisdefault{$name} = 1;
 3702:                     }
 3703:                 }
 3704:                 if ($oldisdefault{$name}) {
 3705:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3706:                 }  else {
 3707:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3708:                 }
 3709:                 if ($newisdefault{$name}) {
 3710:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3711:                 } else {
 3712:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3713:                 }
 3714:             }
 3715:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3716:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3717:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3718:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3719:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3720:                 my ($isadv,$isauthor) =
 3721:                     &Apache::lonnet::is_advanced_user($env{'form.ccdomain'},$env{'form.ccuname'});
 3722:                 unless ($isauthor) {
 3723:                     &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3724:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3725:                 }
 3726:                 &tool_changes('authordefaults',\@authordefaults,\%oldsettings,\%oldsettingstext,
 3727:                                   \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3728:             } else {
 3729:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3730:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3731:             }
 3732:         }
 3733:         foreach my $item (@userinfo) {
 3734:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3735:                 $namechanged{$item} = 1;
 3736:             }
 3737:         }
 3738:         foreach my $name ('portfolio','author') {
 3739:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3740:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3741:         }
 3742:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3743:             my ($chgresult,$namechgresult);
 3744:             if (keys(%changed) > 0) {
 3745:                 $chgresult =
 3746:                     &Apache::lonnet::put('environment',\%changeHash,
 3747:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3748:                 if ($chgresult eq 'ok') {
 3749:                     my ($ca_mgr_del,%ca_mgr_add);
 3750:                     if ($changed{'managers'}) {
 3751:                         my (@adds,@dels);
 3752:                         if ($changeHash{'authormanagers'} eq '') {
 3753:                             @dels = split(/,/,$userenv{'authormanagers'});
 3754:                         } elsif ($userenv{'authormanagers'} eq '') {
 3755:                             @adds = split(/,/,$changeHash{'authormanagers'});
 3756:                         } else {
 3757:                             my @old = split(/,/,$userenv{'authormanagers'});
 3758:                             my @new = split(/,/,$changeHash{'authormanagers'});
 3759:                             my @diffs = &Apache::loncommon::compare_arrays(\@old,\@new);
 3760:                             if (@diffs) {
 3761:                                 foreach my $user (@diffs) {
 3762:                                     if (grep(/^\Q$user\E$/,@old)) {
 3763:                                         push(@dels,$user);
 3764:                                     } elsif (grep(/^\Q$user\E$/,@new)) {
 3765:                                         push(@adds,$user);
 3766:                                     }
 3767:                                 }
 3768:                             }
 3769:                         }
 3770:                         my $key = "internal.manager./$env{'form.ccdomain'}/$env{'form.ccuname'}";
 3771:                         if (@dels) {
 3772:                             foreach my $user (@dels) {
 3773:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3774:                                     &Apache::lonnet::del('environment',[$key],$2,$1);
 3775:                                 }
 3776:                             }
 3777:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3778:                             if (grep(/^\Q$curruser\E$/,@dels)) {
 3779:                                 $ca_mgr_del = $key;
 3780:                             }
 3781:                         }
 3782:                         if (@adds) {
 3783:                             foreach my $user (@adds) {
 3784:                                 if ($user =~ /^($match_username):($match_domain)$/) {
 3785:                                     &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 3786:                                 }
 3787:                             }
 3788:                             my $curruser = $env{'user.name'}.':'.$env{'user.domain'};
 3789:                             if (grep(/^\Q$curruser\E$/,@adds)) {
 3790:                                 $ca_mgr_add{$key} = 1;
 3791:                             }
 3792:                         }
 3793:                     }
 3794:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3795:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3796:                         my (%newenvhash,$got_domdefs,%domdefaults,$got_userenv,
 3797:                             %userenv);
 3798:                         my @fromenv = keys(%changed);
 3799:                         push(@fromenv,'inststatus');
 3800:                         foreach my $key (keys(%changed)) {
 3801:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3802:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3803:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3804:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3805:                                     $changeHash{'requestcourses.'.$key};
 3806:                                 if ($changeHash{'requestcourses.'.$key}) {
 3807:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3808:                                 } else {
 3809:                                     unless ($got_domdefs) {
 3810:                                         %domdefaults =
 3811:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3812:                                         $got_domdefs = 1;
 3813:                                     }
 3814:                                     unless ($got_userenv) {
 3815:                                         %userenv =
 3816:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3817:                                                                              $env{'user.name'},@fromenv);
 3818:                                         $got_userenv = 1;
 3819:                                     }
 3820:                                     $newenvhash{'environment.canrequest.'.$key} =
 3821:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3822:                                             $key,'reload','requestcourses',\%userenv,\%domdefaults);
 3823:                                 }
 3824:                             } elsif ($key eq 'requestauthor') {
 3825:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3826:                                 if ($changeHash{$key}) {
 3827:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3828:                                 } else {
 3829:                                     unless ($got_domdefs) {
 3830:                                         %domdefaults =
 3831:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3832:                                         $got_domdefs = 1;
 3833:                                     }
 3834:                                     unless ($got_userenv) {
 3835:                                         %userenv =
 3836:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3837:                                                                              $env{'user.name'},@fromenv);
 3838:                                         $got_userenv = 1;
 3839:                                     }
 3840:                                     $newenvhash{'environment.canrequest.author'} =
 3841:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3842:                                             $key,'reload','requestauthor',\%userenv,\%domdefaults);
 3843:                                 }
 3844:                             } elsif ($key eq 'editors') {
 3845:                                 $newenvhash{'environment.author'.$key} = $changeHash{'author'.$key};
 3846:                                 if ($env{'form.customeditors'}) {
 3847:                                     $newenvhash{'environment.editors'} = $changeHash{'author'.$key};
 3848:                                 } else {
 3849:                                     unless ($got_domdefs) {
 3850:                                         %domdefaults =
 3851:                                             &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3852:                                         $got_domdefs = 1;
 3853:                                     }
 3854:                                     if ($domdefaults{'editors'} ne '') {
 3855:                                         $newenvhash{'environment.editors'} = $domdefaults{'editors'};
 3856:                                     } else {
 3857:                                         $newenvhash{'environment.editors'} = 'edit,xml';
 3858:                                     }
 3859:                                 }
 3860:                             } elsif ($key ne 'quota') {
 3861:                                 $newenvhash{'environment.tools.'.$key} = 
 3862:                                     $changeHash{'tools.'.$key};
 3863:                                 if ($changeHash{'tools.'.$key} ne '') {
 3864:                                     $newenvhash{'environment.availabletools.'.$key} =
 3865:                                         $changeHash{'tools.'.$key};
 3866:                                 } else {
 3867:                                     unless ($got_domdefs) {
 3868:                                         %domdefaults =
 3869:                                            &Apache::lonnet::get_domain_defaults($env{'user.domain'});
 3870:                                         $got_domdefs = 1;
 3871:                                     }
 3872:                                     unless ($got_userenv) {
 3873:                                         %userenv =
 3874:                                             &Apache::lonnet::userenvironment($env{'user.domain'},
 3875:                                                                              $env{'user.name'},@fromenv);
 3876:                                         $got_userenv = 1;
 3877:                                     }
 3878:                                     $newenvhash{'environment.availabletools.'.$key} =
 3879:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3880:                                             $key,'reload','tools',\%userenv,\%domdefaults);
 3881:                                 }
 3882:                             }
 3883:                         }
 3884:                         if (keys(%newenvhash)) {
 3885:                             &Apache::lonnet::appenv(\%newenvhash);
 3886:                         }
 3887:                     } else {
 3888:                         if ($ca_mgr_del) {
 3889:                             &Apache::lonnet::delenv($ca_mgr_del);
 3890:                         }
 3891:                         if (keys(%ca_mgr_add)) {
 3892:                             &Apache::lonnet::appenv(\%ca_mgr_add);
 3893:                         }
 3894:                     }
 3895:                     if ($changed{'aboutme'}) {
 3896:                         &Apache::loncommon::devalidate_aboutme_cache($env{'form.ccuname'},
 3897:                                                                      $env{'form.ccdomain'});
 3898:                     }
 3899:                 }
 3900:             }
 3901:             if (keys(%namechanged) > 0) {
 3902:                 foreach my $field (@userinfo) {
 3903:                     $changeHash{$field}  = $env{'form.c'.$field};
 3904:                 }
 3905: # Make the change
 3906:                 $namechgresult =
 3907:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3908:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3909:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3910:                         $changeHash{'lastname'},$changeHash{'generation'},
 3911:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3912:                 %userupdate = (
 3913:                                lastname   => $env{'form.clastname'},
 3914:                                middlename => $env{'form.cmiddlename'},
 3915:                                firstname  => $env{'form.cfirstname'},
 3916:                                generation => $env{'form.cgeneration'},
 3917:                                id         => $env{'form.cid'},
 3918:                              );
 3919:             }
 3920:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3921:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3922:             # Tell the user we changed the name
 3923:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3924:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3925:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3926:                                   \%newsettingstext);
 3927:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3928:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3929:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3930:                     if (($recurseid) &&
 3931:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3932:                         my $idresult = 
 3933:                             &Apache::lonuserutils::propagate_id_change(
 3934:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3935:                                 \%userupdate);
 3936:                         $r->print('<br />'.$idresult.'<br />');
 3937:                     }
 3938:                 }
 3939:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3940:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3941:                     my %newenvhash;
 3942:                     foreach my $key (keys(%changeHash)) {
 3943:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3944:                     }
 3945:                     &Apache::lonnet::appenv(\%newenvhash);
 3946:                 }
 3947:             } else { # error occurred
 3948:                 $r->print(
 3949:                     '<p class="LC_error">'
 3950:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3951:                             '"'.$env{'form.ccuname'}.'"',
 3952:                             '"'.$env{'form.ccdomain'}.'"')
 3953:                    .'</p>');
 3954:             }
 3955:         } else { # End of if ($env ... ) logic
 3956:             # They did not want to change the users name, quota, tool availability,
 3957:             # or ability to request creation of courses, 
 3958:             # but we can still tell them what the name and quota and availabilities are  
 3959:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3960:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3961:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3962:         }
 3963:         if (@mod_disallowed) {
 3964:             my ($rolestr,$contextname);
 3965:             if (@longroles > 0) {
 3966:                 $rolestr = join(', ',@longroles);
 3967:             } else {
 3968:                 $rolestr = &mt('No roles');
 3969:             }
 3970:             if ($context eq 'course') {
 3971:                 $contextname = 'course';
 3972:             } elsif ($context eq 'author') {
 3973:                 $contextname = 'co-author';
 3974:             }
 3975:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3976:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3977:             foreach my $field (@mod_disallowed) {
 3978:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3979:             }
 3980:             $r->print('</ul>');
 3981:             if (@mod_disallowed == 1) {
 3982:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3983:             } else {
 3984:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3985:             }
 3986:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3987:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3988:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3989:                          ,'<a href="'.$helplink.'">','</a>')
 3990:                       .'<br />');
 3991:         }
 3992:         $r->print('<span class="LC_warning">'
 3993:                   .$no_forceid_alert
 3994:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3995:                   .'</span>');
 3996:     }
 3997:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3998:     if ($env{'form.action'} eq 'singlestudent') {
 3999:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 4000:                                $crstype,$showcredits,$defaultcredits);
 4001:         my $linktext = ($crstype eq 'Community' ?
 4002:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 4003:         $r->print(
 4004:             &Apache::lonhtmlcommon::actionbox([
 4005:                 '<a href="javascript:backPage(document.userupdate)">'
 4006:                .($crstype eq 'Community' ? 
 4007:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 4008:                .'</a>']));
 4009:     } else {
 4010:         my @rolechanges = &update_roles($r,$context,$showcredits);
 4011:         if (keys(%namechanged) > 0) {
 4012:             if ($context eq 'course') {
 4013:                 if (@userroles > 0) {
 4014:                     if ((@rolechanges == 0) || 
 4015:                         (!(grep(/^st$/,@rolechanges)))) {
 4016:                         if (grep(/^st$/,@userroles)) {
 4017:                             my $classlistupdated =
 4018:                                 &Apache::lonuserutils::update_classlist($cdom,
 4019:                                               $cnum,$env{'form.ccdomain'},
 4020:                                        $env{'form.ccuname'},\%userupdate);
 4021:                         }
 4022:                     }
 4023:                 }
 4024:             }
 4025:         }
 4026:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 4027:                                                      $env{'form.ccdomain'});
 4028:         if ($env{'form.popup'}) {
 4029:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 4030:         } else {
 4031:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 4032:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 4033:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 4034:         }
 4035:     }
 4036: }
 4037: 
 4038: sub display_userinfo {
 4039:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 4040:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 4041:         $newsetting,$newsettingtext) = @_;
 4042:     return unless (ref($order) eq 'ARRAY' &&
 4043:                    ref($canshow) eq 'HASH' && 
 4044:                    ref($requestcourses) eq 'ARRAY' && 
 4045:                    ref($requestauthor) eq 'ARRAY' &&
 4046:                    ref($usertools) eq 'ARRAY' && 
 4047:                    ref($userenv) eq 'HASH' &&
 4048:                    ref($changedhash) eq 'HASH' &&
 4049:                    ref($oldsetting) eq 'HASH' &&
 4050:                    ref($oldsettingtext) eq 'HASH' &&
 4051:                    ref($newsetting) eq 'HASH' &&
 4052:                    ref($newsettingtext) eq 'HASH');
 4053:     my %lt=&Apache::lonlocal::texthash(
 4054:          'ui'             => 'User Information',
 4055:          'uic'            => 'User Information Changed',
 4056:          'firstname'      => 'First Name',
 4057:          'middlename'     => 'Middle Name',
 4058:          'lastname'       => 'Last Name',
 4059:          'generation'     => 'Generation',
 4060:          'id'             => 'Student/Employee ID',
 4061:          'permanentemail' => 'Permanent e-mail address',
 4062:          'portfolioquota' => 'Disk space allocated to portfolio files',
 4063:          'authorquota'    => 'Disk space allocated to Authoring Space',
 4064:          'blog'           => 'Blog Availability',
 4065:          'webdav'         => 'WebDAV Availability',
 4066:          'aboutme'        => 'Personal Information Page Availability',
 4067:          'portfolio'      => 'Portfolio Availability',
 4068:          'portaccess'     => 'Portfolio Shareable',
 4069:          'timezone'       => 'Can set own Time Zone',
 4070:          'official'       => 'Can Request Official Courses',
 4071:          'unofficial'     => 'Can Request Unofficial Courses',
 4072:          'community'      => 'Can Request Communities',
 4073:          'textbook'       => 'Can Request Textbook Courses',
 4074:          'placement'      => 'Can Request Placement Tests',
 4075:          'lti'            => 'Can Request LTI Courses',
 4076:          'requestauthor'  => 'Can Request Author Role',
 4077:          'inststatus'     => "Affiliation",
 4078:          'prvs'           => 'Previous Value:',
 4079:          'chto'           => 'Changed To:',
 4080:          'editors'        => "Available Editors in Authoring Space",
 4081:          'managers'       => "Co-authors who can add/revoke roles",
 4082:          'archive'        => "Managers can download tar.gz file of Authoring Space",
 4083:          'edit'           => 'Standard editor (Edit)',
 4084:          'xml'            => 'Text editor (EditXML)',
 4085:          'daxe'           => 'Daxe editor (Daxe)',
 4086:     );
 4087:     if ($changed) {
 4088:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 4089:                 &Apache::loncommon::start_data_table().
 4090:                 &Apache::loncommon::start_data_table_header_row());
 4091:         $r->print("<th>&nbsp;</th>\n");
 4092:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 4093:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 4094:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4095:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 4096: 
 4097:         foreach my $item (@userinfo) {
 4098:             my $value = $env{'form.c'.$item};
 4099:             #show changes only:
 4100:             unless ($value eq $userenv->{$item}){
 4101:                 $r->print(&Apache::loncommon::start_data_table_row());
 4102:                 $r->print("<td>$lt{$item}</td>\n");
 4103:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 4104:                 $r->print("<td>$value </td>\n");
 4105:                 $r->print(&Apache::loncommon::end_data_table_row());
 4106:             }
 4107:         }
 4108:         foreach my $entry (@{$order}) {
 4109:             if ($canshow->{$entry}) {
 4110:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') ||
 4111:                     ($entry eq 'requestauthor') || ($entry eq 'authordefaults')) {
 4112:                     my @items;
 4113:                     if ($entry eq 'requestauthor') {
 4114:                         @items = ($entry);
 4115:                     } elsif ($entry eq 'authordefaults') {
 4116:                         @items = ('webdav','managers','editors','archive');
 4117:                     } else {
 4118:                         @items = @{$requestcourses};
 4119:                     }
 4120:                     foreach my $item (@items) {
 4121:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 4122:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 4123:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 4124:                             $r->print("<td>$lt{$item}</td><td>\n");
 4125:                             unless ($item eq 'managers') {
 4126:                                 $r->print($oldsetting->{$item});
 4127:                             }
 4128:                             if ($oldsettingtext->{$item}) {
 4129:                                 if ($oldsetting->{$item}) {
 4130:                                     unless ($item eq 'managers') {
 4131:                                         $r->print(' -- ');
 4132:                                     }
 4133:                                 }
 4134:                                 $r->print($oldsettingtext->{$item});
 4135:                             }
 4136:                             $r->print("</td>\n<td>");
 4137:                             unless ($item eq 'managers') {
 4138:                                 $r->print($newsetting->{$item});
 4139:                             }
 4140:                             if ($newsettingtext->{$item}) {
 4141:                                 if ($newsetting->{$item}) {
 4142:                                     unless ($item eq 'managers') {
 4143:                                         $r->print(' -- ');
 4144:                                     }
 4145:                                 }
 4146:                                 $r->print($newsettingtext->{$item});
 4147:                             }
 4148:                             $r->print("</td>\n");
 4149:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4150:                         }
 4151:                     }
 4152:                 } elsif ($entry eq 'tools') {
 4153:                     foreach my $item (@{$usertools}) {
 4154:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 4155:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4156:                             $r->print("<td>$lt{$item}</td>\n");
 4157:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 4158:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 4159:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4160:                         }
 4161:                     }
 4162:                 } elsif ($entry eq 'quota') {
 4163:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 4164:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 4165:                         foreach my $name ('portfolio','author') {
 4166:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 4167:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4168:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 4169:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 4170:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 4171:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4172:                             }
 4173:                         }
 4174:                     }
 4175:                 } else {
 4176:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 4177:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 4178:                         $r->print("<td>$lt{$entry}</td>\n");
 4179:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 4180:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 4181:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 4182:                     }
 4183:                 }
 4184:             }
 4185:         }
 4186:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 4187:     } else {
 4188:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 4189:                   '<p>'.&mt('No changes made to user information').'</p>');
 4190:     }
 4191:     return;
 4192: }
 4193: 
 4194: sub tool_changes {
 4195:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 4196:         $changed,$newaccess,$newaccesstext) = @_;
 4197:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 4198:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 4199:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 4200:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 4201:         return;
 4202:     }
 4203:     my %reqdisplay = &requestchange_display();
 4204:     if ($context eq 'reqcrsotherdom') {
 4205:         my @options = ('approval','validate','autolimit');
 4206:         my $optregex = join('|',@options);
 4207:         my $cdom = $env{'request.role.domain'};
 4208:         foreach my $tool (@{$usertools}) {
 4209:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4210:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4211:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 4212:             my ($newop,$limit);
 4213:             if ($env{'form.'.$context.'_'.$tool}) {
 4214:                 $newop = $env{'form.'.$context.'_'.$tool};
 4215:                 if ($newop eq 'autolimit') {
 4216:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4217:                     $limit =~ s/\D+//g;
 4218:                     $newop .= '='.$limit;
 4219:                 }
 4220:             }
 4221:             if ($userenv->{$context.'.'.$tool} eq '') {
 4222:                 if ($newop) {
 4223:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 4224:                                                   $changeHash,$context);
 4225:                     if ($changed->{$tool}) {
 4226:                         if ($newop =~ /^autolimit/) {
 4227:                             if ($limit) {
 4228:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4229:                             } else {
 4230:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4231:                             }
 4232:                         } else {
 4233:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 4234:                         }
 4235:                     } else {
 4236:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4237:                     }
 4238:                 }
 4239:             } else {
 4240:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 4241:                 my @new;
 4242:                 my $changedoms;
 4243:                 foreach my $req (@curr) {
 4244:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 4245:                         my $oldop = $1;
 4246:                         if ($oldop =~ /^autolimit=(\d*)/) {
 4247:                             my $limit = $1;
 4248:                             if ($limit) {
 4249:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4250:                             } else {
 4251:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4252:                             }
 4253:                         } else {
 4254:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 4255:                         }
 4256:                         if ($oldop ne $newop) {
 4257:                             $changedoms = 1;
 4258:                             foreach my $item (@curr) {
 4259:                                 my ($reqdom,$option) = split(':',$item);
 4260:                                 unless ($reqdom eq $cdom) {
 4261:                                     push(@new,$item);
 4262:                                 }
 4263:                             }
 4264:                             if ($newop) {
 4265:                                 push(@new,$cdom.':'.$newop);
 4266:                             }
 4267:                             @new = sort(@new);
 4268:                         }
 4269:                         last;
 4270:                     }
 4271:                 }
 4272:                 if ((!$changedoms) && ($newop)) {
 4273:                     $changedoms = 1;
 4274:                     @new = sort(@curr,$cdom.':'.$newop);
 4275:                 }
 4276:                 if ($changedoms) {
 4277:                     my $newdomstr;
 4278:                     if (@new) {
 4279:                         $newdomstr = join(',',@new);
 4280:                     }
 4281:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 4282:                                                   $context);
 4283:                     if ($changed->{$tool}) {
 4284:                         if ($env{'form.'.$context.'_'.$tool}) {
 4285:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 4286:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 4287:                                 $limit =~ s/\D+//g;
 4288:                                 if ($limit) {
 4289:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4290:                                 } else {
 4291:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4292:                                 }
 4293:                             } else {
 4294:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 4295:                             }
 4296:                         } else {
 4297:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4298:                         }
 4299:                     }
 4300:                 }
 4301:             }
 4302:         }
 4303:         return;
 4304:     }
 4305:     my %tooldesc = &Apache::lonlocal::texthash(
 4306:         'edit' => 'Standard editor (Edit)',
 4307:         'xml'  => 'Text editor (EditXML)',
 4308:         'daxe' => 'Daxe editor (Daxe)',
 4309:     );
 4310:     foreach my $tool (@{$usertools}) {
 4311:         my ($newval,$limit,$envkey);
 4312:         $envkey = $context.'.'.$tool;
 4313:         if ($context eq 'requestcourses') {
 4314:             $newval = $env{'form.crsreq_'.$tool};
 4315:             if ($newval eq 'autolimit') {
 4316:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 4317:                 $limit =~ s/\D+//g;
 4318:                 $newval .= '='.$limit;
 4319:             }
 4320:         } elsif ($context eq 'requestauthor') {
 4321:             $newval = $env{'form.'.$context};
 4322:             $envkey = $context;
 4323:         } elsif ($context eq 'authordefaults') {
 4324:             if ($tool eq 'editors') {
 4325:                 $envkey = 'authoreditors';
 4326:                 if ($env{'form.customeditors'} == 1) {
 4327:                     my @editors;
 4328:                     my @posseditors = &Apache::loncommon::get_env_multiple('form.custom_editor');
 4329:                     if (@posseditors) {
 4330:                         foreach my $editor (@posseditors) {
 4331:                             if (grep(/^\Q$editor\E$/,@posseditors)) {
 4332:                                 unless (grep(/^\Q$editor\E$/,@editors)) {
 4333:                                     push(@editors,$editor);
 4334:                                 }
 4335:                             }
 4336:                         }
 4337:                     }
 4338:                     if (@editors) {
 4339:                         $newval = join(',',(sort(@editors)));
 4340:                     }
 4341:                 }
 4342:             } elsif ($tool eq 'managers') {
 4343:                 $envkey = 'authormanagers';
 4344:                 my @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 4345:                 if (@possibles) {
 4346:                     my %ca_roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},
 4347:                                                                  undef,['active','future'],['ca']);
 4348:                     if (keys(%ca_roles)) {
 4349:                         my @custommanagers;
 4350:                         foreach my $user (@possibles) {
 4351:                             if ($user =~ /^($match_username):($match_domain)$/) {
 4352:                                 if (exists($ca_roles{$user.':ca'})) {
 4353:                                     unless ($user eq $env{'form.ccuname'}.':'.$env{'form.ccdomain'}) {
 4354:                                         push(@custommanagers,$user);
 4355:                                     }
 4356:                                 }
 4357:                             }
 4358:                         }
 4359:                         if (@custommanagers) {
 4360:                             $newval = join(',',sort(@custommanagers));
 4361:                         }
 4362:                     }
 4363:                 }
 4364:             } elsif ($tool eq 'webdav') {
 4365:                 $envkey = 'tools.webdav';
 4366:                 $newval = $env{'form.'.$context.'_'.$tool};
 4367:             } elsif ($tool eq 'archive') {
 4368:                 $envkey = 'authorarchive';
 4369:                 $newval = $env{'form.'.$context.'_'.$tool};
 4370:             }
 4371:         } else {
 4372:             $newval = $env{'form.'.$context.'_'.$tool};
 4373:         }
 4374:         if ($userenv->{$envkey} ne '') {
 4375:             $oldaccess->{$tool} = &mt('custom');
 4376:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4377:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 4378:                     my $currlimit = $1;
 4379:                     if ($currlimit eq '') {
 4380:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4381:                     } else {
 4382:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 4383:                     }
 4384:                 } elsif ($userenv->{$envkey}) {
 4385:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4386:                 } else {
 4387:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4388:                 }
 4389:             } elsif ($context eq 'authordefaults') {
 4390:                 if ($tool eq 'managers') {
 4391:                     if ($userenv->{$envkey} eq '') {
 4392:                         $oldaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4393:                     } else {
 4394:                         my $managers = $userenv->{$envkey};
 4395:                         $managers =~ s/,/, /g;
 4396:                         $oldaccesstext->{$tool} = $managers;
 4397:                     }
 4398:                 } elsif ($tool eq 'editors') {
 4399:                     $oldaccesstext->{$tool} = &mt('can use: [_1]',
 4400:                                                   join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4401:                 } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4402:                     if ($userenv->{$envkey}) {
 4403:                         $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4404:                     } else {
 4405:                         $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4406:                     }
 4407:                 }
 4408:             } else {
 4409:                 if ($userenv->{$envkey}) {
 4410:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 4411:                 } else {
 4412:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 4413:                 }
 4414:             }
 4415:             $changeHash->{$envkey} = $userenv->{$envkey};
 4416:             if (($env{'form.custom'.$tool} == 1) ||
 4417:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4418:                 if ($newval ne $userenv->{$envkey}) {
 4419:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4420:                                                     $context);
 4421:                     if ($changed->{$tool}) {
 4422:                         $newaccess->{$tool} = &mt('custom');
 4423:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4424:                             if ($newval =~ /^autolimit/) {
 4425:                                 if ($limit) {
 4426:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4427:                                 } else {
 4428:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4429:                                 }
 4430:                             } elsif ($newval) {
 4431:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 4432:                             } else {
 4433:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4434:                             }
 4435:                         } elsif ($context eq 'authordefaults') {
 4436:                             if ($tool eq 'editors') {
 4437:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4438:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$changeHash->{$envkey})));
 4439:                             } elsif ($tool eq 'managers') {
 4440:                                 if ($changeHash->{$envkey} eq '') {
 4441:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4442:                                 } else {
 4443:                                     my $managers = $changeHash->{$envkey};
 4444:                                     $managers =~ s/,/, /g;
 4445:                                     $newaccesstext->{$tool} = $managers;
 4446:                                 }
 4447:                             } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4448:                                 if ($newval) {
 4449:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4450:                                 } else {
 4451:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4452:                                 }
 4453:                             }
 4454:                         } else {
 4455:                             if ($newval) {
 4456:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4457:                             } else {
 4458:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4459:                             }
 4460:                         }
 4461:                     } else {
 4462:                         $newaccess->{$tool} = $oldaccess->{$tool};
 4463:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4464:                             if ($userenv->{$envkey} =~ /^autolimit/) {
 4465:                                 if ($limit) {
 4466:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4467:                                 } else {
 4468:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4469:                                 }
 4470:                             } elsif ($userenv->{$envkey}) {
 4471:                                 $newaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 4472:                             } else {
 4473:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4474:                             }
 4475:                         } elsif ($context eq 'authordefaults') {
 4476:                             if ($tool eq 'editors') {
 4477:                                 $newaccesstext->{$tool} = &mt('can use: [_1]',
 4478:                                                               join(', ', map { $tooldesc{$_} } split(/,/,$userenv->{$envkey})));
 4479:                             } elsif ($tool eq 'managers') {
 4480:                                 if ($userenv->{$envkey} eq '') {
 4481:                                     $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4482:                                 } else {
 4483:                                     my $managers = $userenv->{$envkey};
 4484:                                     $managers =~ s/,/, /g;
 4485:                                     $newaccesstext->{$tool} = $managers;
 4486:                                 }
 4487:                             } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4488:                                 if ($userenv->{$envkey}) {
 4489:                                     $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4490:                                 } else {
 4491:                                     $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4492:                                 }
 4493:                             }
 4494:                         } else {
 4495:                             if ($userenv->{$context.'.'.$tool}) {
 4496:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4497:                             } else {
 4498:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4499:                             }
 4500:                         }
 4501:                     }
 4502:                 } else {
 4503:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4504:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 4505:                 }
 4506:             } else {
 4507:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 4508:                 if ($changed->{$tool}) {
 4509:                     $newaccess->{$tool} = &mt('default');
 4510:                 } else {
 4511:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4512:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4513:                         if ($newval =~ /^autolimit/) {
 4514:                             if ($limit) {
 4515:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4516:                             } else {
 4517:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4518:                             }
 4519:                         } elsif ($newval) {
 4520:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4521:                         } else {
 4522:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4523:                         }
 4524:                     } elsif ($context eq 'authordefaults') {
 4525:                         if ($tool eq 'editors') {
 4526:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4527:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4528:                         } elsif ($tool eq 'managers') {
 4529:                             if ($newval eq '') {
 4530:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4531:                             } else {
 4532:                                 my $managers = $newval;
 4533:                                 $managers =~ s/,/, /g;
 4534:                                 $newaccesstext->{$tool} = $managers;
 4535:                             }
 4536:                         } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4537:                             if ($userenv->{$envkey}) {
 4538:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4539:                             } else {
 4540:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4541:                             }
 4542:                         }
 4543:                     } else {
 4544:                         if ($userenv->{$context.'.'.$tool}) {
 4545:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4546:                         } else {
 4547:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4548:                         }
 4549:                     }
 4550:                 }
 4551:             }
 4552:         } else {
 4553:             $oldaccess->{$tool} = &mt('default');
 4554:             if (($env{'form.custom'.$tool} == 1) ||
 4555:                 (($context eq 'authordefaults') && ($tool eq 'managers') && ($newval ne ''))) {
 4556:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 4557:                                                 $context);
 4558:                 if ($changed->{$tool}) {
 4559:                     $newaccess->{$tool} = &mt('custom');
 4560:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 4561:                         if ($newval =~ /^autolimit/) {
 4562:                             if ($limit) {
 4563:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 4564:                             } else {
 4565:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 4566:                             }
 4567:                         } elsif ($newval) {
 4568:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 4569:                         } else {
 4570:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4571:                         }
 4572:                     } elsif ($context eq 'authordefaults') {
 4573:                         if ($tool eq 'managers') {
 4574:                             if ($newval eq '') {
 4575:                                 $newaccesstext->{$tool} = &mt('Only author may manage co-author roles');
 4576:                             } else {
 4577:                                 my $managers = $newval;
 4578:                                 $managers =~ s/,/, /g;
 4579:                                 $newaccesstext->{$tool} = $managers;
 4580:                             }
 4581:                         } elsif ($tool eq 'editors') {
 4582:                             $newaccesstext->{$tool} = &mt('can use: [_1]',
 4583:                                                           join(', ', map { $tooldesc{$_} } split(/,/,$newval)));
 4584:                         } elsif (($tool eq 'webdav') || ($tool eq 'archive')) {
 4585:                             if ($newval) {
 4586:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4587:                             } else {
 4588:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4589:                             }
 4590:                         }
 4591:                     } else {
 4592:                         if ($newval) {
 4593:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 4594:                         } else {
 4595:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 4596:                         }
 4597:                     }
 4598:                 } else {
 4599:                     $newaccess->{$tool} = $oldaccess->{$tool};
 4600:                 }
 4601:             } else {
 4602:                 $newaccess->{$tool} = $oldaccess->{$tool};
 4603:             }
 4604:         }
 4605:     }
 4606:     return;
 4607: }
 4608: 
 4609: sub update_roles {
 4610:     my ($r,$context,$showcredits) = @_;
 4611:     my $now=time;
 4612:     my @rolechanges;
 4613:     my (%disallowed,%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 4614:         %pending,%reject,%notifydc,%status,%unauthorized,%currqueued);
 4615:     $got_role_approvals{$context} = '';
 4616:     $process_by{$context} = {};
 4617:     my @domroles = &Apache::lonuserutils::domain_roles();
 4618:     my @cstrroles = &Apache::lonuserutils::construction_space_roles();
 4619:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
 4620:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 4621:     foreach my $key (keys(%env)) {
 4622: 	next if (! $env{$key});
 4623:         next if ($key eq 'form.action');
 4624: 	# Revoke roles
 4625: 	if ($key=~/^form\.rev/) {
 4626: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 4627: # Revoke standard role
 4628: 		my ($scope,$role) = ($1,$2);
 4629: 		my $result =
 4630: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 4631: 						$env{'form.ccuname'},
 4632: 						$scope,$role,'','',$context);
 4633:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4634:                             &mt('Revoking [_1] in [_2]',
 4635:                                 &Apache::lonnet::plaintext($role),
 4636:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4637:                                 $result ne "ok").'<br />');
 4638:                 if ($result ne "ok") {
 4639:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4640:                 }
 4641: 		if ($role eq 'st') {
 4642: 		    my $result = 
 4643:                         &Apache::lonuserutils::classlist_drop($scope,
 4644:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4645: 			    $now);
 4646:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4647: 		}
 4648:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4649:                     push(@rolechanges,$role);
 4650:                 }
 4651: 	    }
 4652: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4653: # Revoke custom role
 4654:                 my $result = &Apache::lonnet::revokecustomrole(
 4655:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4656:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4657:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4658:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4659:                             $result ne 'ok').'<br />');
 4660:                 if ($result ne "ok") {
 4661:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4662:                 }
 4663:                 if (!grep(/^cr$/,@rolechanges)) {
 4664:                     push(@rolechanges,'cr');
 4665:                 }
 4666: 	    }
 4667: 	} elsif ($key=~/^form\.del/) {
 4668: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4669: # Delete standard role
 4670: 		my ($scope,$role) = ($1,$2);
 4671: 		my $result =
 4672: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4673: 						$env{'form.ccuname'},
 4674: 						$scope,$role,$now,0,1,'',
 4675:                                                 $context);
 4676:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4677:                             &mt('Deleting [_1] in [_2]',
 4678:                                 &Apache::lonnet::plaintext($role),
 4679:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4680:                             $result ne 'ok').'<br />');
 4681:                 if ($result ne "ok") {
 4682:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4683:                 }
 4684: 
 4685: 		if ($role eq 'st') {
 4686: 		    my $result = 
 4687:                         &Apache::lonuserutils::classlist_drop($scope,
 4688:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4689: 			    $now);
 4690: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4691: 		}
 4692:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4693:                     push(@rolechanges,$role);
 4694:                 }
 4695:             }
 4696: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4697:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4698: # Delete custom role
 4699:                 my $result =
 4700:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4701:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4702:                         0,1,$context);
 4703:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4704:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4705:                       $result ne "ok").'<br />');
 4706:                 if ($result ne "ok") {
 4707:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4708:                 }
 4709: 
 4710:                 if (!grep(/^cr$/,@rolechanges)) {
 4711:                     push(@rolechanges,'cr');
 4712:                 }
 4713:             }
 4714: 	} elsif ($key=~/^form\.ren/) {
 4715:             my $udom = $env{'form.ccdomain'};
 4716:             my $uname = $env{'form.ccuname'};
 4717: # Re-enable standard role
 4718: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4719:                 my $url = $1;
 4720:                 my $role = $2;
 4721:                 my $id = $url.'_'.$role;
 4722:                 my $logmsg;
 4723:                 my $output;
 4724:                 if ($role eq 'st') {
 4725:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4726:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4727:                         my $credits;
 4728:                         if ($showcredits) {
 4729:                             my $defaultcredits =
 4730:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4731:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4732:                         }
 4733:                         unless ($udom eq $cdom) {
 4734:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4735:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,$credits,
 4736:                                          \%process_by,\%instdoms,\%got_role_approvals,
 4737:                                          \%got_instdoms,\%reject,\%pending,\%notifydc,
 4738:                                          \%status,\%unauthorized,\%currqueued));
 4739:                         }
 4740:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4741:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4742:                             if ($result eq 'refused' && $logmsg) {
 4743:                                 $output = $logmsg;
 4744:                             } else { 
 4745:                                 $output = &mt('Error: [_1]',$result)."\n";
 4746:                             }
 4747:                         } else {
 4748:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4749:                                         &Apache::lonnet::plaintext($role),
 4750:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4751:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4752:                         }
 4753:                     }
 4754:                 } else {
 4755:                     my ($cdom,$cnum,$csec);
 4756:                     if (grep(/^\Q$role\E$/,@cstrroles)) {
 4757:                         ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_username)$});
 4758:                     } elsif (grep(/^\Q$role\E$/,@domroles)) {
 4759:                         ($cdom) = ($url =~ m{^/($match_domain)/$});
 4760:                     } elsif ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4761:                         ($cdom,$cnum,$csec) = ($1,$2,$3);
 4762:                     }
 4763:                     if ($cdom ne '') {
 4764:                         unless ($udom eq $cdom) {
 4765:                             next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4766:                                          $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4767:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4768:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4769:                         }
 4770:                     }
 4771: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4772:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4773:                                $context);
 4774:                     $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4775:                                     &Apache::lonnet::plaintext($role),
 4776:                                     &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4777:                     if ($result ne "ok") {
 4778:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4779:                     }
 4780:                 }
 4781:                 $r->print($output);
 4782:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4783:                     push(@rolechanges,$role);
 4784:                 }
 4785: 	    }
 4786: # Re-enable custom role
 4787: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4788:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4789:                 my $id = $url.'_cr'."/$rdom/$rnam/$rolename";
 4790:                 my $role = "cr/$rdom/$rnam/$rolename";
 4791:                 if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4792:                     my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4793:                     unless ($udom eq $cdom) {
 4794:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4795:                                      $uname,$role,$now,0,$cdom,$cnum,$csec,'',\%process_by,
 4796:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4797:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4798:                     }
 4799:                 }
 4800:                 my $result = &Apache::lonnet::assigncustomrole(
 4801:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4802:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4803:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4804:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4805:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4806:                     $result ne "ok").'<br />');
 4807:                 if ($result ne "ok") {
 4808:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4809:                 }
 4810:                 if (!grep(/^cr$/,@rolechanges)) {
 4811:                     push(@rolechanges,'cr');
 4812:                 }
 4813:             }
 4814: 	} elsif ($key=~/^form\.act/) {
 4815:             my $udom = $env{'form.ccdomain'};
 4816:             my $uname = $env{'form.ccuname'};
 4817: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4818:                 # Activate a custom role
 4819: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4820: 		my $url='/'.$one.'/'.$two;
 4821:                 my $id = $url.'_cr/'."$three/$four/$five";
 4822:                 my $role = "cr/$three/$four/$five";
 4823: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4824: 
 4825:                 my $start = ( $env{'form.start_'.$full} ?
 4826:                               $env{'form.start_'.$full} :
 4827:                               $now );
 4828:                 my $end   = ( $env{'form.end_'.$full} ?
 4829:                               $env{'form.end_'.$full} :
 4830:                               0 );
 4831: 
 4832:                 # split multiple sections
 4833:                 my %sections = ();
 4834:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$five);
 4835:                 if ($num_sections == 0) {
 4836:                     unless ($udom eq $one) {
 4837:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4838:                                      $uname,$role,$start,$end,$one,$two,'','',\%process_by,
 4839:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4840:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4841:                     }
 4842:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4843:                 } else {
 4844: 		    my %curr_groups =
 4845: 			&Apache::longroup::coursegroups($one,$two);
 4846:                     my ($restricted,$numchanges);
 4847:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4848:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4849:                             exists($curr_groups{$sec})) {
 4850:                             $disallowed{$sec} = $url;
 4851:                             next;
 4852:                         }
 4853:                         my $securl = $url.'/'.$sec;
 4854:                         my $secid = $securl.'_cr'."/$three/$four/$five";
 4855:                         undef($restricted);
 4856:                         unless ($udom eq $one) {
 4857:                             next if (&Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4858:                                          $uname,$role,$start,$end,$one,$two,$sec,'',\%process_by,
 4859:                                          \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4860:                                          \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4861:                         }
 4862:                         $numchanges ++;
 4863: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4864:                     }
 4865:                     next unless ($numchanges);
 4866:                 }
 4867:                 if (!grep(/^cr$/,@rolechanges)) {
 4868:                     push(@rolechanges,'cr');
 4869:                 }
 4870: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4871: 		# Activate roles for sections with 3 id numbers
 4872: 		# set start, end times, and the url for the class
 4873: 		my ($one,$two,$three)=($1,$2,$3);
 4874: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ?
 4875: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} :
 4876: 			      $now );
 4877: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ?
 4878: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4879: 			      0 );
 4880: 		my $url='/'.$one.'/'.$two;
 4881:                 my $id = $url.'_'.$three;
 4882:                 # split multiple sections
 4883:                 my %sections = ();
 4884:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4885:                 my ($credits,$numchanges);
 4886:                 if ($three eq 'st') {
 4887:                     if ($showcredits) {
 4888:                         my $defaultcredits = 
 4889:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4890:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4891:                         $credits =~ s/[^\d\.]//g;
 4892:                         if ($credits eq $defaultcredits) {
 4893:                             undef($credits);
 4894:                         }
 4895:                     }
 4896:                 }
 4897:                 if ($num_sections == 0) {
 4898:                     unless ($udom eq $one) {
 4899:                         next if (&Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4900:                                      $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4901:                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4902:                                      \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued));
 4903:                     }
 4904:                     $numchanges ++;
 4905:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4906:                 } else {
 4907:                     my %curr_groups = 
 4908: 			&Apache::longroup::coursegroups($one,$two);
 4909:                     my $emptysec = 0;
 4910:                     my $restricted;
 4911:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4912:                         $sec =~ s/\W//g;
 4913:                         if ($sec ne '') {
 4914:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4915:                                 exists($curr_groups{$sec})) {
 4916:                                 $disallowed{$sec} = $url;
 4917:                                 next;
 4918:                             }
 4919:                             my $securl = $url.'/'.$sec;
 4920:                             my $secid = $securl.'_'.$three;
 4921:                             unless ($udom eq $one) {
 4922:                                 undef($restricted);
 4923:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4924:                                                   $uname,$three,$start,$end,$one,$two,$sec,$credits,\%process_by,
 4925:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4926:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4927:                                 next if ($restricted);
 4928:                             }
 4929:                             $numchanges ++;
 4930:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4931:                         } else {
 4932:                             $emptysec = 1;
 4933:                         }
 4934:                     }
 4935:                     if ($emptysec) {
 4936:                         unless ($udom eq $one) {
 4937:                             undef($restricted);
 4938:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4939:                                               $uname,$three,$start,$end,$one,$two,'',$credits,\%process_by,
 4940:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4941:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4942:                             next if ($restricted);
 4943:                         }
 4944:                         $numchanges ++;
 4945:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4946:                     }
 4947:                     next unless ($numchanges);
 4948:                 }
 4949:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4950:                     push(@rolechanges,$three);
 4951:                 }
 4952: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4953: 		# Activate roles for sections with two id numbers
 4954: 		# set start, end times, and the url for the class
 4955: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ?
 4956: 			      $env{'form.start_'.$1.'_'.$2} :
 4957: 			      $now );
 4958: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ?
 4959: 			      $env{'form.end_'.$1.'_'.$2} :
 4960: 			      0 );
 4961:                 my $one = $1;
 4962:                 my $two = $2;
 4963: 		my $url='/'.$one.'/';
 4964:                 my $id = $url.'_'.$two;
 4965:                 my ($cdom,$cnum) = split(/\//,$one);
 4966:                 # split multiple sections
 4967:                 my %sections = ();
 4968:                 my ($restricted,$numchanges);
 4969:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4970:                 if ($num_sections == 0) {
 4971:                     unless ($udom eq $one) {
 4972:                         $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 4973:                                           $uname,$two,$start,$end,$cdom,$cnum,'','',\%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,$url,$two,$start,$end,$one,undef,'',$context));
 4980:                 } else {
 4981:                     my $emptysec = 0;
 4982:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4983:                         if ($sec ne '') {
 4984:                             my $securl = $url.'/'.$sec;
 4985:                             my $secid = $securl.'_'.$two;
 4986:                             unless ($udom eq $one) {
 4987:                                 undef($restricted);
 4988:                                 $restricted = &Apache::lonuserutils::restricted_dom($context,$secid,$udom,
 4989:                                                   $uname,$two,$start,$end,$cdom,$cnum,$sec,'',\%process_by,
 4990:                                                   \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 4991:                                                   \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 4992:                                 next if ($restricted);
 4993:                             }
 4994:                             $numchanges ++;
 4995:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4996:                         } else {
 4997:                             $emptysec = 1;
 4998:                         }
 4999:                     }
 5000:                     if ($emptysec) {
 5001:                         unless ($udom eq $one) {
 5002:                             undef($restricted);
 5003:                             $restricted = &Apache::lonuserutils::restricted_dom($context,$id,$udom,
 5004:                                               $uname,$two,$start,$end,$cdom,$cnum,'','',\%process_by,
 5005:                                               \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 5006:                                               \%pending,\%notifydc,\%status,\%unauthorized,\%currqueued);
 5007:                             next if ($restricted);
 5008:                         }
 5009:                         $numchanges ++;
 5010:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 5011:                     }
 5012:                     next unless ($numchanges); 
 5013:                 }
 5014:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 5015:                     push(@rolechanges,$two);
 5016:                 }
 5017: 	    } else {
 5018: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 5019:             }
 5020:             foreach my $key (sort(keys(%disallowed))) {
 5021:                 $r->print('<p class="LC_warning">');
 5022:                 if (($key eq 'none') || ($key eq 'all')) {  
 5023:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 5024:                 } else {
 5025:                     $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>'));
 5026:                 }
 5027:                 $r->print('</p><p>'
 5028:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 5029:                              ,'<a href="javascript:history.go(-1)'
 5030:                              ,'</a>')
 5031:                          .'</p><br />'
 5032:                 );
 5033:             }
 5034: 	}
 5035:     } # End of foreach (keys(%env))
 5036:     if ((keys(%reject)) || (keys(%unauthorized))) {
 5037:         $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5038:     }
 5039:     if ((keys(%pending)) || (keys(%currqueued))) {
 5040:         $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5041:     }
 5042: # Flush the course logs so reverse user roles immediately updated
 5043:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5044:     if (@rolechanges == 0) {
 5045:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 5046:     }
 5047:     return @rolechanges;
 5048: }
 5049: 
 5050: sub get_user_credits {
 5051:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 5052:     if ($cdom eq '' || $cnum eq '') {
 5053:         return unless ($env{'request.course.id'});
 5054:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5055:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5056:     }
 5057:     my $credits;
 5058:     my %currhash =
 5059:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 5060:     if (keys(%currhash) > 0) {
 5061:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 5062:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 5063:         $credits = $items[$crdidx];
 5064:         $credits =~ s/[^\d\.]//g;
 5065:     }
 5066:     if ($credits eq $defaultcredits) {
 5067:         undef($credits);
 5068:     }
 5069:     return $credits;
 5070: }
 5071: 
 5072: sub enroll_single_student {
 5073:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 5074:         $showcredits,$defaultcredits) = @_;
 5075:     $r->print('<h3>');
 5076:     if ($crstype eq 'Community') {
 5077:         $r->print(&mt('Enrolling Member'));
 5078:     } else {
 5079:         $r->print(&mt('Enrolling Student'));
 5080:     }
 5081:     $r->print('</h3>');
 5082: 
 5083:     # Remove non alphanumeric values from section
 5084:     $env{'form.sections'}=~s/\W//g;
 5085: 
 5086:     my $credits;
 5087:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 5088:         $credits = $env{'form.credits'};
 5089:         $credits =~ s/[^\d\.]//g;
 5090:         if ($credits ne '') {
 5091:             if ($credits eq $defaultcredits) {
 5092:                 undef($credits);
 5093:             }
 5094:         }
 5095:     }
 5096:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 5097:     my (%got_role_approvals,%got_instdoms,%process_by,%instdoms,%pending,%reject,%notifydc,
 5098:         %status,%unauthorized,%currqueued);
 5099:     unless ($env{'form.ccdomain'} eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 5100:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5101:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5102:         my $csec = $env{'form.sections'};
 5103:         my $id = "/$cdom/$cnum";
 5104:         if ($csec ne '') {
 5105:             $id .= "/$csec";
 5106:         }
 5107:         $id .= '_st';
 5108:         if (&Apache::lonuserutils::restricted_dom($context,$id,$env{'form.ccdomain'},$env{'form.ccuname'},
 5109:                                                   'st',$startdate,$enddate,$cdom,$cnum,$csec,$credits,
 5110:                                                   \%process_by,\%instdoms,\%got_role_approvals,\%got_instdoms,
 5111:                                                   \%reject,\%pending,\%notifydc,\%status,\%unauthorized,\%currqueued)) {
 5112:             if ((keys(%reject)) || (keys(%unauthorized))) {
 5113:                 $r->print(&Apache::lonuserutils::print_roles_rejected($context,\%reject,\%unauthorized));
 5114:             }
 5115:             if ((keys(%pending)) || (keys(%currqueued))) {
 5116:                 $r->print(&Apache::lonuserutils::print_roles_queued($context,\%pending,\%notifydc,\%currqueued));
 5117:             }
 5118:             return;
 5119:         }
 5120:     }
 5121: 
 5122:     # Clean out any old student roles the user has in this class.
 5123:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 5124:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 5125:     my $enroll_result =
 5126:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 5127:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 5128:             $env{'form.cmiddlename'},$env{'form.clastname'},
 5129:             $env{'form.generation'},$env{'form.sections'},$enddate,
 5130:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 5131:             $credits);
 5132:     if ($enroll_result =~ /^ok/) {
 5133:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 5134:         if ($env{'form.sections'} ne '') {
 5135:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 5136:         }
 5137:         my ($showstart,$showend);
 5138:         if ($startdate <= $now) {
 5139:             $showstart = &mt('Access starts immediately');
 5140:         } else {
 5141:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 5142:         }
 5143:         if ($enddate == 0) {
 5144:             $showend = &mt('ends: no ending date');
 5145:         } else {
 5146:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 5147:         }
 5148:         $r->print('.<br />'.$showstart.'; '.$showend);
 5149:         if ($startdate <= $now && !$newuser) {
 5150:             $r->print('<p class="LC_info">');
 5151:             if ($crstype eq 'Community') {
 5152:                 $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.'));
 5153:             } else {
 5154:                 $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.'));
 5155:            }
 5156:            $r->print('</p>');
 5157:         }
 5158:     } else {
 5159:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 5160:     }
 5161:     return;
 5162: }
 5163: 
 5164: sub get_defaultquota_text {
 5165:     my ($settingstatus) = @_;
 5166:     my $defquotatext; 
 5167:     if ($settingstatus eq '') {
 5168:         $defquotatext = &mt('default');
 5169:     } else {
 5170:         my ($usertypes,$order) =
 5171:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 5172:         if ($usertypes->{$settingstatus} eq '') {
 5173:             $defquotatext = &mt('default');
 5174:         } else {
 5175:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 5176:         }
 5177:     }
 5178:     return $defquotatext;
 5179: }
 5180: 
 5181: sub update_result_form {
 5182:     my ($uhome) = @_;
 5183:     my $outcome = 
 5184:     '<form name="userupdate" method="post" action="">'."\n";
 5185:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 5186:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5187:     }
 5188:     if ($env{'form.origname'} ne '') {
 5189:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 5190:     }
 5191:     foreach my $item ('sortby','seluname','seludom') {
 5192:         if (exists($env{'form.'.$item})) {
 5193:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 5194:         }
 5195:     }
 5196:     if ($uhome eq 'no_host') {
 5197:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 5198:     }
 5199:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 5200:                 '<input type="hidden" name="currstate" value="" />'."\n".
 5201:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5202:                 '</form>';
 5203:     return $outcome;
 5204: }
 5205: 
 5206: sub quota_admin {
 5207:     my ($setquota,$changeHash,$name) = @_;
 5208:     my $quotachanged;
 5209:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 5210:         # Current user has quota modification privileges
 5211:         if (ref($changeHash) eq 'HASH') {
 5212:             $quotachanged = 1;
 5213:             $changeHash->{$name.'quota'} = $setquota;
 5214:         }
 5215:     }
 5216:     return $quotachanged;
 5217: }
 5218: 
 5219: sub tool_admin {
 5220:     my ($tool,$settool,$changeHash,$context) = @_;
 5221:     my $canchange = 0; 
 5222:     if ($context eq 'requestcourses') {
 5223:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 5224:             $canchange = 1;
 5225:         }
 5226:     } elsif ($context eq 'reqcrsotherdom') {
 5227:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 5228:             $canchange = 1;
 5229:         }
 5230:     } elsif ($context eq 'requestauthor') {
 5231:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5232:             $canchange = 1;
 5233:         }
 5234:     } elsif ($context eq 'authordefaults') {
 5235:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 5236:             $canchange = 1;
 5237:         }
 5238:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 5239:         # Current user has quota modification privileges
 5240:         $canchange = 1;
 5241:     }
 5242:     my $toolchanged;
 5243:     if ($canchange) {
 5244:         if (ref($changeHash) eq 'HASH') {
 5245:             $toolchanged = 1;
 5246:             if ($tool eq 'requestauthor') {
 5247:                 $changeHash->{$context} = $settool;
 5248:             } elsif (($tool eq 'managers') || ($tool eq 'editors') || ($tool eq 'archive')) {
 5249:                 $changeHash->{'author'.$tool} = $settool;
 5250:             } elsif ($tool eq 'webdav') {
 5251:                 $changeHash->{'tools.'.$tool} = $settool;
 5252:             } else {
 5253:                 $changeHash->{$context.'.'.$tool} = $settool;
 5254:             }
 5255:         }
 5256:     }
 5257:     return $toolchanged;
 5258: }
 5259: 
 5260: sub build_roles {
 5261:     my ($sectionstr,$sections,$role) = @_;
 5262:     my $num_sections = 0;
 5263:     if ($sectionstr=~ /,/) {
 5264:         my @secnums = split/,/,$sectionstr;
 5265:         if ($role eq 'st') {
 5266:             $secnums[0] =~ s/\W//g;
 5267:             $$sections{$secnums[0]} = 1;
 5268:             $num_sections = 1;
 5269:         } else {
 5270:             foreach my $sec (@secnums) {
 5271:                 $sec =~ ~s/\W//g;
 5272:                 if (!($sec eq "")) {
 5273:                     if (exists($$sections{$sec})) {
 5274:                         $$sections{$sec} ++;
 5275:                     } else {
 5276:                         $$sections{$sec} = 1;
 5277:                         $num_sections ++;
 5278:                     }
 5279:                 }
 5280:             }
 5281:         }
 5282:     } else {
 5283:         $sectionstr=~s/\W//g;
 5284:         unless ($sectionstr eq '') {
 5285:             $$sections{$sectionstr} = 1;
 5286:             $num_sections ++;
 5287:         }
 5288:     }
 5289: 
 5290:     return $num_sections;
 5291: }
 5292: 
 5293: # ========================================================== Custom Role Editor
 5294: 
 5295: sub custom_role_editor {
 5296:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5297:     my $action = $env{'form.customroleaction'};
 5298:     my ($rolename,$helpitem);
 5299:     if ($action eq 'new') {
 5300:         $rolename=$env{'form.newrolename'};
 5301:     } else {
 5302:         $rolename=$env{'form.rolename'};
 5303:     }
 5304: 
 5305:     my ($crstype,$context);
 5306:     if ($env{'request.course.id'}) {
 5307:         $crstype = &Apache::loncommon::course_type();
 5308:         $context = 'course';
 5309:         $helpitem = 'Course_Editing_Custom_Roles';
 5310:     } else {
 5311:         $context = 'domain';
 5312:         $crstype = 'course';
 5313:         $helpitem = 'Domain_Editing_Custom_Roles';
 5314:     }
 5315: 
 5316:     $rolename=~s/[^A-Za-z0-9]//gs;
 5317:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 5318: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 5319:                                    $permission);
 5320:         return;
 5321:     }
 5322: 
 5323:     my $formname = 'form1';
 5324:     my %privs=();
 5325:     my $body_top = '<h2>';
 5326: # ------------------------------------------------------- Does this role exist?
 5327:     my ($rdummy,$roledef)=
 5328: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5329:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5330:         $body_top .= &mt('Existing Role').' "';
 5331: # ------------------------------------------------- Get current role privileges
 5332:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 5333:         if ($privs{'system'} =~ /bre\&S/) {
 5334:             if ($context eq 'domain') {
 5335:                 $crstype = 'Course';
 5336:             } elsif ($crstype eq 'Community') {
 5337:                 $privs{'system'} =~ s/bre\&S//;
 5338:             }
 5339:         } elsif ($context eq 'domain') {
 5340:             $crstype = 'Course';
 5341:         }
 5342:     } else {
 5343:         $body_top .= &mt('New Role').' "';
 5344:         $roledef='';
 5345:     }
 5346:     $body_top .= $rolename.'"</h2>';
 5347: 
 5348: # ------------------------------------------------------- What can be assigned?
 5349:     my %full=();
 5350:     my %levels=(
 5351:                  course => {},
 5352:                  domain => {},
 5353:                  system => {},
 5354:                );
 5355:     my %levelscurrent=(
 5356:                         course => {},
 5357:                         domain => {},
 5358:                         system => {},
 5359:                       );
 5360:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5361:     my ($jsback,$elements) = &crumb_utilities();
 5362:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5363:     my $head_script =
 5364:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 5365:                                                   \%full,\@templateroles,$jsback);
 5366:     push (@{$brcrum},
 5367:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 5368:                text => "Pick custom role",
 5369:                faq  => 282,bug=>'Instructor Interface',},
 5370:               {href => "javascript:backPage(document.$formname,'','')",
 5371:                text => "Edit custom role",
 5372:                faq  => 282,
 5373:                bug  => 'Instructor Interface',
 5374:                help => $helpitem}
 5375:               );
 5376:     my $args = { bread_crumbs          => $brcrum,
 5377:                  bread_crumbs_component => 'User Management'};
 5378:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 5379:                                              $head_script,$args).
 5380:               $body_top);
 5381:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 5382:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 5383:                                                         \@templateroles,$prefix));
 5384: 
 5385:     $r->print(<<ENDCCF);
 5386: <input type="hidden" name="phase" value="set_custom_roles" />
 5387: <input type="hidden" name="rolename" value="$rolename" />
 5388: ENDCCF
 5389:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5390:                                                        \%levelscurrent,$prefix));
 5391:     $r->print(&Apache::loncommon::end_data_table().
 5392:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 5393:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 5394:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 5395:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 5396:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 5397: }
 5398: 
 5399: # ---------------------------------------------------------- Call to definerole
 5400: sub set_custom_role {
 5401:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 5402:     my $rolename=$env{'form.rolename'};
 5403:     $rolename=~s/[^A-Za-z0-9]//gs;
 5404:     if (!$rolename) {
 5405: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5406:         return;
 5407:     }
 5408:     my ($jsback,$elements) = &crumb_utilities();
 5409:     my $jscript = '<script type="text/javascript">'
 5410:                  .'// <![CDATA['."\n"
 5411:                  .$jsback."\n"
 5412:                  .'// ]]>'."\n"
 5413:                  .'</script>'."\n";
 5414:     my $helpitem = 'Course_Editing_Custom_Roles';
 5415:     if ($context eq 'domain') {
 5416:         $helpitem = 'Domain_Editing_Custom_Roles';
 5417:     }
 5418:     push(@{$brcrum},
 5419:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 5420:          text => "Pick custom role",
 5421:          faq  => 282,
 5422:          bug  => 'Instructor Interface',},
 5423:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 5424:          text => "Edit custom role",
 5425:          faq  => 282,
 5426:          bug  => 'Instructor Interface',},
 5427:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 5428:          text => "Result",
 5429:          faq  => 282,
 5430:          bug  => 'Instructor Interface',
 5431:          help => $helpitem,}
 5432:         );
 5433:     my $args = { bread_crumbs           => $brcrum,
 5434:                  bread_crumbs_component => 'User Management'};
 5435:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 5436: 
 5437:     my $newrole;
 5438:     my ($rdummy,$roledef)=
 5439: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 5440: 
 5441: # ------------------------------------------------------- Does this role exist?
 5442:     $r->print('<h3>');
 5443:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5444: 	$r->print(&mt('Existing Role').' "');
 5445:     } else {
 5446: 	$r->print(&mt('New Role').' "');
 5447: 	$roledef='';
 5448:         $newrole = 1;
 5449:     }
 5450:     $r->print($rolename.'"</h3>');
 5451: # ------------------------------------------------- Assign role and show result
 5452: 
 5453:     my $errmsg;
 5454:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 5455:     # Assign role and return result
 5456:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 5457:                                              $newprivs{'c'});
 5458:     if ($result ne 'ok') {
 5459:         $errmsg = ': '.$result;
 5460:     }
 5461:     my $message =
 5462:         &Apache::lonhtmlcommon::confirm_success(
 5463:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 5464:     if ($env{'request.course.id'}) {
 5465:         my $url='/'.$env{'request.course.id'};
 5466:         $url=~s/\_/\//g;
 5467:         $result =
 5468:             &Apache::lonnet::assigncustomrole(
 5469:                 $env{'user.domain'},$env{'user.name'},
 5470:                 $url,
 5471:                 $env{'user.domain'},$env{'user.name'},
 5472:                 $rolename,undef,undef,undef,$context);
 5473:         if ($result ne 'ok') {
 5474:             $errmsg = ': '.$result;
 5475:         }
 5476:         $message .=
 5477:             '<br />'
 5478:            .&Apache::lonhtmlcommon::confirm_success(
 5479:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 5480:     }
 5481:     $r->print(
 5482:         &Apache::loncommon::confirmwrapper($message)
 5483:        .'<br />'
 5484:        .&Apache::lonhtmlcommon::actionbox([
 5485:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 5486:            .&mt('Create or edit another custom role')
 5487:            .'</a>'])
 5488:        .'<form name="customresult" method="post" action="">'
 5489:        .&Apache::lonhtmlcommon::echo_form_input([])
 5490:        .'</form>'
 5491:     );
 5492: }
 5493: 
 5494: sub show_role_requests {
 5495:     my ($caller,$dom) = @_;
 5496:     my $showrolereqs;
 5497:     my %domconfig = &Apache::lonnet::get_dom('configuration',['privacy'],$dom);
 5498:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 5499:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 5500:             my %approvalconf = %{$domconfig{'privacy'}{'approval'}};
 5501:             foreach my $key ('instdom','extdom') {
 5502:                 if (ref($approvalconf{$key}) eq 'HASH') {
 5503:                     if (keys(%{$approvalconf{$key}})) {
 5504:                         foreach my $context ('domain','author','course','community') {
 5505:                             if ($approvalconf{$key}{$context} eq $caller) {
 5506:                                 $showrolereqs = 1;
 5507:                                 last if ($showrolereqs);
 5508:                             }
 5509:                         }
 5510:                     }
 5511:                 }
 5512:                 last if ($showrolereqs);
 5513:             }
 5514:         }
 5515:     }
 5516:     return $showrolereqs;
 5517: }
 5518: 
 5519: sub display_coauthor_managers {
 5520:     my ($permission) = @_;
 5521:     my $output;
 5522:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5523:         $output = '<form action="/adm/createuser" method="post" name="camanagers">'.
 5524:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 5525:                   '<p>';
 5526:         my (@possmanagers,@custommanagers);
 5527:         my %userenv =
 5528:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5529:                                              $env{'user.name'},
 5530:                                              'authormanagers');
 5531:         my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5532:                                                      ['active','future'],['ca']);
 5533:         if (keys(%ca_roles)) {
 5534:             foreach my $entry (sort(keys(%ca_roles))) {
 5535:                 if ($entry =~ /^($match_username\:$match_domain):ca$/) {
 5536:                     my $user = $1;
 5537:                     unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5538:                         push(@possmanagers,$user);
 5539:                     }
 5540:                 }
 5541:             }
 5542:         }
 5543:         if ($userenv{'authormanagers'} eq '') {
 5544:             $output .= &mt('Currently author manages co-author roles');
 5545:         } else {
 5546:             if (keys(%ca_roles)) {
 5547:                 foreach my $user (split(/,/,$userenv{'authormanagers'})) {
 5548:                     if ($user =~ /^($match_username)\:($match_domain)$/) {
 5549:                         if (exists($ca_roles{$user.':ca'})) {
 5550:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5551:                                 push(@custommanagers,$user);
 5552:                             }
 5553:                         }
 5554:                     }
 5555:                 }
 5556:             }
 5557:             if (@custommanagers) {
 5558:                 $output .= &mt('Co-authors with active or future roles who currently manage co-author roles: [_1]',
 5559:                               '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @custommanagers));
 5560:             } else {
 5561:                 $output .= &mt('Currently author manages co-author roles');
 5562:             }
 5563:         }
 5564:         $output .= "</p>\n";
 5565:         if (@possmanagers) {
 5566:             $output .= '<p>'.&mt('If checked, can manage').': ';
 5567:             foreach my $user (@possmanagers) {
 5568:                  my $checked;
 5569:                  if (grep(/^\Q$user\E$/,@custommanagers)) {
 5570:                      $checked = ' checked="checked"';
 5571:                  }
 5572:                  $output .= '<span style="LC_nobreak"><label>'.
 5573:                             '<input type="checkbox" name="custommanagers" '.
 5574:                             'value="'.&HTML::Entities::encode($user,'\'<>"&').'"'.$checked.' />'.
 5575:                             &Apache::loncommon::plainname(split(/:/,$user))." ($user)".'</label></span> '."\n";
 5576:             }
 5577:             $output .= '<input type="hidden" name="state" value="process" /></p>'."\n".
 5578:                        '<p><input type="submit" value="'.&mt('Save changes').'" /></p>'."\n";
 5579:         } else {
 5580:             $output .= '<p>'.&mt('No co-author roles assignable as manager').'</p>';
 5581:         }
 5582:         $output .= '</form>';
 5583:     } else {
 5584:         $output = '<span class="LC_warning">'.
 5585:                   &mt('You do not have permission to perform this action').
 5586:                   '</span>';
 5587:     }
 5588:     return $output;
 5589: }
 5590: 
 5591: sub update_coauthor_managers {
 5592:     my ($permission) = @_;
 5593:     my $output;
 5594:     if ((ref($permission) eq 'HASH') && ($permission->{'author'})) {
 5595:         my ($current,$newval,@possibles,@managers);
 5596:         my %userenv =
 5597:             &Apache::lonnet::userenvironment($env{'user.domain'},
 5598:                                              $env{'user.name'},
 5599:                                              'authormanagers');
 5600:         $current = $userenv{'authormanagers'};
 5601:         @possibles = &Apache::loncommon::get_env_multiple('form.custommanagers');
 5602:         if (@possibles) {
 5603:             my %ca_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 5604:                                                          ['active','future'],['ca']);
 5605:             if (keys(%ca_roles)) {
 5606:                 foreach my $user (@possibles) {
 5607:                     if ($user =~ /^($match_username):($match_domain)$/) {
 5608:                         if (exists($ca_roles{$user.':ca'})) {
 5609:                             unless ($user eq $env{'user.name'}.':'.$env{'user.domain'}) {
 5610:                                 push(@managers,$user);
 5611:                             }
 5612:                         }
 5613:                     }
 5614:                 }
 5615:                 if (@managers) {
 5616:                     $newval = join(',',sort(@managers));
 5617:                 }
 5618:             }
 5619:         }
 5620:         if ($current eq $newval) {
 5621:             $output = &mt('No changes made to management of co-author roles');
 5622:         } else {
 5623:             my $chgresult =
 5624:                 &Apache::lonnet::put('environment',{'authormanagers' => $newval},
 5625:                                      $env{'user.domain'},$env{'user.name'});
 5626:             if ($chgresult eq 'ok') {
 5627:                 &Apache::lonnet::appenv({'environment.authormanagers' => $newval});
 5628:                 my (@adds,@dels);
 5629:                 if ($newval eq '') {
 5630:                     @dels = split(/,/,$current);
 5631:                 } elsif ($current eq '') {
 5632:                     @adds = @managers;
 5633:                 } else {
 5634:                     my @old = split(/,/,$current);
 5635:                     my @diffs = &Apache::loncommon::compare_arrays(\@old,\@managers);
 5636:                     if (@diffs) {
 5637:                         foreach my $user (@diffs) {
 5638:                             if (grep(/^\Q$user\E$/,@old)) {
 5639:                                 push(@dels,$user);
 5640:                             } elsif (grep(/^\Q$user\E$/,@managers)) {
 5641:                                 push(@adds,$user);
 5642:                             }
 5643:                         }
 5644:                     }
 5645:                 }
 5646:                 my $key = "internal.manager./$env{'user.domain'}/$env{'user.name'}";
 5647:                 if (@dels) {
 5648:                     foreach my $user (@dels) {
 5649:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5650:                             &Apache::lonnet::del('environment',[$key],$2,$1);
 5651:                         }
 5652:                     }
 5653:                 }
 5654:                 if (@adds) {
 5655:                     foreach my $user (@adds) {
 5656:                         if ($user =~ /^($match_username):($match_domain)$/) {
 5657:                             &Apache::lonnet::put('environment',{$key => 1},$2,$1);
 5658:                         }
 5659:                     }
 5660:                 }
 5661:                 if ($newval eq '') {
 5662:                     $output = &mt('Management of co-authors set to be author-only');
 5663:                 } else {
 5664:                     $output .= &mt('Co-authors who can manage co-author roles set to: [_1]',
 5665:                                    '<br />'.join(', ',map { &Apache::loncommon::plainname(split(':',$_))." ($_)"; } @managers));
 5666:                 }
 5667:             }
 5668:         }
 5669:     } else {
 5670:         $output = '<span class="LC_warning">'.
 5671:                   &mt('You do not have permission to perform this action').
 5672:                   '</span>';
 5673:     }
 5674:     return $output;
 5675: }
 5676: 
 5677: # ================================================================ Main Handler
 5678: sub handler {
 5679:     my $r = shift;
 5680:     if ($r->header_only) {
 5681:        &Apache::loncommon::content_type($r,'text/html');
 5682:        $r->send_http_header;
 5683:        return OK;
 5684:     }
 5685:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 5686: 
 5687:     if ($env{'request.course.id'}) {
 5688:         $context = 'course';
 5689:         $crstype = &Apache::loncommon::course_type();
 5690:     } elsif ($env{'request.role'} =~ /^au\./) {
 5691:         $context = 'author';
 5692:     } elsif ($env{'request.role'} =~ m{^(ca|aa)\./$match_domain/$match_username$}) {
 5693:         $context = 'coauthor';
 5694:     } else {
 5695:         $context = 'domain';
 5696:     }
 5697: 
 5698:     my ($permission,$allowed) =
 5699:         &Apache::lonuserutils::get_permission($context,$crstype);
 5700:     if (($context eq 'coauthor') && ($allowed)) {
 5701:         $context = 'author';
 5702:     }
 5703: 
 5704:     if ($allowed) {
 5705:         my @allhelp;
 5706:         if ($context eq 'course') {
 5707:             $cid = $env{'request.course.id'};
 5708:             $cdom = $env{'course.'.$cid.'.domain'};
 5709:             $cnum = $env{'course.'.$cid.'.num'};
 5710: 
 5711:             if ($permission->{'cusr'}) {
 5712:                 push(@allhelp,'Course_Create_Class_List');
 5713:             }
 5714:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5715:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 5716:             }
 5717:             if ($permission->{'custom'}) {
 5718:                 push(@allhelp,'Course_Editing_Custom_Roles');
 5719:             }
 5720:             if ($permission->{'cusr'}) {
 5721:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 5722:             }
 5723:             unless ($permission->{'cusr_section'}) {
 5724:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 5725:                     push(@allhelp,'Course_Automated_Enrollment');
 5726:                 }
 5727:                 if (($permission->{'selfenrolladmin'}) || ($permission->{'selfenrollview'})) {
 5728:                     push(@allhelp,'Course_Approve_Selfenroll');
 5729:                 }
 5730:             }
 5731:             if ($permission->{'grp_manage'}) {
 5732:                 push(@allhelp,'Course_Manage_Group');
 5733:             }
 5734:             if ($permission->{'view'} || $permission->{'cusr'}) {
 5735:                 push(@allhelp,'Course_User_Logs');
 5736:             }
 5737:         } elsif ($context eq 'author') {
 5738:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5739:                            'Author_View_Coauthor_List','Author_User_Logs'));
 5740:         } elsif ($context eq 'coauthor') {
 5741:             if ($permission->{'cusr'}) {
 5742:                 push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 5743:                                'Author_View_Coauthor_List','Author_User_Logs'));
 5744:             } elsif ($permission->{'view'}) {
 5745:                 push(@allhelp,'Author_View_Coauthor_List');
 5746:             }
 5747:         } else {
 5748:             if ($permission->{'cusr'}) {
 5749:                 push(@allhelp,'Domain_Change_Privileges');
 5750:                 if ($permission->{'activity'}) {
 5751:                     push(@allhelp,'Domain_User_Access_Logs');
 5752:                 }
 5753:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 5754:                 if ($permission->{'custom'}) {
 5755:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 5756:                 }
 5757:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 5758:             } elsif ($permission->{'view'}) {
 5759:                 push(@allhelp,'Domain_View_Privileges');
 5760:                 if ($permission->{'activity'}) {
 5761:                     push(@allhelp,'Domain_User_Access_Logs');
 5762:                 }
 5763:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 5764:             }
 5765:         }
 5766:         if (@allhelp) {
 5767:             $allhelpitems = join(',',@allhelp);
 5768:         }
 5769:     }
 5770: 
 5771:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5772:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 5773:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue',
 5774:          'forceedit']);
 5775:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 5776:     my $args;
 5777:     my $brcrum = [];
 5778:     my $bread_crumbs_component = 'User Management';
 5779:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 5780:         $brcrum = [{href=>"/adm/createuser",
 5781:                     text=>"User Management",
 5782:                     help=>$allhelpitems}
 5783:                   ];
 5784:     }
 5785:     if (!$allowed) {
 5786:         if ($context eq 'course') {
 5787:             $r->internal_redirect('/adm/viewclasslist');
 5788:             return OK;
 5789:         } elsif ($context eq 'coauthor') {
 5790:             $r->internal_redirect('/adm/viewcoauthors');
 5791:             return OK;
 5792:         }
 5793:         $env{'user.error.msg'}=
 5794:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 5795:                                  "or view user status.";
 5796:         return HTTP_NOT_ACCEPTABLE;
 5797:     }
 5798: 
 5799:     &Apache::loncommon::content_type($r,'text/html');
 5800:     $r->send_http_header;
 5801: 
 5802:     my $showcredits;
 5803:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 5804:          ($context eq 'domain')) {
 5805:         my %domdefaults = 
 5806:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 5807:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 5808:             $showcredits = 1;
 5809:         }
 5810:     }
 5811: 
 5812:     # Main switch on form.action and form.state, as appropriate
 5813:     if (! exists($env{'form.action'})) {
 5814:         $args = {bread_crumbs => $brcrum,
 5815:                  bread_crumbs_component => $bread_crumbs_component}; 
 5816:         $r->print(&header(undef,$args));
 5817:         $r->print(&print_main_menu($permission,$context,$crstype));
 5818:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 5819:         my $helpitem = 'Course_Create_Class_List';
 5820:         if ($context eq 'author') {
 5821:             $helpitem = 'Author_Create_Coauthor_List';
 5822:         } elsif ($context eq 'domain') {
 5823:             $helpitem = 'Domain_Create_Users';
 5824:         }
 5825:         push(@{$brcrum},
 5826:               { href => '/adm/createuser?action=upload&state=',
 5827:                 text => 'Upload Users List',
 5828:                 help => $helpitem,
 5829:               });
 5830:         $bread_crumbs_component = 'Upload Users List';
 5831:         $args = {bread_crumbs           => $brcrum,
 5832:                  bread_crumbs_component => $bread_crumbs_component};
 5833:         $r->print(&header(undef,$args));
 5834:         $r->print('<form name="studentform" method="post" '.
 5835:                   'enctype="multipart/form-data" '.
 5836:                   ' action="/adm/createuser">'."\n");
 5837:         if (! exists($env{'form.state'})) {
 5838:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5839:         } elsif ($env{'form.state'} eq 'got_file') {
 5840:             my $result = 
 5841:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 5842:                                                                  $permission,
 5843:                                                                  $crstype,$showcredits);
 5844:             if ($result eq 'missingdata') {
 5845:                 delete($env{'form.state'});
 5846:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5847:             }
 5848:         } elsif ($env{'form.state'} eq 'enrolling') {
 5849:             if ($env{'form.datatoken'}) {
 5850:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 5851:                                                                     $permission,
 5852:                                                                     $showcredits);
 5853:                 if ($result eq 'missingdata') {
 5854:                     delete($env{'form.state'});
 5855:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5856:                 } elsif ($result eq 'invalidhome') {
 5857:                     $env{'form.state'} = 'got_file';
 5858:                     delete($env{'form.lcserver'});
 5859:                     my $result =
 5860:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 5861:                                                                          $crstype,$showcredits);
 5862:                     if ($result eq 'missingdata') {
 5863:                         delete($env{'form.state'});
 5864:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5865:                     }
 5866:                 }
 5867:             } else {
 5868:                 delete($env{'form.state'});
 5869:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5870:             }
 5871:         } else {
 5872:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 5873:         }
 5874:         $r->print('</form>');
 5875:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 5876:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 5877:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 5878:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 5879:         my $phase = $env{'form.phase'};
 5880:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 5881: 	&Apache::loncreateuser::restore_prev_selections();
 5882: 	my $srch;
 5883: 	foreach my $item (@search) {
 5884: 	    $srch->{$item} = $env{'form.'.$item};
 5885: 	}
 5886:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 5887:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 5888:             if ($env{'form.phase'} eq 'createnewuser') {
 5889:                 my $response;
 5890:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 5891:                     my $response =
 5892:                         '<span class="LC_warning">'
 5893:                        .&mt('You must specify a valid username. Only the following are allowed:'
 5894:                            .' letters numbers - . @')
 5895:                        .'</span>';
 5896:                     $env{'form.phase'} = '';
 5897:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 5898:                                                $crstype,$brcrum,$permission);
 5899:                 } else {
 5900:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 5901:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 5902:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 5903:                                                   $srch,$response,$context,
 5904:                                                   $permission,$crstype,$brcrum,
 5905:                                                   $showcredits);
 5906:                 }
 5907:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 5908:                 my ($currstate,$response,$forcenewuser,$results) = 
 5909:                     &user_search_result($context,$srch);
 5910:                 if ($env{'form.currstate'} eq 'modify') {
 5911:                     $currstate = $env{'form.currstate'};
 5912:                 }
 5913:                 if ($currstate eq 'select') {
 5914:                     &print_user_selection_page($r,$response,$srch,$results,
 5915:                                                \@search,$context,undef,$crstype,
 5916:                                                $brcrum);
 5917:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 5918:                     my ($ccuname,$ccdomain,$uhome);
 5919:                     if (($srch->{'srchby'} eq 'uname') && 
 5920:                         ($srch->{'srchtype'} eq 'exact')) {
 5921:                         $ccuname = $srch->{'srchterm'};
 5922:                         $ccdomain= $srch->{'srchdomain'};
 5923:                     } else {
 5924:                         my @matchedunames = keys(%{$results});
 5925:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 5926:                     }
 5927:                     $ccuname =&LONCAPA::clean_username($ccuname);
 5928:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 5929:                     if ($env{'form.action'} eq 'accesslogs') {
 5930:                         my $uhome;
 5931:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 5932:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 5933:                         }
 5934:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 5935:                             $env{'form.phase'} = '';
 5936:                             undef($forcenewuser);
 5937:                             #if ($response) {
 5938:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 5939:                             #        $response .= '<br /><br />';
 5940:                             #    }
 5941:                             #}
 5942:                             &print_username_entry_form($r,$context,$response,$srch,
 5943:                                                        $forcenewuser,$crstype,$brcrum,
 5944:                                                        $permission);
 5945:                         } else {
 5946:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5947:                         }
 5948:                     } else {
 5949:                         if ($env{'form.forcenewuser'}) {
 5950:                             $response = '';
 5951:                         }
 5952:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 5953:                                                       $srch,$response,$context,
 5954:                                                       $permission,$crstype,$brcrum);
 5955:                     }
 5956:                 } elsif ($currstate eq 'query') {
 5957:                     &print_user_query_page($r,'createuser',$brcrum);
 5958:                 } else {
 5959:                     $env{'form.phase'} = '';
 5960:                     &print_username_entry_form($r,$context,$response,$srch,
 5961:                                                $forcenewuser,$crstype,$brcrum,
 5962:                                                $permission);
 5963:                 }
 5964:             } elsif ($env{'form.phase'} eq 'userpicked') {
 5965:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 5966:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 5967:                 if ($env{'form.action'} eq 'accesslogs') {
 5968:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5969:                 } else {
 5970:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 5971:                                                   $context,$permission,$crstype,
 5972:                                                   $brcrum);
 5973:                 }
 5974:             } elsif ($env{'form.action'} eq 'accesslogs') {
 5975:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 5976:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 5977:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 5978:             }
 5979:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 5980:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 5981:         } else {
 5982:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 5983:                                        $brcrum,$permission);
 5984:         }
 5985:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 5986:         my $prefix;
 5987:         if ($env{'form.phase'} eq 'set_custom_roles') {
 5988:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 5989:         } else {
 5990:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 5991:         }
 5992:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 5993:              ($permission->{'cusr'}) && 
 5994:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5995:         push(@{$brcrum},
 5996:                  {href => '/adm/createuser?action=processauthorreq',
 5997:                   text => 'Authoring Space requests',
 5998:                   help => 'Domain_Role_Approvals'});
 5999:         $bread_crumbs_component = 'Authoring requests';
 6000:         if ($env{'form.state'} eq 'done') {
 6001:             push(@{$brcrum},
 6002:                      {href => '/adm/createuser?action=authorreqqueue',
 6003:                       text => 'Result',
 6004:                       help => 'Domain_Role_Approvals'});
 6005:             $bread_crumbs_component = 'Authoring request result';
 6006:         }
 6007:         $args = { bread_crumbs           => $brcrum,
 6008:                   bread_crumbs_component => $bread_crumbs_component};
 6009:         my $js = &usernamerequest_javascript();
 6010:         $r->print(&header(&add_script($js),$args));
 6011:         if (!exists($env{'form.state'})) {
 6012:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 6013:                                                                             $env{'request.role.domain'}));
 6014:         } elsif ($env{'form.state'} eq 'done') {
 6015:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 6016:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 6017:                                                                          $env{'request.role.domain'}));
 6018:         }
 6019:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 6020:              ($permission->{'cusr'}) &&
 6021:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 6022:         push(@{$brcrum},
 6023:                  {href => '/adm/createuser?action=processusernamereq',
 6024:                   text => 'LON-CAPA account requests',
 6025:                   help => 'Domain_Username_Approvals'});
 6026:         $bread_crumbs_component = 'Account requests';
 6027:         if ($env{'form.state'} eq 'done') {
 6028:             push(@{$brcrum},
 6029:                      {href => '/adm/createuser?action=usernamereqqueue',
 6030:                       text => 'Result',
 6031:                       help => 'Domain_Username_Approvals'});
 6032:             $bread_crumbs_component = 'LON-CAPA account request result';
 6033:         }
 6034:         $args = { bread_crumbs           => $brcrum,
 6035:                   bread_crumbs_component => $bread_crumbs_component};
 6036:         my $js = &usernamerequest_javascript();
 6037:         $r->print(&header(&add_script($js),$args));
 6038:         if (!exists($env{'form.state'})) {
 6039:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 6040:                                                                             $env{'request.role.domain'}));
 6041:         } elsif ($env{'form.state'} eq 'done') {
 6042:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 6043:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 6044:                                                                          $env{'request.role.domain'}));
 6045:         }
 6046:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 6047:              ($permission->{'cusr'})) {
 6048:         my $dom = $env{'form.domain'};
 6049:         my $uname = $env{'form.username'};
 6050:         my $warning;
 6051:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 6052:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 6053:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 6054:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 6055:                     if ($uhome eq 'no_host') {
 6056:                         my $queue = $env{'form.queue'};
 6057:                         my $reqkey = &escape($uname).'_'.$queue; 
 6058:                         my $namespace = 'usernamequeue';
 6059:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 6060:                         my %queued =
 6061:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 6062:                         unless ($queued{$reqkey}) {
 6063:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 6064:                         }
 6065:                     } else {
 6066:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 6067:                     }
 6068:                 } else {
 6069:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 6070:                 }
 6071:             } else {
 6072:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 6073:             }
 6074:         } else {
 6075:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 6076:         }
 6077:         my $args = { only_body => 1 };
 6078:         $r->print(&header(undef,$args).
 6079:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 6080:         if ($warning ne '') {
 6081:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 6082:         } else {
 6083:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 6084:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 6085:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6086:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6087:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 6088:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 6089:                         my %info =
 6090:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 6091:                         if (ref($info{$uname}) eq 'HASH') {
 6092:                             my $usertype = $info{$uname}{'inststatus'};
 6093:                             unless ($usertype) {
 6094:                                 $usertype = 'default';
 6095:                             }
 6096:                             my ($showstatus,$showemail,$pickstart);
 6097:                             my $numextras = 0;
 6098:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6099:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 6100:                                 if (ref($usertypes) eq 'HASH') {
 6101:                                     if ($usertypes->{$usertype}) {
 6102:                                         $showstatus = $usertypes->{$usertype};
 6103:                                     } else {
 6104:                                         $showstatus = $othertitle;
 6105:                                     }
 6106:                                     if ($showstatus) {
 6107:                                         $numextras ++;
 6108:                                     }
 6109:                                 }
 6110:                             }
 6111:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 6112:                                 $showemail = $info{$uname}{'email'};
 6113:                                 $numextras ++;
 6114:                             }
 6115:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 6116:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 6117:                                     $pickstart = 1;
 6118:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6119:                                     my ($num,$count);
 6120:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 6121:                                     $count += $numextras;
 6122:                                     foreach my $field (@{$infofields}) {
 6123:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 6124:                                         next unless ($infotitles->{$field});
 6125:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 6126:                                                   $info{$uname}{$field});
 6127:                                         $num ++;
 6128:                                         unless ($count == $num) {
 6129:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 6130:                                         }
 6131:                                     }
 6132:                                 }
 6133:                             }
 6134:                             if ($numextras) {
 6135:                                 unless ($pickstart) {
 6136:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 6137:                                     $pickstart = 1;
 6138:                                 }
 6139:                                 if ($showemail) {
 6140:                                     my $closure = '';
 6141:                                     unless ($showstatus) {
 6142:                                         $closure = 1;
 6143:                                     }
 6144:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 6145:                                               $showemail.
 6146:                                               &Apache::lonhtmlcommon::row_closure($closure));
 6147:                                 }
 6148:                                 if ($showstatus) {
 6149:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 6150:                                               $showstatus.
 6151:                                               &Apache::lonhtmlcommon::row_closure(1));
 6152:                                 }
 6153:                             }
 6154:                             if ($pickstart) { 
 6155:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 6156:                             } else {
 6157:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 6158:                             }
 6159:                         } else {
 6160:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 6161:                         }
 6162:                     }
 6163:                 }
 6164:             }
 6165:         }
 6166:         $r->print(&close_popup_form());
 6167:     } elsif (($env{'form.action'} eq 'listusers') && 
 6168:              ($permission->{'view'} || $permission->{'cusr'})) {
 6169:         my $helpitem = 'Course_View_Class_List';
 6170:         if ($context eq 'author') {
 6171:             $helpitem = 'Author_View_Coauthor_List';
 6172:         } elsif ($context eq 'domain') {
 6173:             $helpitem = 'Domain_View_Users_List';
 6174:         }
 6175:         if ($env{'form.phase'} eq 'bulkchange') {
 6176:             push(@{$brcrum},
 6177:                     {href => '/adm/createuser?action=listusers',
 6178:                      text => "List Users"},
 6179:                     {href => "/adm/createuser",
 6180:                      text => "Result",
 6181:                      help => $helpitem});
 6182:             $bread_crumbs_component = 'Update Users';
 6183:             $args = {bread_crumbs           => $brcrum,
 6184:                      bread_crumbs_component => $bread_crumbs_component};
 6185:             $r->print(&header(undef,$args));
 6186:             my $setting = $env{'form.roletype'};
 6187:             my $choice = $env{'form.bulkaction'};
 6188:             if ($permission->{'cusr'}) {
 6189:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 6190:             } else {
 6191:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 6192:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 6193:             }
 6194:         } else {
 6195:             push(@{$brcrum},
 6196:                     {href => '/adm/createuser?action=listusers',
 6197:                      text => "List Users",
 6198:                      help => $helpitem});
 6199:             $bread_crumbs_component = 'List Users';
 6200:             $args = {bread_crumbs           => $brcrum,
 6201:                      bread_crumbs_component => $bread_crumbs_component};
 6202:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 6203:             my $formname = 'studentform';
 6204:             my $hidecall = "hide_searching();";
 6205:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 6206:                 ($env{'form.roletype'} eq 'community'))) {
 6207:                 if ($env{'form.roletype'} eq 'course') {
 6208:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 6209:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 6210:                                                                 $formname);
 6211:                 } elsif ($env{'form.roletype'} eq 'community') {
 6212:                     $cb_jscript = 
 6213:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 6214:                     my %elements = (
 6215:                                       coursepick => 'radio',
 6216:                                       coursetotal => 'text',
 6217:                                       courselist => 'text',
 6218:                                    );
 6219:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 6220:                 }
 6221:                 $jscript .= &verify_user_display($context)."\n".
 6222:                             &Apache::loncommon::check_uncheck_jscript();
 6223:                 my $js = &add_script($jscript).$cb_jscript;
 6224:                 my $loadcode = 
 6225:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 6226:                 if ($loadcode ne '') {
 6227:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 6228:                 } else {
 6229:                     $args->{add_entries} = {onload => $hidecall};
 6230:                 }
 6231:                 $r->print(&header($js,$args));
 6232:             } else {
 6233:                 $args->{add_entries} = {onload => $hidecall};
 6234:                 $jscript = &verify_user_display($context).
 6235:                            &Apache::loncommon::check_uncheck_jscript(); 
 6236:                 $r->print(&header(&add_script($jscript),$args));
 6237:             }
 6238:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 6239:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 6240:                          $showcredits);
 6241:         }
 6242:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 6243:         my $brtext;
 6244:         if ($crstype eq 'Community') {
 6245:             $brtext = 'Drop Members';
 6246:         } else {
 6247:             $brtext = 'Drop Students';
 6248:         }
 6249:         push(@{$brcrum},
 6250:                 {href => '/adm/createuser?action=drop',
 6251:                  text => $brtext,
 6252:                  help => 'Course_Drop_Student'});
 6253:         if ($env{'form.state'} eq 'done') {
 6254:             push(@{$brcrum},
 6255:                      {href=>'/adm/createuser?action=drop',
 6256:                       text=>"Result"});
 6257:         }
 6258:         $bread_crumbs_component = $brtext;
 6259:         $args = {bread_crumbs           => $brcrum,
 6260:                  bread_crumbs_component => $bread_crumbs_component}; 
 6261:         $r->print(&header(undef,$args));
 6262:         if (!exists($env{'form.state'})) {
 6263:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 6264:         } elsif ($env{'form.state'} eq 'done') {
 6265:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 6266:                                                     $env{'form.action'});
 6267:         }
 6268:     } elsif ($env{'form.action'} eq 'dateselect') {
 6269:         if ($permission->{'cusr'}) {
 6270:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6271:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 6272:                                                                    $crstype,$showcredits));
 6273:         } else {
 6274:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6275:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 6276:         }
 6277:     } elsif ($env{'form.action'} eq 'selfenroll') {
 6278:         my %currsettings;
 6279:         if ($permission->{selfenrolladmin} || $permission->{selfenrollview}) {
 6280:             %currsettings = (
 6281:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 6282:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 6283:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 6284:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 6285:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 6286:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 6287:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 6288:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 6289:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 6290:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 6291:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 6292:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 6293:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 6294:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 6295:             );
 6296:         }
 6297:         if ($permission->{selfenrolladmin}) {
 6298:             push(@{$brcrum},
 6299:                     {href => '/adm/createuser?action=selfenroll',
 6300:                      text => "Configure Self-enrollment",
 6301:                      help => 'Course_Self_Enrollment'});
 6302:             if (!exists($env{'form.state'})) {
 6303:                 $args = { bread_crumbs           => $brcrum,
 6304:                           bread_crumbs_component => 'Configure Self-enrollment'};
 6305:                 $r->print(&header(undef,$args));
 6306:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6307:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 6308:             } elsif ($env{'form.state'} eq 'done') {
 6309:                 push (@{$brcrum},
 6310:                           {href=>'/adm/createuser?action=selfenroll',
 6311:                            text=>"Result"});
 6312:                 $args = { bread_crumbs           => $brcrum,
 6313:                           bread_crumbs_component => 'Self-enrollment result'};
 6314:                 $r->print(&header(undef,$args));
 6315:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6316:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 6317:             }
 6318:         } elsif ($permission->{selfenrollview}) {
 6319:             push(@{$brcrum},
 6320:                     {href => '/adm/createuser?action=selfenroll',
 6321:                      text => "View Self-enrollment configuration",
 6322:                      help => 'Course_Self_Enrollment'});
 6323:             $args = { bread_crumbs           => $brcrum,
 6324:                       bread_crumbs_component => 'Self-enrollment Settings'};
 6325:             $r->print(&header(undef,$args));
 6326:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 6327:             &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings,'',1);
 6328:         } else {
 6329:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6330:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 6331:         }
 6332:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 6333:         if ($permission->{selfenrolladmin}) {
 6334:             push(@{$brcrum},
 6335:                      {href => '/adm/createuser?action=selfenrollqueue',
 6336:                       text => 'Enrollment requests',
 6337:                       help => 'Course_Approve_Selfenroll'});
 6338:             $bread_crumbs_component = 'Enrollment requests';
 6339:             if ($env{'form.state'} eq 'done') {
 6340:                 push(@{$brcrum},
 6341:                          {href => '/adm/createuser?action=selfenrollqueue',
 6342:                           text => 'Result',
 6343:                           help => 'Course_Approve_Selfenroll'});
 6344:                 $bread_crumbs_component = 'Enrollment result';
 6345:             }
 6346:             $args = { bread_crumbs           => $brcrum,
 6347:                       bread_crumbs_component => $bread_crumbs_component};
 6348:             $r->print(&header(undef,$args));
 6349:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6350:             if (!exists($env{'form.state'})) {
 6351:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 6352:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 6353:                                                                                 $cdom,$cnum));
 6354:             } elsif ($env{'form.state'} eq 'done') {
 6355:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 6356:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 6357:                               $cdom,$cnum,$coursedesc));
 6358:             }
 6359:         } else {
 6360:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6361:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 6362:         }
 6363:     } elsif ($env{'form.action'} eq 'changelogs') {
 6364:         if ($permission->{cusr} || $permission->{view}) {
 6365:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 6366:         } else {
 6367:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6368:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 6369:         }
 6370:     } elsif ($env{'form.action'} eq 'helpdesk') {
 6371:         if (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6372:             ($permission->{'cusr'} || $permission->{'view'})) {
 6373:             if ($env{'form.state'} eq 'process') {
 6374:                 if ($permission->{'owner'}) {
 6375:                     &update_helpdeskaccess($r,$permission,$brcrum);
 6376:                 } else {
 6377:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 6378:                 }
 6379:             } else {
 6380:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 6381:             }
 6382:         } else {
 6383:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6384:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 6385:         }
 6386:     } elsif ($env{'form.action'} eq 'rolerequests') {
 6387:         if ($permission->{cusr} || $permission->{view}) {
 6388:             &print_queued_roles($r,$context,$permission,$brcrum);
 6389:         }
 6390:     } elsif ($env{'form.action'} eq 'queuedroles') {
 6391:         if (($permission->{cusr}) && ($context eq 'domain')) {
 6392:             if (&show_role_requests($context,$env{'request.role.domain'})) {
 6393:                 if ($env{'form.state'} eq 'done') {
 6394:                     &process_pendingroles($r,$context,$permission,$brcrum);
 6395:                 } else {
 6396:                     &print_pendingroles($r,$context,$permission,$brcrum);
 6397:                 }
 6398:             } else {
 6399:                 $r->print(&header(undef,{'no_nav_bar' => 1}).
 6400:                           '<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>');
 6401:             }
 6402:         } else {
 6403:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 6404:                      '<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>');
 6405:         }
 6406:     } elsif ($env{'form.action'} eq 'camanagers') {
 6407:         if (($permission->{cusr}) && ($context eq 'author')) {
 6408:             push(@{$brcrum},
 6409:                      {href => '/adm/createuser?action=camanagers',
 6410:                       text => 'Co-author Managers',
 6411:                       help => 'Author_Manage_Coauthors'});
 6412:             if ($env{'form.state'} eq 'process') {
 6413:                 push(@{$brcrum},
 6414:                          {href => '/adm/createuser?action=camanagers',
 6415:                           text => 'Result',
 6416:                           help => 'Author_Manage_Coauthors'});
 6417:             }
 6418:             $args = { bread_crumbs           => $brcrum };
 6419:             $r->print(&header(undef,$args));
 6420:             my $coursedesc = $env{'course.'.$cid.'.description'};
 6421:             if (!exists($env{'form.state'})) {
 6422:                 $r->print('<h3>'.&mt('Co-author Management').'</h3>'."\n".
 6423:                           &display_coauthor_managers($permission));
 6424:             } elsif ($env{'form.state'} eq 'process') {
 6425:                 $r->print('<h3>'.&mt('Co-author Management Update Result').'</h3>'."\n".
 6426:                           &update_coauthor_managers($permission));
 6427:             }
 6428:         }
 6429:     } elsif (($env{'form.action'} eq 'calist') && ($context eq 'author')) {
 6430:         if ($permission->{'cusr'}) {
 6431:             my ($role,$audom,$auname,$canview,$canedit) =
 6432:                 &Apache::lonviewcoauthors::get_allowable();
 6433:             if (($canedit) && ($env{'form.forceedit'})) {
 6434:                 &Apache::lonviewcoauthors::get_editor_crumbs($brcrum,'/adm/createuser');
 6435:                 my $args = { 'bread_crumbs' => $brcrum };
 6436:                 $r->print(&Apache::loncommon::start_page('Configure co-author listing',undef,
 6437:                                                          $args).
 6438:                           &Apache::lonviewcoauthors::edit_settings($audom,$auname,$role,
 6439:                                                                    '/adm/createuser'));
 6440:             } else {
 6441:                 push(@{$brcrum},
 6442:                        {href => '/adm/createuser?action=calist',
 6443:                         text => 'Coauthor-viewable list',
 6444:                         help => 'Author_List_Coauthors'});
 6445:                 my $args = { 'bread_crumbs' => $brcrum };
 6446:                 $r->print(&Apache::loncommon::start_page('Coauthor-viewable list',undef,
 6447:                                                          $args));
 6448:                 my %viewsettings =
 6449:                     &Apache::lonviewcoauthors::retrieve_view_settings($auname,$audom,$role);
 6450:                 if ($viewsettings{'show'} eq 'none') {
 6451:                     $r->print('<h3>'.&mt('Coauthor-viewable listing').'</h3>'.
 6452:                               '<p class="LC_info">'.
 6453:                               &mt('Listing of co-authors not enabled for this Authoring Space').
 6454:                               '</p>');
 6455:                 } else {
 6456:                     &Apache::lonviewcoauthors::print_coauthors($r,$auname,$audom,$role,
 6457:                                                                '/adm/createuser',\%viewsettings);
 6458:                 }
 6459:             }
 6460:         } else {
 6461:             $r->internal_redirect('/adm/viewcoauthors');
 6462:             return OK;
 6463:         }
 6464:     } else {
 6465:         $bread_crumbs_component = 'User Management';
 6466:         $args = { bread_crumbs           => $brcrum,
 6467:                   bread_crumbs_component => $bread_crumbs_component};
 6468:         $r->print(&header(undef,$args));
 6469:         $r->print(&print_main_menu($permission,$context,$crstype));
 6470:     }
 6471:     $r->print(&Apache::loncommon::end_page());
 6472:     return OK;
 6473: }
 6474: 
 6475: sub header {
 6476:     my ($jscript,$args) = @_;
 6477:     my $start_page;
 6478:     if (ref($args) eq 'HASH') {
 6479:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 6480:     } else {
 6481:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 6482:     }
 6483:     return $start_page;
 6484: }
 6485: 
 6486: sub add_script {
 6487:     my ($js) = @_;
 6488:     return '<script type="text/javascript">'."\n"
 6489:           .'// <![CDATA['."\n"
 6490:           .$js."\n"
 6491:           .'// ]]>'."\n"
 6492:           .'</script>'."\n";
 6493: }
 6494: 
 6495: sub usernamerequest_javascript {
 6496:     my $js = <<ENDJS;
 6497: 
 6498: function openusernamereqdisplay(dom,uname,queue) {
 6499:     var url = '/adm/createuser?action=displayuserreq';
 6500:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 6501:     var title = 'Account_Request_Browser';
 6502:     var options = 'scrollbars=1,resizable=1,menubar=0';
 6503:     options += ',width=700,height=600';
 6504:     var stdeditbrowser = open(url,title,options,'1');
 6505:     stdeditbrowser.focus();
 6506:     return;
 6507: }
 6508:  
 6509: ENDJS
 6510: }
 6511: 
 6512: sub close_popup_form {
 6513:     my $close= &mt('Close Window');
 6514:     return << "END";
 6515: <p><form name="displayreq" action="" method="post">
 6516: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 6517: </form></p>
 6518: END
 6519: }
 6520: 
 6521: sub verify_user_display {
 6522:     my ($context) = @_;
 6523:     my %lt = &Apache::lonlocal::texthash (
 6524:         course    => 'course(s): description, section(s), status',
 6525:         community => 'community(s): description, section(s), status',
 6526:         author    => 'author',
 6527:     );
 6528:     my $photos;
 6529:     if (($context eq 'course') && $env{'request.course.id'}) {
 6530:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 6531:     }
 6532:     my $output = <<"END";
 6533: 
 6534: function hide_searching() {
 6535:     if (document.getElementById('searching')) {
 6536:         document.getElementById('searching').style.display = 'none';
 6537:     }
 6538:     return;
 6539: }
 6540: 
 6541: function display_update() {
 6542:     document.studentform.action.value = 'listusers';
 6543:     document.studentform.phase.value = 'display';
 6544:     document.studentform.submit();
 6545: }
 6546: 
 6547: function updateCols(caller) {
 6548:     var context = '$context';
 6549:     var photos = '$photos';
 6550:     if (caller == 'Status') {
 6551:         if ((context == 'domain') && 
 6552:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6553:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 6554:             document.getElementById('showcolstatus').checked = false;
 6555:             document.getElementById('showcolstatus').disabled = 'disabled';
 6556:             document.getElementById('showcolstart').checked = false;
 6557:             document.getElementById('showcolend').checked = false;
 6558:         } else {
 6559:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6560:                 document.getElementById('showcolstatus').checked = true;
 6561:                 document.getElementById('showcolstatus').disabled = '';
 6562:                 document.getElementById('showcolstart').checked = true;
 6563:                 document.getElementById('showcolend').checked = true;
 6564:             } else {
 6565:                 document.getElementById('showcolstatus').checked = false;
 6566:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6567:                 document.getElementById('showcolstart').checked = false;
 6568:                 document.getElementById('showcolend').checked = false;
 6569:             }
 6570:             if (context == 'author') {
 6571:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Expired') {
 6572:                     document.getElementById('showcolmanager').checked = false;
 6573:                     document.getElementById('showcolmanager').disabled = 'disabled';
 6574:                 } else if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value != 'aa') {
 6575:                     document.getElementById('showcolmanager').checked = true;
 6576:                     document.getElementById('showcolmanager').disabled = '';
 6577:                 }
 6578:             }
 6579:         }
 6580:     }
 6581:     if (caller == 'output') {
 6582:         if (photos == 1) {
 6583:             if (document.getElementById('showcolphoto')) {
 6584:                 var photoitem = document.getElementById('showcolphoto');
 6585:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 6586:                     photoitem.checked = true;
 6587:                     photoitem.disabled = '';
 6588:                 } else {
 6589:                     photoitem.checked = false;
 6590:                     photoitem.disabled = 'disabled';
 6591:                 }
 6592:             }
 6593:         }
 6594:     }
 6595:     if (caller == 'showrole') {
 6596:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 6597:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 6598:             document.getElementById('showcolrole').checked = true;
 6599:             document.getElementById('showcolrole').disabled = '';
 6600:         } else {
 6601:             document.getElementById('showcolrole').checked = false;
 6602:             document.getElementById('showcolrole').disabled = 'disabled';
 6603:         }
 6604:         if (context == 'domain') {
 6605:             var quotausageshow = 0;
 6606:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 6607:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 6608:                 document.getElementById('showcolstatus').checked = false;
 6609:                 document.getElementById('showcolstatus').disabled = 'disabled';
 6610:                 document.getElementById('showcolstart').checked = false;
 6611:                 document.getElementById('showcolend').checked = false;
 6612:             } else {
 6613:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 6614:                     document.getElementById('showcolstatus').checked = true;
 6615:                     document.getElementById('showcolstatus').disabled = '';
 6616:                     document.getElementById('showcolstart').checked = true;
 6617:                     document.getElementById('showcolend').checked = true;
 6618:                 }
 6619:             }
 6620:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 6621:                 document.getElementById('showcolextent').disabled = 'disabled';
 6622:                 document.getElementById('showcolextent').checked = 'false';
 6623:                 document.getElementById('showextent').style.display='none';
 6624:                 document.getElementById('showcoltextextent').innerHTML = '';
 6625:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 6626:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 6627:                     if (document.getElementById('showcolauthorusage')) {
 6628:                         document.getElementById('showcolauthorusage').disabled = '';
 6629:                     }
 6630:                     if (document.getElementById('showcolauthorquota')) {
 6631:                         document.getElementById('showcolauthorquota').disabled = '';
 6632:                     }
 6633:                     quotausageshow = 1;
 6634:                 }
 6635:             } else {
 6636:                 document.getElementById('showextent').style.display='block';
 6637:                 document.getElementById('showextent').style.textAlign='left';
 6638:                 document.getElementById('showextent').style.textFace='normal';
 6639:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 6640:                     document.getElementById('showcolextent').disabled = '';
 6641:                     document.getElementById('showcolextent').checked = 'true';
 6642:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 6643:                 } else {
 6644:                     document.getElementById('showcolextent').disabled = '';
 6645:                     document.getElementById('showcolextent').checked = 'true';
 6646:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 6647:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 6648:                     } else {
 6649:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 6650:                     }
 6651:                 }
 6652:             }
 6653:             if (quotausageshow == 0)  {
 6654:                 if (document.getElementById('showcolauthorusage')) {
 6655:                     document.getElementById('showcolauthorusage').checked = false;
 6656:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 6657:                 }
 6658:                 if (document.getElementById('showcolauthorquota')) {
 6659:                     document.getElementById('showcolauthorquota').checked = false;
 6660:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 6661:                 }
 6662:             }
 6663:         }
 6664:         if (context == 'author') {
 6665:             if (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'aa') {
 6666:                 document.getElementById('showcolmanager').checked = false;
 6667:                 document.getElementById('showcolmanager').disabled = 'disabled';
 6668:             } else if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value != 'Expired') {
 6669:                 document.getElementById('showcolmanager').checked = true;
 6670:                 document.getElementById('showcolmanager').disabled = '';
 6671:             }
 6672:         }
 6673:     }
 6674:     return;
 6675: }
 6676: 
 6677: END
 6678:     return $output;
 6679: 
 6680: }
 6681: 
 6682: ###############################################################
 6683: ###############################################################
 6684: #  Menu Phase One
 6685: sub print_main_menu {
 6686:     my ($permission,$context,$crstype) = @_;
 6687:     my $linkcontext = $context;
 6688:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 6689:     if (($context eq 'course') && ($crstype eq 'Community')) {
 6690:         $linkcontext = lc($crstype);
 6691:         $stuterm = 'Members';
 6692:     }
 6693:     my %links = (
 6694:                 domain => {
 6695:                             upload     => 'Upload a File of Users',
 6696:                             singleuser => 'Add/Modify a User',
 6697:                             listusers  => 'Manage Users',
 6698:                             },
 6699:                 author => {
 6700:                             upload     => 'Upload a File of Co-authors',
 6701:                             singleuser => 'Add/Modify a Co-author',
 6702:                             listusers  => 'Manage Co-authors',
 6703:                             },
 6704:                 course => {
 6705:                             upload     => 'Upload a File of Course Users',
 6706:                             singleuser => 'Add/Modify a Course User',
 6707:                             listusers  => 'List and Modify Multiple Course Users',
 6708:                             },
 6709:                 community => {
 6710:                             upload     => 'Upload a File of Community Users',
 6711:                             singleuser => 'Add/Modify a Community User',
 6712:                             listusers  => 'List and Modify Multiple Community Users',
 6713:                            },
 6714:                 );
 6715:      my %linktitles = (
 6716:                 domain => {
 6717:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 6718:                             listusers  => 'Show and manage users in this domain.',
 6719:                             },
 6720:                 author => {
 6721:                             singleuser => 'Add a user with a co- or assistant author role.',
 6722:                             listusers  => 'Show and manage co- or assistant authors.',
 6723:                             },
 6724:                 course => {
 6725:                             singleuser => 'Add a user with a certain role to this course.',
 6726:                             listusers  => 'Show and manage users in this course.',
 6727:                             },
 6728:                 community => {
 6729:                             singleuser => 'Add a user with a certain role to this community.',
 6730:                             listusers  => 'Show and manage users in this community.',
 6731:                            },
 6732:                 );
 6733: 
 6734:   if ($linkcontext eq 'domain') {
 6735:       unless ($permission->{'cusr'}) {
 6736:           $links{'domain'}{'singleuser'} = 'View a User';
 6737:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 6738:       }
 6739:   } elsif ($linkcontext eq 'course') {
 6740:       unless ($permission->{'cusr'}) {
 6741:           $links{'course'}{'singleuser'} = 'View a Course User';
 6742:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 6743:           $links{'course'}{'listusers'} = 'List Course Users';
 6744:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 6745:       }
 6746:   } elsif ($linkcontext eq 'community') {
 6747:       unless ($permission->{'cusr'}) {
 6748:           $links{'community'}{'singleuser'} = 'View a Community User';
 6749:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 6750:           $links{'community'}{'listusers'} = 'List Community Users';
 6751:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 6752:       }
 6753:   }
 6754:   my @menu = ( {categorytitle => 'Single Users', 
 6755:          items =>
 6756:          [
 6757:             {
 6758:              linktext => $links{$linkcontext}{'singleuser'},
 6759:              icon => 'edit-redo.png',
 6760:              #help => 'Course_Change_Privileges',
 6761:              url => '/adm/createuser?action=singleuser',
 6762:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6763:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 6764:             },
 6765:          ]},
 6766: 
 6767:          {categorytitle => 'Multiple Users',
 6768:          items => 
 6769:          [
 6770:             {
 6771:              linktext => $links{$linkcontext}{'upload'},
 6772:              icon => 'uplusr.png',
 6773:              #help => 'Course_Create_Class_List',
 6774:              url => '/adm/createuser?action=upload',
 6775:              permission => $permission->{'cusr'},
 6776:              linktitle => 'Upload a CSV or a text file containing users.',
 6777:             },
 6778:             {
 6779:              linktext => $links{$linkcontext}{'listusers'},
 6780:              icon => 'mngcu.png',
 6781:              #help => 'Course_View_Class_List',
 6782:              url => '/adm/createuser?action=listusers',
 6783:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6784:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 6785:             },
 6786: 
 6787:          ]},
 6788: 
 6789:          {categorytitle => 'Administration',
 6790:          items => [ ]},
 6791:        );
 6792: 
 6793:     if ($context eq 'domain'){
 6794:         push(@{  $menu[0]->{items} }, # Single Users
 6795:             {
 6796:              linktext => 'User Access Log',
 6797:              icon => 'document-properties.png',
 6798:              #help => 'Domain_User_Access_Logs',
 6799:              url => '/adm/createuser?action=accesslogs',
 6800:              permission => $permission->{'activity'},
 6801:              linktitle => 'View user access log.',
 6802:             }
 6803:         );
 6804:         
 6805:         push(@{ $menu[2]->{items} }, #Category: Administration
 6806:             {
 6807:              linktext => 'Custom Roles',
 6808:              icon => 'emblem-photos.png',
 6809:              #help => 'Course_Editing_Custom_Roles',
 6810:              url => '/adm/createuser?action=custom',
 6811:              permission => $permission->{'custom'},
 6812:              linktitle => 'Configure a custom role.',
 6813:             },
 6814:             {
 6815:              linktext => 'Authoring Space Requests',
 6816:              icon => 'selfenrl-queue.png',
 6817:              #help => 'Domain_Role_Approvals',
 6818:              url => '/adm/createuser?action=processauthorreq',
 6819:              permission => $permission->{'cusr'},
 6820:              linktitle => 'Approve or reject author role requests',
 6821:             },
 6822:             {
 6823:              linktext => 'LON-CAPA Account Requests',
 6824:              icon => 'list-add.png',
 6825:              #help => 'Domain_Username_Approvals',
 6826:              url => '/adm/createuser?action=processusernamereq',
 6827:              permission => $permission->{'cusr'},
 6828:              linktitle => 'Approve or reject LON-CAPA account requests',
 6829:             },
 6830:             {
 6831:              linktext => 'Change Log',
 6832:              icon => 'document-properties.png',
 6833:              #help => 'Course_User_Logs',
 6834:              url => '/adm/createuser?action=changelogs',
 6835:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 6836:              linktitle => 'View change log.',
 6837:             },
 6838:         );
 6839:         
 6840:     }elsif ($context eq 'course'){
 6841:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 6842: 
 6843:         my %linktext = (
 6844:                          'Course'    => {
 6845:                                           single => 'Add/Modify a Student', 
 6846:                                           drop   => 'Drop Students',
 6847:                                           groups => 'Course Groups',
 6848:                                         },
 6849:                          'Community' => {
 6850:                                           single => 'Add/Modify a Member', 
 6851:                                           drop   => 'Drop Members',
 6852:                                           groups => 'Community Groups',
 6853:                                         },
 6854:                        );
 6855:         $linktext{'Placement'} = $linktext{'Course'};
 6856: 
 6857:         my %linktitle = (
 6858:             'Course' => {
 6859:                   single => 'Add a user with the role of student to this course',
 6860:                   drop   => 'Remove a student from this course.',
 6861:                   groups => 'Manage course groups',
 6862:                         },
 6863:             'Community' => {
 6864:                   single => 'Add a user with the role of member to this community',
 6865:                   drop   => 'Remove a member from this community.',
 6866:                   groups => 'Manage community groups',
 6867:                            },
 6868:         );
 6869: 
 6870:         $linktitle{'Placement'} = $linktitle{'Course'};
 6871: 
 6872:         push(@{ $menu[0]->{items} }, #Category: Single Users
 6873:             {   
 6874:              linktext => $linktext{$crstype}{'single'},
 6875:              #help => 'Course_Add_Student',
 6876:              icon => 'list-add.png',
 6877:              url => '/adm/createuser?action=singlestudent',
 6878:              permission => $permission->{'cusr'},
 6879:              linktitle => $linktitle{$crstype}{'single'},
 6880:             },
 6881:         );
 6882:         
 6883:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 6884:             {
 6885:              linktext => $linktext{$crstype}{'drop'},
 6886:              icon => 'edit-undo.png',
 6887:              #help => 'Course_Drop_Student',
 6888:              url => '/adm/createuser?action=drop',
 6889:              permission => $permission->{'cusr'},
 6890:              linktitle => $linktitle{$crstype}{'drop'},
 6891:             },
 6892:         );
 6893:         push(@{ $menu[2]->{items} }, #Category: Administration
 6894:             {
 6895:              linktext => 'Helpdesk Access',
 6896:              icon => 'helpdesk-access.png',
 6897:              #help => 'Course_Helpdesk_Access',
 6898:              url => '/adm/createuser?action=helpdesk',
 6899:              permission => (($permission->{'owner'} || $permission->{'co-owner'}) &&
 6900:                             ($permission->{'view'} || $permission->{'cusr'})),
 6901:              linktitle => 'Helpdesk access options',
 6902:             },
 6903:             {
 6904:              linktext => 'Custom Roles',
 6905:              icon => 'emblem-photos.png',
 6906:              #help => 'Course_Editing_Custom_Roles',
 6907:              url => '/adm/createuser?action=custom',
 6908:              permission => $permission->{'custom'},
 6909:              linktitle => 'Configure a custom role.',
 6910:             },
 6911:             {
 6912:              linktext => $linktext{$crstype}{'groups'},
 6913:              icon => 'grps.png',
 6914:              #help => 'Course_Manage_Group',
 6915:              url => '/adm/coursegroups?refpage=cusr',
 6916:              permission => $permission->{'grp_manage'},
 6917:              linktitle => $linktitle{$crstype}{'groups'},
 6918:             },
 6919:             {
 6920:              linktext => 'Change Log',
 6921:              icon => 'document-properties.png',
 6922:              #help => 'Course_User_Logs',
 6923:              url => '/adm/createuser?action=changelogs',
 6924:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 6925:              linktitle => 'View change log.',
 6926:             },
 6927:         );
 6928:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 6929:             push(@{ $menu[2]->{items} },
 6930:                     {
 6931:                      linktext => 'Enrollment Requests',
 6932:                      icon => 'selfenrl-queue.png',
 6933:                      #help => 'Course_Approve_Selfenroll',
 6934:                      url => '/adm/createuser?action=selfenrollqueue',
 6935:                      permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6936:                      linktitle =>'Approve or reject enrollment requests.',
 6937:                     },
 6938:             );
 6939:         }
 6940:         
 6941:         if (!exists($permission->{'cusr_section'})){
 6942:             if ($crstype ne 'Community') {
 6943:                 push(@{ $menu[2]->{items} },
 6944:                     {
 6945:                      linktext => 'Automated Enrollment',
 6946:                      icon => 'roles.png',
 6947:                      #help => 'Course_Automated_Enrollment',
 6948:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 6949:                                          && (($permission->{'cusr'}) ||
 6950:                                              ($permission->{'view'}))),
 6951:                      url  => '/adm/populate',
 6952:                      linktitle => 'Automated enrollment manager.',
 6953:                     }
 6954:                 );
 6955:             }
 6956:             push(@{ $menu[2]->{items} }, 
 6957:                 {
 6958:                  linktext => 'User Self-Enrollment',
 6959:                  icon => 'self_enroll.png',
 6960:                  #help => 'Course_Self_Enrollment',
 6961:                  url => '/adm/createuser?action=selfenroll',
 6962:                  permission => $permission->{'selfenrolladmin'} || $permission->{'selfenrollview'},
 6963:                  linktitle => 'Configure user self-enrollment.',
 6964:                 },
 6965:             );
 6966:         }
 6967:     } elsif ($context eq 'author') {
 6968:         push(@{ $menu[2]->{items} }, #Category: Administration
 6969:             {
 6970:              linktext => 'Change Log',
 6971:              icon => 'document-properties.png',
 6972:              #help => 'Course_User_Logs',
 6973:              url => '/adm/createuser?action=changelogs',
 6974:              permission => $permission->{'cusr'},
 6975:              linktitle => 'View change log.',
 6976:             },
 6977:             {
 6978:              linktext => 'Co-author Managers',
 6979:              icon => 'camanager.png',
 6980:              #help => 'Coauthor_Management',
 6981:              url => '/adm/createuser?action=camanagers',
 6982:              permission => $permission->{'author'},
 6983:              linktitle => 'Assign/Revoke right to manage co-author roles',
 6984:             },
 6985:             {
 6986:              linktext => 'Configure Co-author Listing',
 6987:              icon => 'coauthors.png',
 6988:              #help => 'Coauthor_Settings',
 6989:              url => '/adm/createuser?action=calist&forceedit=1',
 6990:              permission => ($permission->{'cusr'}),
 6991:              linktitle => 'Set availability of coauthor-viewable user listing',
 6992:             },
 6993:         );
 6994:     }
 6995:     push(@{ $menu[2]->{items} },
 6996:         {
 6997:          linktext => 'Role Requests (other domains)',
 6998:          icon => 'edit-find.png',
 6999:          #help => 'Role_Requests',
 7000:          url => '/adm/createuser?action=rolerequests',
 7001:          permission => $permission->{'cusr'},
 7002:          linktitle => 'Role requests for users in other domains',
 7003:         },
 7004:     );
 7005:     if (&show_role_requests($context,$env{'request.role.domain'})) {
 7006:         push(@{ $menu[2]->{items} },
 7007:             {
 7008:              linktext => 'Queued Role Assignments (this domain)',
 7009:              icon => 'edit-find.png',
 7010:              #help => 'Role_Approvals',
 7011:              url => '/adm/createuser?action=queuedroles',
 7012:              permission => $permission->{'cusr'},
 7013:              linktitle => "Role requests for this domain's users",
 7014:             },
 7015:         );
 7016:     }
 7017:     return Apache::lonhtmlcommon::generate_menu(@menu);
 7018: #               { text => 'View Log-in History',
 7019: #                 help => 'Course_User_Logins',
 7020: #                 action => 'logins',
 7021: #                 permission => $permission->{'cusr'},
 7022: #               });
 7023: }
 7024: 
 7025: sub restore_prev_selections {
 7026:     my %saveable_parameters = ('srchby'   => 'scalar',
 7027: 			       'srchin'   => 'scalar',
 7028: 			       'srchtype' => 'scalar',
 7029: 			       );
 7030:     &Apache::loncommon::store_settings('user','user_picker',
 7031: 				       \%saveable_parameters);
 7032:     &Apache::loncommon::restore_settings('user','user_picker',
 7033: 					 \%saveable_parameters);
 7034: }
 7035: 
 7036: sub print_selfenroll_menu {
 7037:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 7038:     my $crstype = &Apache::loncommon::course_type();
 7039:     my $formname = 'selfenroll';
 7040:     my $nolink = 1;
 7041:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 7042:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 7043:     my $setsec_js = 
 7044:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 7045:     my %alerts = &Apache::lonlocal::texthash(
 7046:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 7047:         butn => 'but no user types have been checked.',
 7048:         wilf => "Please uncheck 'activate' or check at least one type.",
 7049:     );
 7050:     my $disabled;
 7051:     if ($readonly) {
 7052:        $disabled = ' disabled="disabled"';
 7053:     }
 7054:     &js_escape(\%alerts);
 7055:     my $selfenroll_js = <<"ENDSCRIPT";
 7056: function update_types(caller,num) {
 7057:     var delidx = getIndexByName('selfenroll_delete');
 7058:     var actidx = getIndexByName('selfenroll_activate');
 7059:     if (caller == 'selfenroll_all') {
 7060:         var selall;
 7061:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7062:             if (document.$formname.selfenroll_all[i].checked) {
 7063:                 selall = document.$formname.selfenroll_all[i].value;
 7064:             }
 7065:         }
 7066:         if (selall == 1) {
 7067:             if (delidx != -1) {
 7068:                 if (document.$formname.selfenroll_delete.length) {
 7069:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7070:                         document.$formname.selfenroll_delete[j].checked = true;
 7071:                     }
 7072:                 } else {
 7073:                     document.$formname.elements[delidx].checked = true;
 7074:                 }
 7075:             }
 7076:             if (actidx != -1) {
 7077:                 if (document.$formname.selfenroll_activate.length) {
 7078:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7079:                         document.$formname.selfenroll_activate[j].checked = false;
 7080:                     }
 7081:                 } else {
 7082:                     document.$formname.elements[actidx].checked = false;
 7083:                 }
 7084:             }
 7085:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 7086:         }
 7087:     }
 7088:     if (caller == 'selfenroll_activate') {
 7089:         if (document.$formname.selfenroll_activate.length) {
 7090:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7091:                 if (document.$formname.selfenroll_activate[j].value == num) {
 7092:                     if (document.$formname.selfenroll_activate[j].checked) {
 7093:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7094:                             if (document.$formname.selfenroll_all[i].value == '1') {
 7095:                                 document.$formname.selfenroll_all[i].checked = false;
 7096:                             }
 7097:                             if (document.$formname.selfenroll_all[i].value == '0') {
 7098:                                 document.$formname.selfenroll_all[i].checked = true;
 7099:                             }
 7100:                         }
 7101:                     }
 7102:                 }
 7103:             }
 7104:         } else {
 7105:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 7106:                 if (document.$formname.selfenroll_all[i].value == '1') {
 7107:                     document.$formname.selfenroll_all[i].checked = false;
 7108:                 }
 7109:                 if (document.$formname.selfenroll_all[i].value == '0') {
 7110:                     document.$formname.selfenroll_all[i].checked = true;
 7111:                 }
 7112:             }
 7113:         }
 7114:     }
 7115:     if (caller == 'selfenroll_delete') {
 7116:         if (document.$formname.selfenroll_delete.length) {
 7117:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 7118:                 if (document.$formname.selfenroll_delete[j].value == num) {
 7119:                     if (document.$formname.selfenroll_delete[j].checked) {
 7120:                         var delindex = getIndexByName('selfenroll_types_'+num);
 7121:                         if (delindex != -1) { 
 7122:                             if (document.$formname.elements[delindex].length) {
 7123:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7124:                                     document.$formname.elements[delindex][k].checked = false;
 7125:                                 }
 7126:                             } else {
 7127:                                 document.$formname.elements[delindex].checked = false;
 7128:                             }
 7129:                         }
 7130:                     }
 7131:                 }
 7132:             }
 7133:         } else {
 7134:             if (document.$formname.selfenroll_delete.checked) {
 7135:                 var delindex = getIndexByName('selfenroll_types_'+num);
 7136:                 if (delindex != -1) {
 7137:                     if (document.$formname.elements[delindex].length) {
 7138:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 7139:                             document.$formname.elements[delindex][k].checked = false;
 7140:                         }
 7141:                     } else {
 7142:                         document.$formname.elements[delindex].checked = false;
 7143:                     }
 7144:                 }
 7145:             }
 7146:         }
 7147:     }
 7148:     return;
 7149: }
 7150: 
 7151: function validate_types(form) {
 7152:     var needaction = new Array();
 7153:     var countfail = 0;
 7154:     var actidx = getIndexByName('selfenroll_activate');
 7155:     if (actidx != -1) {
 7156:         if (document.$formname.selfenroll_activate.length) {
 7157:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 7158:                 var num = document.$formname.selfenroll_activate[j].value;
 7159:                 if (document.$formname.selfenroll_activate[j].checked) {
 7160:                     countfail = check_types(num,countfail,needaction)
 7161:                 }
 7162:             }
 7163:         } else {
 7164:             if (document.$formname.selfenroll_activate.checked) {
 7165:                 var num = document.$formname.selfenroll_activate.value;
 7166:                 countfail = check_types(num,countfail,needaction)
 7167:             }
 7168:         }
 7169:     }
 7170:     if (countfail > 0) {
 7171:         var msg = "$alerts{'acto'}\\n";
 7172:         var loopend = needaction.length -1;
 7173:         if (loopend > 0) {
 7174:             for (var m=0; m<loopend; m++) {
 7175:                 msg += needaction[m]+", ";
 7176:             }
 7177:         }
 7178:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 7179:         alert(msg);
 7180:         return; 
 7181:     }
 7182:     setSections(form);
 7183: }
 7184: 
 7185: function check_types(num,countfail,needaction) {
 7186:     var boxname = 'selfenroll_types_'+num;
 7187:     var typeidx = getIndexByName(boxname);
 7188:     var count = 0;
 7189:     if (typeidx != -1) {
 7190:         if (document.$formname.elements[boxname].length) {
 7191:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 7192:                 if (document.$formname.elements[boxname][k].checked) {
 7193:                     count ++;
 7194:                 }
 7195:             }
 7196:         } else {
 7197:             if (document.$formname.elements[typeidx].checked) {
 7198:                 count ++;
 7199:             }
 7200:         }
 7201:         if (count == 0) {
 7202:             var domidx = getIndexByName('selfenroll_dom_'+num);
 7203:             if (domidx != -1) {
 7204:                 var domname = document.$formname.elements[domidx].value;
 7205:                 needaction[countfail] = domname;
 7206:                 countfail ++;
 7207:             }
 7208:         }
 7209:     }
 7210:     return countfail;
 7211: }
 7212: 
 7213: function toggleNotify() {
 7214:     var selfenrollApproval = 0;
 7215:     if (document.$formname.selfenroll_approval.length) {
 7216:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 7217:             if (document.$formname.selfenroll_approval[i].checked) {
 7218:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 7219:                 break;        
 7220:             }
 7221:         }
 7222:     }
 7223:     if (document.getElementById('notified')) {
 7224:         if (selfenrollApproval == 0) {
 7225:             document.getElementById('notified').style.display='none';
 7226:         } else {
 7227:             document.getElementById('notified').style.display='block';
 7228:         }
 7229:     }
 7230:     return;
 7231: }
 7232: 
 7233: function getIndexByName(item) {
 7234:     for (var i=0;i<document.$formname.elements.length;i++) {
 7235:         if (document.$formname.elements[i].name == item) {
 7236:             return i;
 7237:         }
 7238:     }
 7239:     return -1;
 7240: }
 7241: ENDSCRIPT
 7242: 
 7243:     my $output = '<script type="text/javascript">'."\n".
 7244:                  '// <![CDATA['."\n".
 7245:                  $setsec_js."\n".$selfenroll_js."\n".
 7246:                  '// ]]>'."\n".
 7247:                  '</script>'."\n".
 7248:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 7249:     my $visactions = &cat_visibility($cdom);
 7250:     my ($cathash,%cattype);
 7251:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 7252:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 7253:         $cathash = $domconfig{'coursecategories'}{'cats'};
 7254:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 7255:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 7256:         if ($cattype{'auth'} eq '') {
 7257:             $cattype{'auth'} = 'std';
 7258:         }
 7259:         if ($cattype{'unauth'} eq '') {
 7260:             $cattype{'unauth'} = 'std';
 7261:         }
 7262:     } else {
 7263:         $cathash = {};
 7264:         $cattype{'auth'} = 'std';
 7265:         $cattype{'unauth'} = 'std';
 7266:     }
 7267:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 7268:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7269:                   '<br />'.
 7270:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7271:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 7272:                   '</ul>');
 7273:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 7274:         if ($currsettings->{'uniquecode'}) {
 7275:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 7276:         } else {
 7277:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 7278:                   '<br />'.
 7279:                   '<br />'.$visactions->{'take'}.'<ul>'.
 7280:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 7281:                   '</ul><br />');
 7282:         }
 7283:     } else {
 7284:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 7285:         if (ref($visactions) eq 'HASH') {
 7286:             if ($visible) {
 7287:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 7288:            } else {
 7289:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 7290:                           .$visactions->{'yous'}.
 7291:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 7292:                 if (ref($vismsgs) eq 'ARRAY') {
 7293:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 7294:                     foreach my $item (@{$vismsgs}) {
 7295:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 7296:                     }
 7297:                     $output .= '</ul>';
 7298:                 }
 7299:                 $output .= '</p>';
 7300:             }
 7301:         }
 7302:     }
 7303:     my $actionhref = '/adm/createuser';
 7304:     if ($context eq 'domain') {
 7305:         $actionhref = '/adm/modifycourse';
 7306:     }
 7307: 
 7308:     my %noedit;
 7309:     unless ($context eq 'domain') {
 7310:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 7311:     }
 7312:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 7313:                &Apache::lonhtmlcommon::start_pick_box();
 7314:     if (ref($row) eq 'ARRAY') {
 7315:         foreach my $item (@{$row}) {
 7316:             my $title = $item; 
 7317:             if (ref($lt) eq 'HASH') {
 7318:                 $title = $lt->{$item};
 7319:             }
 7320:             $output .= &Apache::lonhtmlcommon::row_title($title);
 7321:             if ($item eq 'types') {
 7322:                 my $curr_types;
 7323:                 if (ref($currsettings) eq 'HASH') {
 7324:                     $curr_types = $currsettings->{'selfenroll_types'};
 7325:                 }
 7326:                 if ($noedit{$item}) {
 7327:                     if ($curr_types eq '*') {
 7328:                         $output .= &mt('Any user in any domain');   
 7329:                     } else {
 7330:                         my @entries = split(/;/,$curr_types);
 7331:                         if (@entries > 0) {
 7332:                             $output .= '<ul>'; 
 7333:                             foreach my $entry (@entries) {
 7334:                                 my ($currdom,$typestr) = split(/:/,$entry);
 7335:                                 next if ($typestr eq '');
 7336:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 7337:                                 my @currinsttypes = split(',',$typestr);
 7338:                                 my ($othertitle,$usertypes,$types) = 
 7339:                                     &Apache::loncommon::sorted_inst_types($currdom);
 7340:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7341:                                     $usertypes->{'any'} = &mt('any user'); 
 7342:                                     if (keys(%{$usertypes}) > 0) {
 7343:                                         $usertypes->{'other'} = &mt('other users');
 7344:                                     }
 7345:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 7346:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 7347:                                  }
 7348:                             }
 7349:                             $output .= '</ul>';
 7350:                         } else {
 7351:                             $output .= &mt('None');
 7352:                         }
 7353:                     }
 7354:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7355:                     next;
 7356:                 }
 7357:                 my $showdomdesc = 1;
 7358:                 my $includeempty = 1;
 7359:                 my $num = 0;
 7360:                 $output .= &Apache::loncommon::start_data_table().
 7361:                            &Apache::loncommon::start_data_table_row()
 7362:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 7363:                            .&mt('Any user in any domain:')
 7364:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 7365:                 if ($curr_types eq '*') {
 7366:                     $output .= ' checked="checked" '; 
 7367:                 }
 7368:                 $output .= 'onchange="javascript:update_types('.
 7369:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 7370:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 7371:                 if ($curr_types ne '*') {
 7372:                     $output .= ' checked="checked" ';
 7373:                 }
 7374:                 $output .= ' onchange="javascript:update_types('.
 7375:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 7376:                            &Apache::loncommon::end_data_table_row().
 7377:                            &Apache::loncommon::end_data_table().
 7378:                            &mt('Or').'<br />'.
 7379:                            &Apache::loncommon::start_data_table();
 7380:                 my %currdoms;
 7381:                 if ($curr_types eq '') {
 7382:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 7383:                 } elsif ($curr_types ne '*') {
 7384:                     my @entries = split(/;/,$curr_types);
 7385:                     if (@entries > 0) {
 7386:                         foreach my $entry (@entries) {
 7387:                             my ($currdom,$typestr) = split(/:/,$entry);
 7388:                             $currdoms{$currdom} = 1;
 7389:                             my $domdesc = &Apache::lonnet::domain($currdom);
 7390:                             my @currinsttypes = split(',',$typestr);
 7391:                             $output .= &Apache::loncommon::start_data_table_row()
 7392:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 7393:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 7394:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 7395:                                        .'" value="'.$currdom.'" /></span><br />'
 7396:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 7397:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 7398:                                        .&mt('Delete').'</label></span></td>';
 7399:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 7400:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 7401:                                        .&Apache::loncommon::end_data_table_row();
 7402:                             $num ++;
 7403:                         }
 7404:                     }
 7405:                 }
 7406:                 my $add_domtitle = &mt('Users in additional domain:');
 7407:                 if ($curr_types eq '*') { 
 7408:                     $add_domtitle = &mt('Users in specific domain:');
 7409:                 } elsif ($curr_types eq '') {
 7410:                     $add_domtitle = &mt('Users in other domain:');
 7411:                 }
 7412:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 7413:                 $output .= &Apache::loncommon::start_data_table_row()
 7414:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 7415:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 7416:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 7417:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 7418:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 7419:                            .&Apache::loncommon::end_data_table();
 7420:             } elsif ($item eq 'registered') {
 7421:                 my ($regon,$regoff);
 7422:                 my $registered;
 7423:                 if (ref($currsettings) eq 'HASH') {
 7424:                     $registered = $currsettings->{'selfenroll_registered'};
 7425:                 }
 7426:                 if ($noedit{$item}) {
 7427:                     if ($registered) {
 7428:                         $output .= &mt('Must be registered in course');
 7429:                     } else {
 7430:                         $output .= &mt('No requirement');
 7431:                     }
 7432:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7433:                     next;
 7434:                 }
 7435:                 if ($registered) {
 7436:                     $regon = ' checked="checked" ';
 7437:                     $regoff = '';
 7438:                 } else {
 7439:                     $regon = '';
 7440:                     $regoff = ' checked="checked" ';
 7441:                 }
 7442:                 $output .= '<label>'.
 7443:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 7444:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 7445:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 7446:                            &mt('No').'</label>';
 7447:             } elsif ($item eq 'enroll_dates') {
 7448:                 my ($starttime,$endtime);
 7449:                 if (ref($currsettings) eq 'HASH') {
 7450:                     $starttime = $currsettings->{'selfenroll_start_date'};
 7451:                     $endtime = $currsettings->{'selfenroll_end_date'};
 7452:                     if ($starttime eq '') {
 7453:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7454:                     }
 7455:                     if ($endtime eq '') {
 7456:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7457:                     }
 7458:                 }
 7459:                 if ($noedit{$item}) {
 7460:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7461:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7462:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7463:                     next;
 7464:                 }
 7465:                 my $startform =
 7466:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 7467:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7468:                 my $endform =
 7469:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 7470:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7471:                 $output .= &selfenroll_date_forms($startform,$endform);
 7472:             } elsif ($item eq 'access_dates') {
 7473:                 my ($starttime,$endtime);
 7474:                 if (ref($currsettings) eq 'HASH') {
 7475:                     $starttime = $currsettings->{'selfenroll_start_access'};
 7476:                     $endtime = $currsettings->{'selfenroll_end_access'};
 7477:                     if ($starttime eq '') {
 7478:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 7479:                     }
 7480:                     if ($endtime eq '') {
 7481:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 7482:                     }
 7483:                 }
 7484:                 if ($noedit{$item}) {
 7485:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 7486:                                                           &Apache::lonlocal::locallocaltime($endtime));
 7487:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7488:                     next;
 7489:                 }
 7490:                 my $startform =
 7491:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 7492:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7493:                 my $endform =
 7494:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 7495:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 7496:                 $output .= &selfenroll_date_forms($startform,$endform);
 7497:             } elsif ($item eq 'section') {
 7498:                 my $currsec;
 7499:                 if (ref($currsettings) eq 'HASH') {
 7500:                     $currsec = $currsettings->{'selfenroll_section'};
 7501:                 }
 7502:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 7503:                 my $newsecval;
 7504:                 if ($currsec ne 'none' && $currsec ne '') {
 7505:                     if (!defined($sections_count{$currsec})) {
 7506:                         $newsecval = $currsec;
 7507:                     }
 7508:                 }
 7509:                 if ($noedit{$item}) {
 7510:                     if ($currsec ne '') {
 7511:                         $output .= $currsec;
 7512:                     } else {
 7513:                         $output .= &mt('No specific section');
 7514:                     }
 7515:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 7516:                     next;
 7517:                 }
 7518:                 my $sections_select = 
 7519:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 7520:                 $output .= '<table class="LC_createuser">'."\n".
 7521:                            '<tr class="LC_section_row">'."\n".
 7522:                            '<td align="center">'.&mt('Existing sections')."\n".
 7523:                            '<br />'.$sections_select.'</td><td align="center">'.
 7524:                            &mt('New section').'<br />'."\n".
 7525:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 7526:                            '<input type="hidden" name="sections" value="" />'."\n".
 7527:                            '</td></tr></table>'."\n";
 7528:             } elsif ($item eq 'approval') {
 7529:                 my ($currnotified,$currapproval,%appchecked);
 7530:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 7531:                 if (ref($currsettings) eq 'HASH') {
 7532:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 7533:                     $currapproval = $currsettings->{'selfenroll_approval'};
 7534:                 }
 7535:                 if ($currapproval !~ /^[012]$/) {
 7536:                     $currapproval = 0;
 7537:                 }
 7538:                 if ($noedit{$item}) {
 7539:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 7540:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 7541:                     next;
 7542:                 }
 7543:                 $appchecked{$currapproval} = ' checked="checked"';
 7544:                 for my $i (0..2) {
 7545:                     $output .= '<label>'.
 7546:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 7547:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 7548:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 7549:                 }
 7550:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 7551:                 my (@ccs,%notified);
 7552:                 my $ccrole = 'cc';
 7553:                 if ($crstype eq 'Community') {
 7554:                     $ccrole = 'co';
 7555:                 }
 7556:                 if ($advhash{$ccrole}) {
 7557:                     @ccs = split(/,/,$advhash{$ccrole});
 7558:                 }
 7559:                 if ($currnotified) {
 7560:                     foreach my $current (split(/,/,$currnotified)) {
 7561:                         $notified{$current} = 1;
 7562:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 7563:                             push(@ccs,$current);
 7564:                         }
 7565:                     }
 7566:                 }
 7567:                 if (@ccs) {
 7568:                     my $style;
 7569:                     unless ($currapproval) {
 7570:                         $style = ' style="display: none;"'; 
 7571:                     }
 7572:                     $output .= '<br /><div id="notified"'.$style.'>'.
 7573:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 7574:                                &Apache::loncommon::start_data_table().
 7575:                                &Apache::loncommon::start_data_table_row();
 7576:                     my $count = 0;
 7577:                     my $numcols = 4;
 7578:                     foreach my $cc (sort(@ccs)) {
 7579:                         my $notifyon;
 7580:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 7581:                         if ($notified{$cc}) {
 7582:                             $notifyon = ' checked="checked" ';
 7583:                         }
 7584:                         if ($count && !$count%$numcols) {
 7585:                             $output .= &Apache::loncommon::end_data_table_row().
 7586:                                        &Apache::loncommon::start_data_table_row()
 7587:                         }
 7588:                         $output .= '<td><span class="LC_nobreak"><label>'.
 7589:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 7590:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 7591:                                    '</label></span></td>';
 7592:                         $count ++;
 7593:                     }
 7594:                     my $rem = $count%$numcols;
 7595:                     if ($rem) {
 7596:                         my $emptycols = $numcols - $rem;
 7597:                         for (my $i=0; $i<$emptycols; $i++) { 
 7598:                             $output .= '<td>&nbsp;</td>';
 7599:                         }
 7600:                     }
 7601:                     $output .= &Apache::loncommon::end_data_table_row().
 7602:                                &Apache::loncommon::end_data_table().
 7603:                                '</div>';
 7604:                 }
 7605:             } elsif ($item eq 'limit') {
 7606:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 7607:                 if (ref($currsettings) eq 'HASH') {
 7608:                     $currlim = $currsettings->{'selfenroll_limit'};
 7609:                     $currcap = $currsettings->{'selfenroll_cap'};
 7610:                 }
 7611:                 if ($noedit{$item}) {
 7612:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 7613:                         if ($currlim eq 'allstudents') {
 7614:                             $output .= &mt('Limit by total students');
 7615:                         } elsif ($currlim eq 'selfenrolled') {
 7616:                             $output .= &mt('Limit by total self-enrolled students');
 7617:                         }
 7618:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 7619:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 7620:                     } else {
 7621:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 7622:                     }
 7623:                     next;
 7624:                 }
 7625:                 if ($currlim eq 'allstudents') {
 7626:                     $crslimit = ' checked="checked" ';
 7627:                     $selflimit = ' ';
 7628:                     $nolimit = ' ';
 7629:                 } elsif ($currlim eq 'selfenrolled') {
 7630:                     $crslimit = ' ';
 7631:                     $selflimit = ' checked="checked" ';
 7632:                     $nolimit = ' '; 
 7633:                 } else {
 7634:                     $crslimit = ' ';
 7635:                     $selflimit = ' ';
 7636:                     $nolimit = ' checked="checked" ';
 7637:                 }
 7638:                 $output .= '<table><tr><td><label>'.
 7639:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 7640:                            &mt('No limit').'</label></td><td><label>'.
 7641:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 7642:                            &mt('Limit by total students').'</label></td><td><label>'.
 7643:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 7644:                            &mt('Limit by total self-enrolled students').
 7645:                            '</td></tr><tr>'.
 7646:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 7647:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 7648:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 7649:             }
 7650:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 7651:         }
 7652:     }
 7653:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 7654:     unless ($readonly) {
 7655:         $output .= '<input type="button" name="selfenrollconf" value="'
 7656:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 7657:     }
 7658:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 7659:               .'<input type="hidden" name="state" value="done" />'."\n"
 7660:               .$additional.'</form>';
 7661:     $r->print($output);
 7662:     return;
 7663: }
 7664: 
 7665: sub get_noedit_fields {
 7666:     my ($cdom,$cnum,$crstype,$row) = @_;
 7667:     my %noedit;
 7668:     if (ref($row) eq 'ARRAY') {
 7669:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 7670:                                                            'internal.selfenrollmgrdc',
 7671:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 7672:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 7673:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 7674:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 7675:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 7676:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 7677:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 7678: 
 7679:         foreach my $item (@{$row}) {
 7680:             next if ($specific_managebycc{$item});
 7681:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 7682:                 $noedit{$item} = 1;
 7683:             }
 7684:         }
 7685:     }
 7686:     return %noedit;
 7687: }
 7688: 
 7689: sub visible_in_stdcat {
 7690:     my ($cdom,$cnum,$domconf) = @_;
 7691:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 7692:     unless (ref($domconf) eq 'HASH') {
 7693:         return ($visible,$cansetvis,\@vismsgs);
 7694:     }
 7695:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7696:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 7697:             $settable{'togglecats'} = 1;
 7698:         }
 7699:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 7700:             $settable{'categorize'} = 1;
 7701:         }
 7702:         $cathash = $domconf->{'coursecategories'}{'cats'};
 7703:     }
 7704:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 7705:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 7706:     } elsif ($settable{'togglecats'}) {
 7707:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 7708:     } elsif ($settable{'categorize'}) {
 7709:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 7710:     } else {
 7711:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 7712:     }
 7713:      
 7714:     my %currsettings =
 7715:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 7716:                              $cdom,$cnum);
 7717:     $visible = 0;
 7718:     if ($currsettings{'internal.coursecode'} ne '') {
 7719:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7720:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7721:             if (ref($cathash) eq 'HASH') {
 7722:                 if ($cathash->{'instcode::0'} eq '') {
 7723:                     push(@vismsgs,'dc_addinst'); 
 7724:                 } else {
 7725:                     $visible = 1;
 7726:                 }
 7727:             } else {
 7728:                 $visible = 1;
 7729:             }
 7730:         } else {
 7731:             $visible = 1;
 7732:         }
 7733:     } else {
 7734:         if (ref($cathash) eq 'HASH') {
 7735:             if ($cathash->{'instcode::0'} ne '') {
 7736:                 push(@vismsgs,'dc_instcode');
 7737:             }
 7738:         } else {
 7739:             push(@vismsgs,'dc_instcode');
 7740:         }
 7741:     }
 7742:     if ($currsettings{'categories'} ne '') {
 7743:         my $cathash;
 7744:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 7745:             $cathash = $domconf->{'coursecategories'}{'cats'};
 7746:             if (ref($cathash) eq 'HASH') {
 7747:                 if (keys(%{$cathash}) == 0) {
 7748:                     push(@vismsgs,'dc_catalog');
 7749:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 7750:                     push(@vismsgs,'dc_categories');
 7751:                 } else {
 7752:                     my @currcategories = split('&',$currsettings{'categories'});
 7753:                     my $matched = 0;
 7754:                     foreach my $cat (@currcategories) {
 7755:                         if ($cathash->{$cat} ne '') {
 7756:                             $visible = 1;
 7757:                             $matched = 1;
 7758:                             last;
 7759:                         }
 7760:                     }
 7761:                     if (!$matched) {
 7762:                         if ($settable{'categorize'}) { 
 7763:                             push(@vismsgs,'chgcat');
 7764:                         } else {
 7765:                             push(@vismsgs,'dc_chgcat');
 7766:                         }
 7767:                     }
 7768:                 }
 7769:             }
 7770:         }
 7771:     } else {
 7772:         if (ref($cathash) eq 'HASH') {
 7773:             if ((keys(%{$cathash}) > 1) || 
 7774:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 7775:                 if ($settable{'categorize'}) {
 7776:                     push(@vismsgs,'addcat');
 7777:                 } else {
 7778:                     push(@vismsgs,'dc_addcat');
 7779:                 }
 7780:             }
 7781:         }
 7782:     }
 7783:     if ($currsettings{'hidefromcat'} eq 'yes') {
 7784:         $visible = 0;
 7785:         if ($settable{'togglecats'}) {
 7786:             unshift(@vismsgs,'unhide');
 7787:         } else {
 7788:             unshift(@vismsgs,'dc_unhide')
 7789:         }
 7790:     }
 7791:     return ($visible,$cansetvis,\@vismsgs);
 7792: }
 7793: 
 7794: sub cat_visibility {
 7795:     my ($cdom) = @_;
 7796:     my %visactions = &Apache::lonlocal::texthash(
 7797:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 7798:                    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.',
 7799:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 7800:                    none => 'Display of a course catalog is disabled for this domain.',
 7801:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 7802:                    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.',
 7803:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 7804:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 7805:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 7806:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 7807:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 7808:                    dc_addinst => 'Ask a domain coordinator to enable catalog display of "Official courses (with institutional codes)".',
 7809:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 7810:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 7811:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 7812:                    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',
 7813:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 7814:     );
 7815:     if ($env{'request.role'} eq "dc./$cdom/") {
 7816:         $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;');
 7817:         $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;');
 7818:         $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;');
 7819:         $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;');
 7820:         $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;');
 7821:         $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;');
 7822:         $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;');
 7823:         $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;');
 7824:         $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;');
 7825:     }
 7826:     $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>"');
 7827:     $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>"');
 7828:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 7829:     return \%visactions;
 7830: }
 7831: 
 7832: sub new_selfenroll_dom_row {
 7833:     my ($newdom,$num) = @_;
 7834:     my $domdesc = &Apache::lonnet::domain($newdom);
 7835:     my $output;
 7836:     if ($domdesc ne '') {
 7837:         $output .= &Apache::loncommon::start_data_table_row()
 7838:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 7839:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 7840:                    .'" value="'.$newdom.'" /></span><br />'
 7841:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 7842:                    .'name="selfenroll_activate" value="'.$num.'" '
 7843:                    .'onchange="javascript:update_types('
 7844:                    ."'selfenroll_activate','$num'".');" />'
 7845:                    .&mt('Activate').'</label></span></td>';
 7846:         my @currinsttypes;
 7847:         $output .= '<td>'.&mt('User types:').'<br />'
 7848:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 7849:                    .&Apache::loncommon::end_data_table_row();
 7850:     }
 7851:     return $output;
 7852: }
 7853: 
 7854: sub selfenroll_inst_types {
 7855:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 7856:     my $output;
 7857:     my $numinrow = 4;
 7858:     my $count = 0;
 7859:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 7860:     my $othervalue = 'any';
 7861:     my $disabled;
 7862:     if ($readonly) {
 7863:         $disabled = ' disabled="disabled"';
 7864:     }
 7865:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7866:         if (keys(%{$usertypes}) > 0) {
 7867:             $othervalue = 'other';
 7868:         }
 7869:         $output .= '<table><tr>';
 7870:         foreach my $type (@{$types}) {
 7871:             if (($count > 0) && ($count%$numinrow == 0)) {
 7872:                 $output .= '</tr><tr>';
 7873:             }
 7874:             if (defined($usertypes->{$type})) {
 7875:                 my $esc_type = &escape($type);
 7876:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 7877:                            $esc_type.'" ';
 7878:                 if (ref($currinsttypes) eq 'ARRAY') {
 7879:                     if (@{$currinsttypes} > 0) {
 7880:                         if (grep(/^any$/,@{$currinsttypes})) {
 7881:                             $output .= 'checked="checked"';
 7882:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 7883:                             $output .= 'checked="checked"';
 7884:                         }
 7885:                     } else {
 7886:                         $output .= 'checked="checked"';
 7887:                     }
 7888:                 }
 7889:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 7890:             }
 7891:             $count ++;
 7892:         }
 7893:         if (($count > 0) && ($count%$numinrow == 0)) {
 7894:             $output .= '</tr><tr>';
 7895:         }
 7896:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 7897:         if (ref($currinsttypes) eq 'ARRAY') {
 7898:             if (@{$currinsttypes} > 0) {
 7899:                 if (grep(/^any$/,@{$currinsttypes})) { 
 7900:                     $output .= ' checked="checked"';
 7901:                 } elsif ($othervalue eq 'other') {
 7902:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 7903:                         $output .= ' checked="checked"';
 7904:                     }
 7905:                 }
 7906:             } else {
 7907:                 $output .= ' checked="checked"';
 7908:             }
 7909:         } else {
 7910:             $output .= ' checked="checked"';
 7911:         }
 7912:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 7913:     }
 7914:     return $output;
 7915: }
 7916: 
 7917: sub selfenroll_date_forms {
 7918:     my ($startform,$endform) = @_;
 7919:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 7920:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 7921:                                                     'LC_oddrow_value')."\n".
 7922:                   $startform."\n".
 7923:                   &Apache::lonhtmlcommon::row_closure(1).
 7924:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 7925:                                                    'LC_oddrow_value')."\n".
 7926:                   $endform."\n".
 7927:                   &Apache::lonhtmlcommon::row_closure(1).
 7928:                   &Apache::lonhtmlcommon::end_pick_box();
 7929:     return $output;
 7930: }
 7931: 
 7932: sub print_userchangelogs_display {
 7933:     my ($r,$context,$permission,$brcrum) = @_;
 7934:     my $formname = 'rolelog';
 7935:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 7936:     if ($context eq 'domain') {
 7937:         $domain = $env{'request.role.domain'};
 7938:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 7939:     } else {
 7940:         if ($context eq 'course') { 
 7941:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7942:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 7943:             $crstype = &Apache::loncommon::course_type();
 7944:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 7945:             my %saveable_parameters = ('show' => 'scalar',);
 7946:             &Apache::loncommon::store_course_settings('roles_log',
 7947:                                                       \%saveable_parameters);
 7948:             &Apache::loncommon::restore_course_settings('roles_log',
 7949:                                                         \%saveable_parameters);
 7950:         } elsif ($context eq 'author') {
 7951:             $domain = $env{'user.domain'};
 7952:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 7953:                 $username = $env{'user.name'};
 7954:             } elsif ($env{'request.role'} =~ m{^ca\./($match_domain)/($match_username)$}) {
 7955:                 ($domain,$username) = ($1,$2);
 7956:             } else {
 7957:                 undef($domain);
 7958:             }
 7959:         }
 7960:         if ($domain ne '' && $username ne '') { 
 7961:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 7962:         }
 7963:     }
 7964:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 7965: 
 7966:     my $helpitem;
 7967:     if ($context eq 'course') {
 7968:         $helpitem = 'Course_User_Logs';
 7969:     } elsif ($context eq 'domain') {
 7970:         $helpitem = 'Domain_Role_Logs';
 7971:     } elsif ($context eq 'author') {
 7972:         $helpitem = 'Author_User_Logs';
 7973:     }
 7974:     push (@{$brcrum},
 7975:              {href => '/adm/createuser?action=changelogs',
 7976:               text => 'User Management Logs',
 7977:               help => $helpitem});
 7978:     my $bread_crumbs_component = 'User Changes';
 7979:     my $args = { bread_crumbs           => $brcrum,
 7980:                  bread_crumbs_component => $bread_crumbs_component};
 7981: 
 7982:     # Create navigation javascript
 7983:     my $jsnav = &userlogdisplay_js($formname);
 7984: 
 7985:     my $jscript = (<<ENDSCRIPT);
 7986: <script type="text/javascript">
 7987: // <![CDATA[
 7988: $jsnav
 7989: // ]]>
 7990: </script>
 7991: ENDSCRIPT
 7992: 
 7993:     # print page header
 7994:     $r->print(&header($jscript,$args));
 7995: 
 7996:     # set defaults
 7997:     my $now = time();
 7998:     my $defstart = $now - (7*24*3600); #7 days ago 
 7999:     my %defaults = (
 8000:                      page               => '1',
 8001:                      show               => '10',
 8002:                      role               => 'any',
 8003:                      chgcontext         => 'any',
 8004:                      rolelog_start_date => $defstart,
 8005:                      rolelog_end_date   => $now,
 8006:                      approvals          => 'any',
 8007:                    );
 8008:     my $more_records = 0;
 8009: 
 8010:     # set current
 8011:     my %curr;
 8012:     foreach my $item ('show','page','role','chgcontext','approvals') {
 8013:         $curr{$item} = $env{'form.'.$item};
 8014:     }
 8015:     my ($startdate,$enddate) = 
 8016:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 8017:     $curr{'rolelog_start_date'} = $startdate;
 8018:     $curr{'rolelog_end_date'} = $enddate;
 8019:     foreach my $key (keys(%defaults)) {
 8020:         if ($curr{$key} eq '') {
 8021:             $curr{$key} = $defaults{$key};
 8022:         }
 8023:     }
 8024:     my (%whodunit,%changed,$version);
 8025:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 8026:     my ($minshown,$maxshown);
 8027:     $minshown = 1;
 8028:     my $count = 0;
 8029:     if ($curr{'show'} =~ /\D/) {
 8030:         $curr{'page'} = 1;
 8031:     } else {
 8032:         $maxshown = $curr{'page'} * $curr{'show'};
 8033:         if ($curr{'page'} > 1) {
 8034:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8035:         }
 8036:     }
 8037: 
 8038:     # Form Header
 8039:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8040:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 8041:                                    $version,$crstype));
 8042: 
 8043:     my $showntableheader = 0;
 8044: 
 8045:     # Table Header
 8046:     my $tableheader = 
 8047:         &Apache::loncommon::start_data_table_header_row()
 8048:        .'<th>&nbsp;</th>'
 8049:        .'<th>'.&mt('When').'</th>'
 8050:        .'<th>'.&mt('Who made the change').'</th>'
 8051:        .'<th>'.&mt('Changed User').'</th>'
 8052:        .'<th>'.&mt('Role').'</th>';
 8053: 
 8054:     if ($context eq 'course') {
 8055:         $tableheader .= '<th>'.&mt('Section').'</th>';
 8056:     }
 8057:     $tableheader .=
 8058:         '<th>'.&mt('Context').'</th>'
 8059:        .'<th>'.&mt('Start').'</th>'
 8060:        .'<th>'.&mt('End').'</th>'
 8061:        .&Apache::loncommon::end_data_table_header_row();
 8062: 
 8063:     # Display user change log data
 8064:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 8065:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 8066:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 8067:         if ($curr{'show'} !~ /\D/) {
 8068:             if ($count >= $curr{'page'} * $curr{'show'}) {
 8069:                 $more_records = 1;
 8070:                 last;
 8071:             }
 8072:         }
 8073:         if ($curr{'role'} ne 'any') {
 8074:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 8075:         }
 8076:         if ($curr{'chgcontext'} ne 'any') {
 8077:             if ($curr{'chgcontext'} eq 'selfenroll') {
 8078:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 8079:             } else {
 8080:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 8081:             }
 8082:         }
 8083:         if (($context eq 'course') && ($viewablesec ne '')) {
 8084:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 8085:         }
 8086:         if ($curr{'approvals'} eq 'none') {
 8087:             next if ($roleslog{$id}{'logentry'}{'approval'});
 8088:         } elsif ($curr{'approvals'} ne 'any') { 
 8089:             next if ($roleslog{$id}{'logentry'}{'approval'} ne $curr{'approvals'});
 8090:         }
 8091:         $count ++;
 8092:         next if ($count < $minshown);
 8093:         unless ($showntableheader) {
 8094:             $r->print(&Apache::loncommon::start_data_table()
 8095:                      .$tableheader);
 8096:             $r->rflush();
 8097:             $showntableheader = 1;
 8098:         }
 8099:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 8100:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 8101:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 8102:         }
 8103:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 8104:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 8105:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 8106:         }
 8107:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 8108:         if ($sec eq '') {
 8109:             $sec = &mt('None');
 8110:         }
 8111:         my ($rolestart,$roleend);
 8112:         if ($roleslog{$id}{'delflag'}) {
 8113:             $rolestart = &mt('deleted');
 8114:             $roleend = &mt('deleted');
 8115:         } else {
 8116:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 8117:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 8118:             if ($rolestart eq '' || $rolestart == 0) {
 8119:                 $rolestart = &mt('No start date'); 
 8120:             } else {
 8121:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 8122:             }
 8123:             if ($roleend eq '' || $roleend == 0) { 
 8124:                 $roleend = &mt('No end date');
 8125:             } else {
 8126:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 8127:             }
 8128:         }
 8129:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 8130:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 8131:             $chgcontext = 'selfenroll';
 8132:         }
 8133:         my %lt = &rolechg_contexts($context,$crstype);
 8134:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 8135:             $chgcontext = $lt{$chgcontext};
 8136:         }
 8137:         my ($showreqby,%reqby);
 8138:         if (($roleslog{$id}{'logentry'}{'approval'}) &&
 8139:             ($roleslog{$id}{'logentry'}{'requester'})) {
 8140:             if ($reqby{$roleslog{$id}{'logentry'}{'requester'}} eq '') {
 8141:                 my ($requname,$requdom) = split(/:/,$roleslog{$id}{'logentry'}{'requester'});
 8142:                 $reqby{$roleslog{$id}{'logentry'}{'requester'}} =
 8143:                     &Apache::loncommon::plainname($requname,$requdom);
 8144:             }
 8145:             $showreqby = &mt('Requester').': <span class="LC_nobreak">'.$reqby{$roleslog{$id}{'logentry'}{'requester'}}.'</span><br />';
 8146:             if ($roleslog{$id}{'logentry'}{'approval'} eq 'domain') {
 8147:                 $showreqby .= &mt('Adjudicator').': <span class="LC_nobreak">'.
 8148:                               $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.
 8149:                               '</span>';
 8150:             } else {
 8151:                 $showreqby .= '<span class="LC_nobreak">'.&mt('User approved').'</span>';
 8152:             }
 8153:         } else {
 8154:             $showreqby = $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}};
 8155:         }
 8156:         $r->print(
 8157:             &Apache::loncommon::start_data_table_row()
 8158:            .'<td>'.$count.'</td>'
 8159:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 8160:            .'<td>'.$showreqby.'</td>'
 8161:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 8162:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 8163:         if ($context eq 'course') { 
 8164:             $r->print('<td>'.$sec.'</td>');
 8165:         }
 8166:         $r->print(
 8167:             '<td>'.$chgcontext.'</td>'
 8168:            .'<td>'.$rolestart.'</td>'
 8169:            .'<td>'.$roleend.'</td>'
 8170:            .&Apache::loncommon::end_data_table_row()."\n");
 8171:     }
 8172: 
 8173:     if ($showntableheader) { # Table footer, if content displayed above
 8174:         $r->print(&Apache::loncommon::end_data_table().
 8175:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8176:     } else { # No content displayed above
 8177:         $r->print('<p class="LC_info">'
 8178:                  .&mt('There are no records to display.')
 8179:                  .'</p>'
 8180:         );
 8181:     }
 8182: 
 8183:     # Form Footer
 8184:     $r->print( 
 8185:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8186:        .'<input type="hidden" name="action" value="changelogs" />'
 8187:        .'</form>');
 8188:     return;
 8189: }
 8190: 
 8191: sub print_useraccesslogs_display {
 8192:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 8193:     my $formname = 'accesslog';
 8194:     my $form = 'document.accesslog';
 8195: 
 8196: # set breadcrumbs
 8197:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 8198:     my $prevphasestr;
 8199:     if ($env{'form.popup'}) {
 8200:         $brcrum = [];
 8201:     } else {
 8202:         push (@{$brcrum},
 8203:             {href => "javascript:backPage($form)",
 8204:              text => $breadcrumb_text{'search'}});
 8205:         my @prevphases;
 8206:         if ($env{'form.prevphases'}) {
 8207:             @prevphases = split(/,/,$env{'form.prevphases'});
 8208:             $prevphasestr = $env{'form.prevphases'};
 8209:         }
 8210:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 8211:             push(@{$brcrum},
 8212:                   {href => "javascript:backPage($form,'get_user_info','select')",
 8213:                    text => $breadcrumb_text{'userpicked'}});
 8214:             if ($env{'form.phase'} eq 'userpicked') {
 8215:                 $prevphasestr = 'userpicked';
 8216:             }
 8217:         }
 8218:     }
 8219:     push(@{$brcrum},
 8220:              {href => '/adm/createuser?action=accesslogs',
 8221:               text => 'User access logs',
 8222:               help => 'Domain_User_Access_Logs'});
 8223:     my $bread_crumbs_component = 'User Access Logs';
 8224:     my $args = { bread_crumbs           => $brcrum,
 8225:                  bread_crumbs_component => 'User Management'};
 8226:     if ($env{'form.popup'}) {
 8227:         $args->{'no_nav_bar'} = 1;
 8228:         $args->{'bread_crumbs_nomenu'} = 1;
 8229:     }
 8230: 
 8231: # set javascript
 8232:     my ($jsback,$elements) = &crumb_utilities();
 8233:     my $jsnav = &userlogdisplay_js($formname);
 8234: 
 8235:     my $jscript = (<<ENDSCRIPT);
 8236: <script type="text/javascript">
 8237: // <![CDATA[
 8238: 
 8239: $jsback
 8240: $jsnav
 8241: 
 8242: // ]]>
 8243: </script>
 8244: 
 8245: ENDSCRIPT
 8246: 
 8247: # print page header
 8248:     $r->print(&header($jscript,$args));
 8249: 
 8250: # early out unless log data can be displayed.
 8251:     unless ($permission->{'activity'}) {
 8252:         $r->print('<p class="LC_warning">'
 8253:                  .&mt('You do not have rights to display user access logs.')
 8254:                  .'</p>');
 8255:         if ($env{'form.popup'}) {
 8256:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8257:         } else {
 8258:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8259:         }
 8260:         return;
 8261:     }
 8262: 
 8263:     unless ($udom eq $env{'request.role.domain'}) {
 8264:         $r->print('<p class="LC_warning">'
 8265:                  .&mt("User's domain must match role's domain")
 8266:                  .'</p>'
 8267:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8268:         return;
 8269:     }
 8270: 
 8271:     if (($uname eq '') || ($udom eq '')) {
 8272:         $r->print('<p class="LC_warning">'
 8273:                  .&mt('Invalid username or domain')
 8274:                  .'</p>'
 8275:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8276:         return;
 8277:     }
 8278: 
 8279:     if (&Apache::lonnet::privileged($uname,$udom,
 8280:                                     [$env{'request.role.domain'}],['dc','su'])) {
 8281:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 8282:                                             [$env{'request.role.domain'}],['dc','su'])) {
 8283:             $r->print('<p class="LC_warning">'
 8284:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 8285:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 8286:                                                          $uname,$udom))
 8287:                  .'</p>');
 8288:             if ($env{'form.popup'}) {
 8289:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 8290:             } else {
 8291:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 8292:             }
 8293:             return;
 8294:         }
 8295:     }
 8296: 
 8297: # set defaults
 8298:     my $now = time();
 8299:     my $defstart = $now - (7*24*3600);
 8300:     my %defaults = (
 8301:                      page                 => '1',
 8302:                      show                 => '10',
 8303:                      activity             => 'any',
 8304:                      accesslog_start_date => $defstart,
 8305:                      accesslog_end_date   => $now,
 8306:                    );
 8307:     my $more_records = 0;
 8308: 
 8309: # set current
 8310:     my %curr;
 8311:     foreach my $item ('show','page','activity') {
 8312:         $curr{$item} = $env{'form.'.$item};
 8313:     }
 8314:     my ($startdate,$enddate) =
 8315:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 8316:     $curr{'accesslog_start_date'} = $startdate;
 8317:     $curr{'accesslog_end_date'} = $enddate;
 8318:     foreach my $key (keys(%defaults)) {
 8319:         if ($curr{$key} eq '') {
 8320:             $curr{$key} = $defaults{$key};
 8321:         }
 8322:     }
 8323:     my ($minshown,$maxshown);
 8324:     $minshown = 1;
 8325:     my $count = 0;
 8326:     if ($curr{'show'} =~ /\D/) {
 8327:         $curr{'page'} = 1;
 8328:     } else {
 8329:         $maxshown = $curr{'page'} * $curr{'show'};
 8330:         if ($curr{'page'} > 1) {
 8331:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 8332:         }
 8333:     }
 8334: 
 8335: # form header
 8336:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 8337:               &activity_display_filter($formname,\%curr));
 8338: 
 8339:     my $showntableheader = 0;
 8340:     my ($nav_script,$nav_links);
 8341: 
 8342: # table header
 8343:     my $heading = '<h3>'.
 8344:         &mt('User access logs for: [_1]',
 8345:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 8346:     my $tableheader = $heading
 8347:        .&Apache::loncommon::start_data_table_header_row()
 8348:        .'<th>&nbsp;</th>'
 8349:        .'<th>'.&mt('When').'</th>'
 8350:        .'<th>'.&mt('HostID').'</th>'
 8351:        .'<th>'.&mt('Event').'</th>'
 8352:        .'<th>'.&mt('Other data').'</th>'
 8353:        .&Apache::loncommon::end_data_table_header_row();
 8354: 
 8355:     my %filters=(
 8356:         start  => $curr{'accesslog_start_date'},
 8357:         end    => $curr{'accesslog_end_date'},
 8358:         action => $curr{'activity'},
 8359:     );
 8360: 
 8361:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 8362:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8363:         my (%courses,%missing);
 8364:         my @results = split(/\&/,$reply);
 8365:         foreach my $item (reverse(@results)) {
 8366:             my ($timestamp,$host,$event) = split(/:/,$item);
 8367:             next unless ($event =~ /^(Log|Role)/);
 8368:             if ($curr{'show'} !~ /\D/) {
 8369:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 8370:                     $more_records = 1;
 8371:                     last;
 8372:                 }
 8373:             }
 8374:             $count ++;
 8375:             next if ($count < $minshown);
 8376:             unless ($showntableheader) {
 8377:                 $r->print($nav_script
 8378:                          .&Apache::loncommon::start_data_table()
 8379:                          .$tableheader);
 8380:                 $r->rflush();
 8381:                 $showntableheader = 1;
 8382:             }
 8383:             my ($shown,$extra);
 8384:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 8385:             if ($event eq 'Role') {
 8386:                 my ($rolecode,$extent) = split(/\./,$data,2);
 8387:                 next if ($extent eq '');
 8388:                 my ($crstype,$desc,$info);
 8389:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 8390:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 8391:                     my $cid = $cdom.'_'.$cnum;
 8392:                     if (exists($courses{$cid})) {
 8393:                         $crstype = $courses{$cid}{'type'};
 8394:                         $desc = $courses{$cid}{'description'};
 8395:                     } elsif ($missing{$cid}) {
 8396:                         $crstype = 'Course';
 8397:                         $desc = 'Course/Community';
 8398:                     } else {
 8399:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8400:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 8401:                             $courses{$cid} = $crsinfo{$cid};
 8402:                             $crstype = $crsinfo{$cid}{'type'};
 8403:                             $desc = $crsinfo{$cid}{'description'};
 8404:                         } else {
 8405:                             $missing{$cid} = 1;
 8406:                         }
 8407:                     }
 8408:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 8409:                     if ($sec ne '') {
 8410:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 8411:                     }
 8412:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 8413:                     my ($dom,$name) = ($1,$2);
 8414:                     if ($rolecode eq 'au') {
 8415:                         $extra = '';
 8416:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 8417:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 8418:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 8419:                         $extra = &mt('Domain: [_1]',$dom);
 8420:                     }
 8421:                 }
 8422:                 my $rolename;
 8423:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 8424:                     my $role = $3;
 8425:                     my $owner = "($2:$1)";
 8426:                     if ($2 eq $1.'-domainconfig') {
 8427:                         $owner = '(ad hoc)';
 8428:                     }
 8429:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 8430:                 } else {
 8431:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 8432:                 }
 8433:                 $shown = &mt('Role selection: [_1]',$rolename);
 8434:             } else {
 8435:                 $shown = &mt($event);
 8436:                 if ($data =~ /^webdav/) {
 8437:                     my ($path,$clientip) = split(/\s+/,$data,2);
 8438:                     $path =~ s/^webdav//;
 8439:                     if ($clientip ne '') {
 8440:                         $extra = &mt('Client IP address: [_1]',$clientip);
 8441:                     }
 8442:                     if ($path ne '') {
 8443:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 8444:                     }
 8445:                 } elsif ($data ne '') {
 8446:                     $extra = &mt('Client IP address: [_1]',$data);
 8447:                 }
 8448:             }
 8449:             $r->print(
 8450:             &Apache::loncommon::start_data_table_row()
 8451:            .'<td>'.$count.'</td>'
 8452:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 8453:            .'<td>'.$host.'</td>'
 8454:            .'<td>'.$shown.'</td>'
 8455:            .'<td>'.$extra.'</td>'
 8456:            .&Apache::loncommon::end_data_table_row()."\n");
 8457:         }
 8458:     }
 8459: 
 8460:     if ($showntableheader) { # Table footer, if content displayed above
 8461:         $r->print(&Apache::loncommon::end_data_table().
 8462:                   &userlogdisplay_navlinks(\%curr,$more_records));
 8463:     } else { # No content displayed above
 8464:         $r->print($heading.'<p class="LC_info">'
 8465:                  .&mt('There are no records to display.')
 8466:                  .'</p>');
 8467:     }
 8468: 
 8469:     if ($env{'form.popup'} == 1) {
 8470:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 8471:     }
 8472: 
 8473:     # Form Footer
 8474:     $r->print(
 8475:         '<input type="hidden" name="currstate" value="" />'
 8476:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 8477:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 8478:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 8479:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 8480:        .'<input type="hidden" name="phase" value="activity" />'
 8481:        .'<input type="hidden" name="action" value="accesslogs" />'
 8482:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 8483:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 8484:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 8485:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 8486:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 8487:        .'</form>');
 8488:     return;
 8489: }
 8490: 
 8491: sub earlyout_accesslog_form {
 8492:     my ($formname,$prevphasestr,$udom) = @_;
 8493:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 8494:    return <<"END";
 8495: <form action="/adm/createuser" method="post" name="$formname">
 8496: <input type="hidden" name="currstate" value="" />
 8497: <input type="hidden" name="prevphases" value="$prevphasestr" />
 8498: <input type="hidden" name="phase" value="activity" />
 8499: <input type="hidden" name="action" value="accesslogs" />
 8500: <input type="hidden" name="srchdomain" value="$udom" />
 8501: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 8502: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 8503: <input type="hidden" name="srchterm" value="$srchterm" />
 8504: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 8505: </form>
 8506: END
 8507: }
 8508: 
 8509: sub activity_display_filter {
 8510:     my ($formname,$curr) = @_;
 8511:     my $nolink = 1;
 8512:     my $output = '<table><tr><td valign="top">'.
 8513:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 8514:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8515:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8516:                  '</td><td>&nbsp;&nbsp;</td>';
 8517:     my $startform =
 8518:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 8519:                                             $curr->{'accesslog_start_date'},undef,
 8520:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8521:     my $endform =
 8522:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 8523:                                             $curr->{'accesslog_end_date'},undef,
 8524:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8525:     my %lt = &Apache::lonlocal::texthash (
 8526:                                           activity => 'Activity',
 8527:                                           Role     => 'Role selection',
 8528:                                           log      => 'Log-in or Logout',
 8529:     );
 8530:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 8531:                '<table><tr><td>'.&mt('After:').
 8532:                '</td><td>'.$startform.'</td></tr>'.
 8533:                '<tr><td>'.&mt('Before:').'</td>'.
 8534:                '<td>'.$endform.'</td></tr></table>'.
 8535:                '</td>'.
 8536:                '<td>&nbsp;&nbsp;</td>'.
 8537:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 8538:                '<select name="activity"><option value="any"';
 8539:     if ($curr->{'activity'} eq 'any') {
 8540:         $output .= ' selected="selected"';
 8541:     }
 8542:     $output .= '>'.&mt('Any').'</option>'."\n";
 8543:     foreach my $activity ('Role','log') {
 8544:         my $selstr = '';
 8545:         if ($activity eq $curr->{'activity'}) {
 8546:             $selstr = ' selected="selected"';
 8547:         }
 8548:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 8549:     }
 8550:     $output .= '</select></td>'.
 8551:                '</tr></table>';
 8552:     # Update Display button
 8553:     $output .= '<p>'
 8554:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8555:               .'</p><hr />';
 8556:     return $output;
 8557: }
 8558: 
 8559: sub userlogdisplay_js {
 8560:     my ($formname) = @_;
 8561:     return <<"ENDSCRIPT";
 8562: 
 8563: function chgPage(caller) {
 8564:     if (caller == 'previous') {
 8565:         document.$formname.page.value --;
 8566:     }
 8567:     if (caller == 'next') {
 8568:         document.$formname.page.value ++;
 8569:     }
 8570:     document.$formname.submit();
 8571:     return;
 8572: }
 8573: ENDSCRIPT
 8574: }
 8575: 
 8576: sub userlogdisplay_navlinks {
 8577:     my ($curr,$more_records) = @_;
 8578:     return unless(ref($curr) eq 'HASH');
 8579:     # Navigation Buttons
 8580:     my $nav_links = '<p>';
 8581:     if (($curr->{'page'} > 1) || ($more_records)) {
 8582:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 8583:             $nav_links .= '<input type="button"'
 8584:                          .' onclick="javascript:chgPage('."'previous'".');"'
 8585:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 8586:                          .'" /> ';
 8587:         }
 8588:         if ($more_records) {
 8589:             $nav_links .= '<input type="button"'
 8590:                          .' onclick="javascript:chgPage('."'next'".');"'
 8591:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 8592:                          .'" />';
 8593:         }
 8594:     }
 8595:     $nav_links .= '</p>';
 8596:     return $nav_links;
 8597: }
 8598: 
 8599: sub role_display_filter {
 8600:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 8601:     my $nolink = 1;
 8602:     my $output = '<table><tr><td valign="top">'.
 8603:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 8604:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},'',undef,
 8605:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 8606:                  '</td><td>&nbsp;&nbsp;</td>';
 8607:     my $startform =
 8608:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 8609:                                             $curr->{'rolelog_start_date'},undef,
 8610:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8611:     my $endform =
 8612:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 8613:                                             $curr->{'rolelog_end_date'},undef,
 8614:                                             undef,undef,undef,undef,undef,undef,$nolink);
 8615:     my %lt = &rolechg_contexts($context,$crstype);
 8616:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 8617:                '<table><tr><td>'.&mt('After:').
 8618:                '</td><td>'.$startform.'</td></tr>'.
 8619:                '<tr><td>'.&mt('Before:').'</td>'.
 8620:                '<td>'.$endform.'</td></tr></table>'.
 8621:                '</td>'.
 8622:                '<td>&nbsp;&nbsp;</td>'.
 8623:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 8624:                '<select name="role"><option value="any"';
 8625:     if ($curr->{'role'} eq 'any') {
 8626:         $output .= ' selected="selected"';
 8627:     }
 8628:     $output .= '>'.&mt('Any').'</option>'."\n";
 8629:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 8630:     foreach my $role (@roles) {
 8631:         my $plrole;
 8632:         if ($role eq 'cr') {
 8633:             $plrole = &mt('Custom Role');
 8634:         } else {
 8635:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 8636:         }
 8637:         my $selstr = '';
 8638:         if ($role eq $curr->{'role'}) {
 8639:             $selstr = ' selected="selected"';
 8640:         }
 8641:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 8642:     }
 8643:     $output .= '</select></td>'.
 8644:                '<td>&nbsp;&nbsp;</td>'.
 8645:                '<td valign="top"><b>'.
 8646:                &mt('Context:').'</b><br /><select name="chgcontext">';
 8647:     my @posscontexts;
 8648:     if ($context eq 'course') {
 8649:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype','ltienroll');
 8650:     } elsif ($context eq 'domain') {
 8651:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 8652:     } else {
 8653:         @posscontexts = ('any','author','coauthor','domain');
 8654:     }
 8655:     foreach my $chgtype (@posscontexts) {
 8656:         my $selstr = '';
 8657:         if ($curr->{'chgcontext'} eq $chgtype) {
 8658:             $selstr = ' selected="selected"';
 8659:         }
 8660:         if ($context eq 'course') {
 8661:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 8662:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 8663:             }
 8664:         }
 8665:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 8666:     }
 8667:     my @possapprovals = ('any','none','domain','user');
 8668:     my %apptxt = &approval_types();
 8669:     $output .= '</select></td>'.
 8670:                '<td>&nbsp;&nbsp;</td>'.
 8671:                '<td valign="top"><b>'.
 8672:                &mt('Approvals:').'</b><br /><select name="approvals">';
 8673:     foreach my $approval (@possapprovals) {
 8674:         my $selstr = '';
 8675:         if ($curr->{'approvals'} eq $approval) {
 8676:             $selstr = ' selected="selected"';
 8677:         }    
 8678:         $output .= '<option value="'.$approval.'"'.$selstr.'>'.$apptxt{$approval}.'</option>';
 8679:     }
 8680:     $output .= '</select></td></tr></table>';
 8681: 
 8682:     # Update Display button
 8683:     $output .= '<p>'
 8684:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 8685:               .'</p>';
 8686: 
 8687:     # Server version info
 8688:     my $needsrev = '2.11.0';
 8689:     if ($context eq 'course') {
 8690:         $needsrev = '2.7.0';
 8691:     }
 8692:     
 8693:     $output .= '<p class="LC_info">'
 8694:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 8695:                   ,$needsrev);
 8696:     if ($version) {
 8697:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 8698:     }
 8699:     $output .= '</p><hr />';
 8700:     return $output;
 8701: }
 8702: 
 8703: sub rolechg_contexts {
 8704:     my ($context,$crstype) = @_;
 8705:     my %lt;
 8706:     if ($context eq 'course') {
 8707:         %lt = &Apache::lonlocal::texthash (
 8708:                                              any          => 'Any',
 8709:                                              automated    => 'Automated Enrollment',
 8710:                                              chgtype      => 'Enrollment Type/Lock Change',
 8711:                                              updatenow    => 'Roster Update',
 8712:                                              createcourse => 'Course Creation',
 8713:                                              course       => 'User Management in course',
 8714:                                              domain       => 'User Management in domain',
 8715:                                              selfenroll   => 'Self-enrolled',
 8716:                                              requestcourses => 'Course Request',
 8717:                                              ltienroll    => 'Enrollment via LTI',
 8718:                                          );
 8719:         if ($crstype eq 'Community') {
 8720:             $lt{'createcourse'} = &mt('Community Creation');
 8721:             $lt{'course'} = &mt('User Management in community');
 8722:             $lt{'requestcourses'} = &mt('Community Request');
 8723:         }
 8724:     } elsif ($context eq 'domain') {
 8725:         %lt = &Apache::lonlocal::texthash (
 8726:                                              any           => 'Any',
 8727:                                              domain        => 'User Management in domain',
 8728:                                              requestauthor => 'Authoring Request',
 8729:                                              server        => 'Command line script (DC role)',
 8730:                                              domconfig     => 'Self-enrolled',
 8731:                                          );
 8732:     } else {
 8733:         %lt = &Apache::lonlocal::texthash (
 8734:                                              any    => 'Any',
 8735:                                              domain => 'User Management in domain',
 8736:                                              author => 'User Management by author',
 8737:                                              coauthor => 'User Management by coauthor',
 8738:                                          );
 8739:     } 
 8740:     return %lt;
 8741: }
 8742: 
 8743: sub approval_types {
 8744:     return &Apache::lonlocal::texthash (
 8745:                                           any => 'Any',
 8746:                                           none => 'No approval needed',
 8747:                                           user => 'Role recipient approval',
 8748:                                           domain => 'Domain coordinator approval',
 8749:                                        );
 8750: }
 8751: 
 8752: sub print_helpdeskaccess_display {
 8753:     my ($r,$permission,$brcrum) = @_;
 8754:     my $formname = 'helpdeskaccess';
 8755:     my $helpitem = 'Course_Helpdesk_Access';
 8756:     push (@{$brcrum},
 8757:              {href => '/adm/createuser?action=helpdesk',
 8758:               text => 'Helpdesk Access',
 8759:               help => $helpitem});
 8760:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8761:     my $args = { bread_crumbs           => $brcrum,
 8762:                  bread_crumbs_component => $bread_crumbs_component};
 8763: 
 8764:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8765:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8766:     my $confname = $cdom.'-domainconfig';
 8767:     my $crstype = &Apache::loncommon::course_type();
 8768: 
 8769:     my @accesstypes = ('all','dh','da','none');
 8770:     my ($numstatustypes,@jsarray);
 8771:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8772:     if (ref($types) eq 'ARRAY') {
 8773:         if (@{$types} > 0) {
 8774:             $numstatustypes = scalar(@{$types});
 8775:             push(@accesstypes,'status');
 8776:             @jsarray = ('bystatus');
 8777:         }
 8778:     }
 8779:     my %customroles = &get_domain_customroles($cdom,$confname);
 8780:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8781:     if (keys(%domhelpdesk)) {
 8782:        push(@accesstypes,('inc','exc'));
 8783:        push(@jsarray,('notinc','notexc'));
 8784:     }
 8785:     push(@jsarray,'privs');
 8786:     my $hiddenstr = join("','",@jsarray);
 8787:     my $rolestr = join("','",sort(keys(%customroles)));
 8788: 
 8789:     my $jscript;
 8790:     my (%settings,%overridden);
 8791:     if (keys(%customroles)) {
 8792:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8793:                                 $types,\%customroles,\%settings,\%overridden);
 8794:         my %jsfull=();
 8795:         my %jslevels= (
 8796:                      course => {},
 8797:                      domain => {},
 8798:                      system => {},
 8799:                     );
 8800:         my %jslevelscurrent=(
 8801:                            course => {},
 8802:                            domain => {},
 8803:                            system => {},
 8804:                           );
 8805:         my (%privs,%jsprivs);
 8806:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 8807:         foreach my $priv (keys(%jsfull)) {
 8808:             if ($jslevels{'course'}{$priv}) {
 8809:                 $jsprivs{$priv} = 1;
 8810:             }
 8811:         }
 8812:         my (%elements,%stored);
 8813:         foreach my $role (keys(%customroles)) {
 8814:             $elements{$role.'_access'} = 'radio';
 8815:             $elements{$role.'_incrs'} = 'radio';
 8816:             if ($numstatustypes) {
 8817:                 $elements{$role.'_status'} = 'checkbox';
 8818:             }
 8819:             if (keys(%domhelpdesk) > 0) {
 8820:                 $elements{$role.'_staff_inc'} = 'checkbox';
 8821:                 $elements{$role.'_staff_exc'} = 'checkbox';
 8822:             }
 8823:             $elements{$role.'_override'} = 'checkbox';
 8824:             if (ref($settings{$role}) eq 'HASH') {
 8825:                 if ($settings{$role}{'access'} ne '') {
 8826:                     my $curraccess = $settings{$role}{'access'};
 8827:                     $stored{$role.'_access'} = $curraccess;
 8828:                     $stored{$role.'_incrs'} = 1;
 8829:                     if ($curraccess eq 'status') {
 8830:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 8831:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 8832:                         }
 8833:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8834:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 8835:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 8836:                         }
 8837:                     }
 8838:                 } else {
 8839:                     $stored{$role.'_incrs'} = 0;
 8840:                 }
 8841:                 $stored{$role.'_override'} = [];
 8842:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 8843:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 8844:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 8845:                             push(@{$stored{$role.'_override'}},$priv);
 8846:                         }
 8847:                     }
 8848:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 8849:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 8850:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 8851:                                 push(@{$stored{$role.'_override'}},$priv);
 8852:                             }
 8853:                         }
 8854:                     }
 8855:                 }
 8856:             } else {
 8857:                 $stored{$role.'_incrs'} = 0;
 8858:             }
 8859:         }
 8860:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 8861:     }
 8862: 
 8863:     my $js = <<"ENDJS";
 8864: <script type="text/javascript">
 8865: // <![CDATA[
 8866: $jscript;
 8867: 
 8868: function switchRoleTab(caller,role) {
 8869:     if (document.getElementById(role+'_maindiv')) {
 8870:         if (caller.id != 'LC_current_minitab') {
 8871:             if (document.getElementById('LC_current_minitab')) {
 8872:                 document.getElementById('LC_current_minitab').id=null;
 8873:             }
 8874:             var roledivs = Array('$rolestr');
 8875:             if (roledivs.length > 0) {
 8876:                 for (var i=0; i<roledivs.length; i++) {
 8877:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 8878:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 8879:                     }
 8880:                 }
 8881:             }
 8882:             caller.id = 'LC_current_minitab';
 8883:             document.getElementById(role+'_maindiv').style.display='block';
 8884:         }
 8885:     }
 8886:     return false;
 8887: }
 8888: 
 8889: function helpdeskAccess(role) {
 8890:     var curraccess = null;
 8891:     if (document.$formname.elements[role+'_access'].length) {
 8892:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 8893:             if (document.$formname.elements[role+'_access'][i].checked) {
 8894:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 8895:             }
 8896:         }
 8897:     }
 8898:     var shown = Array();
 8899:     var hidden = Array();
 8900:     if (curraccess == 'none') {
 8901:         hidden = Array ('$hiddenstr');
 8902:     } else {
 8903:         if (curraccess == 'status') {
 8904:             shown = Array ('bystatus','privs');
 8905:             hidden = Array ('notinc','notexc');
 8906:         } else {
 8907:             if (curraccess == 'exc') {
 8908:                 shown = Array ('notexc','privs');
 8909:                 hidden = Array ('notinc','bystatus');
 8910:             }
 8911:             if (curraccess == 'inc') {
 8912:                 shown = Array ('notinc','privs');
 8913:                 hidden = Array ('notexc','bystatus');
 8914:             }
 8915:             if (curraccess == 'all') {
 8916:                 shown = Array ('privs');
 8917:                 hidden = Array ('notinc','notexc','bystatus');
 8918:             }
 8919:         }
 8920:     }
 8921:     if (hidden.length > 0) {
 8922:         for (var i=0; i<hidden.length; i++) {
 8923:             if (document.getElementById(role+'_'+hidden[i])) {
 8924:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 8925:             }
 8926:         }
 8927:     }
 8928:     if (shown.length > 0) {
 8929:         for (var i=0; i<shown.length; i++) {
 8930:             if (document.getElementById(role+'_'+shown[i])) {
 8931:                 if (shown[i] == 'privs') {
 8932:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 8933:                 } else {
 8934:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 8935:                 }
 8936:             }
 8937:         }
 8938:     }
 8939:     return;
 8940: }
 8941: 
 8942: function toggleAccess(role) {
 8943:     if ((document.getElementById(role+'_setincrs')) &&
 8944:         (document.getElementById(role+'_setindom'))) {
 8945:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 8946:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 8947:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 8948:                     document.getElementById(role+'_setindom').style.display = 'none';
 8949:                     document.getElementById(role+'_setincrs').style.display = 'block';
 8950:                 } else {
 8951:                     document.getElementById(role+'_setincrs').style.display = 'none';
 8952:                     document.getElementById(role+'_setindom').style.display = 'block';
 8953:                 }
 8954:                 break;
 8955:             }
 8956:         }
 8957:     }
 8958:     return;
 8959: }
 8960: 
 8961: // ]]>
 8962: </script>
 8963: ENDJS
 8964: 
 8965:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 8966: 
 8967:     # print page header
 8968:     $r->print(&header($js,$args));
 8969:     # print form header
 8970:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 8971: 
 8972:     if (keys(%customroles)) {
 8973:         my %lt = &Apache::lonlocal::texthash(
 8974:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 8975:                     'rou'    => 'Role usage',
 8976:                     'whi'    => 'Which helpdesk personnel may use this role?',
 8977:                     'udd'    => 'Use domain default',
 8978:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 8979:                     'dh'     => 'All with domain helpdesk role',
 8980:                     'da'     => 'All with domain helpdesk assistant role',
 8981:                     'none'   => 'None',
 8982:                     'status' => 'Determined based on institutional status',
 8983:                     'inc'    => 'Include all, but exclude specific personnel',
 8984:                     'exc'    => 'Exclude all, but include specific personnel',
 8985:                     'hel'    => 'Helpdesk',
 8986:                     'rpr'    => 'Role privileges',
 8987:                  );
 8988:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 8989:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8990:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 8991:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8992:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8993:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8994:             }
 8995:         }
 8996:         my $count = 0;
 8997:         foreach my $role (sort(keys(%customroles))) {
 8998:             my ($order,$desc,$access_in_dom);
 8999:             if (ref($domcurrent{$role}) eq 'HASH') {
 9000:                 $order = $domcurrent{$role}{'order'};
 9001:                 $desc = $domcurrent{$role}{'desc'};
 9002:                 $access_in_dom = $domcurrent{$role}{'access'};
 9003:             }
 9004:             if ($order eq '') {
 9005:                 $order = $count;
 9006:             }
 9007:             $ordered{$order} = $role;
 9008:             if ($desc ne '') {
 9009:                 $description{$role} = $desc;
 9010:             } else {
 9011:                 $description{$role}= $role;
 9012:             }
 9013:             $count++;
 9014:         }
 9015:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9016:         my @roles_by_num = ();
 9017:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9018:             push(@roles_by_num,$ordered{$item});
 9019:         }
 9020:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 9021:         if ($permission->{'owner'}) {
 9022:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 9023:             $r->print('<input type="hidden" name="state" value="process" />'.
 9024:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 9025:         } else {
 9026:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 9027:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 9028:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 9029:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 9030:             }
 9031:             $disabled = ' disabled="disabled"';
 9032:         }
 9033:         $r->print('</p>');
 9034: 
 9035:         $r->print('<div id="LC_minitab_header"><ul>');
 9036:         my $count = 0;
 9037:         my %visibility;
 9038:         foreach my $role (@roles_by_num) {
 9039:             my $id;
 9040:             if ($count == 0) {
 9041:                 $id=' id="LC_current_minitab"';
 9042:                 $visibility{$role} = ' style="display:block"';
 9043:             } else {
 9044:                 $visibility{$role} = ' style="display:none"';
 9045:             }
 9046:             $count ++;
 9047:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 9048:         }
 9049:         $r->print('</ul></div>');
 9050: 
 9051:         foreach my $role (@roles_by_num) {
 9052:             my %usecheck = (
 9053:                              all => ' checked="checked"',
 9054:                            );
 9055:             my %displaydiv = (
 9056:                                 status => 'none',
 9057:                                 inc    => 'none',
 9058:                                 exc    => 'none',
 9059:                                 priv   => 'block',
 9060:                              );
 9061:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 9062:             if (ref($settings{$role}) eq 'HASH') {
 9063:                 if ($settings{$role}{'access'} ne '') {
 9064:                     $indomvis = ' style="display:none"';
 9065:                     $incrsvis = ' style="display:block"';
 9066:                     $incrscheck = ' checked="checked"';
 9067:                     if ($settings{$role}{'access'} ne 'all') {
 9068:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 9069:                         delete($usecheck{'all'});
 9070:                         if ($settings{$role}{'access'} eq 'status') {
 9071:                             my $access = 'status';
 9072:                             $displaydiv{$access} = 'inline';
 9073:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9074:                                 $selected{$access} = $settings{$role}{$access};
 9075:                             }
 9076:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 9077:                             my $access = $1;
 9078:                             $displaydiv{$access} = 'inline';
 9079:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 9080:                                 $selected{$access} = $settings{$role}{$access};
 9081:                             }
 9082:                         } elsif ($settings{$role}{'access'} eq 'none') {
 9083:                             $displaydiv{'priv'} = 'none';
 9084:                         }
 9085:                     }
 9086:                 } else {
 9087:                     $indomcheck = ' checked="checked"';
 9088:                     $indomvis = ' style="display:block"';
 9089:                     $incrsvis = ' style="display:none"';
 9090:                 }
 9091:             } else {
 9092:                 $indomcheck = ' checked="checked"';
 9093:                 $indomvis = ' style="display:block"';
 9094:                 $incrsvis = ' style="display:none"';
 9095:             }
 9096:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 9097:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 9098:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 9099:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9100:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 9101:                       '<span>'.('&nbsp;'x2).
 9102:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 9103:                       $lt{'udd'}.'</label><span></p>'.
 9104:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 9105:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 9106:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 9107:             foreach my $access (@accesstypes) {
 9108:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 9109:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 9110:                 if ($access eq 'status') {
 9111:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 9112:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 9113:                                                                         $othertitle,$usertypes,$types,$disabled).
 9114:                               '</div>');
 9115:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 9116:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 9117:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9118:                                                                  \%domhelpdesk,$disabled).
 9119:                               '</div>');
 9120:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 9121:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 9122:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 9123:                                                                  \%domhelpdesk,$disabled).
 9124:                               '</div>');
 9125:                 }
 9126:                 $r->print('</p>');
 9127:             }
 9128:             $r->print('</div></fieldset>');
 9129:             my %full=();
 9130:             my %levels= (
 9131:                          course => {},
 9132:                          domain => {},
 9133:                          system => {},
 9134:                         );
 9135:             my %levelscurrent=(
 9136:                                course => {},
 9137:                                domain => {},
 9138:                                system => {},
 9139:                               );
 9140:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9141:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 9142:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 9143:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 9144:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 9145:         }
 9146:         if ($permission->{'owner'}) {
 9147:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 9148:         }
 9149:     } else {
 9150:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 9151:     }
 9152:     # Form Footer
 9153:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 9154:              .'</form>');
 9155:     return;
 9156: }
 9157: 
 9158: sub print_queued_roles {
 9159:     my ($r,$context,$permission,$brcrum) = @_;
 9160:     push (@{$brcrum},
 9161:              {href => '/adm/createuser?action=rolerequests',
 9162:               text => 'Role Requests (other domains)',
 9163:               help => ''});
 9164:     my $bread_crumbs_component = 'Role Requests';
 9165:     my $args = { bread_crumbs           => $brcrum,
 9166:                  bread_crumbs_component => $bread_crumbs_component};
 9167:     # print page header
 9168:     $r->print(&header('',$args));
 9169:     my ($dom,$cnum);
 9170:     $dom = $env{'request.role.domain'};
 9171:     if ($context eq 'course') {
 9172:         if ($env{'request.course.id'}) {
 9173:             if (&Apache::loncommon::course_type() eq 'Community') {
 9174:                 $context = 'community';
 9175:             }
 9176:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9177:         }
 9178:     } elsif ($context eq 'author') {
 9179:         $cnum = $env{'user.name'};
 9180:     }
 9181:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomqueue',$dom,$cnum,$context));
 9182:     return;
 9183: }
 9184: 
 9185: sub print_pendingroles {
 9186:     my ($r,$context,$permission,$brcrum) = @_;
 9187:     push (@{$brcrum},
 9188:              {href => '/adm/createuser?action=queuedroles',
 9189:               text => 'Queued Role Assignments (users in this domain)',
 9190:               help => ''});
 9191:     my $bread_crumbs_component = 'Queued Role Assignments';
 9192:     my $args = { bread_crumbs           => $brcrum,
 9193:                  bread_crumbs_component => $bread_crumbs_component};
 9194:     # print page header
 9195:     $r->print(&header('',$args));
 9196:     $r->print(&Apache::loncoursequeueadmin::display_queued_requests('othdomaction',$env{'request.role.domain'},'','domain'));
 9197:     return;
 9198: }
 9199: 
 9200: sub process_pendingroles {
 9201:     my ($r,$context,$permission,$brcrum) = @_;
 9202:     push (@{$brcrum},
 9203:              {href => '/adm/createuser?action=queuedroles',
 9204:               text => 'Queued Role Assignments (users in this domain)',
 9205:               help => ''},
 9206:              {href => '/adm/createuser?action=processrolereq',
 9207:               text => 'Process Queue',
 9208:               help => ''});
 9209:     my $bread_crumbs_component = 'Queued Role Assignments';
 9210:     my $args = { bread_crumbs           => $brcrum,
 9211:                  bread_crumbs_component => $bread_crumbs_component};
 9212:     # print page header
 9213:     $r->print(&header('',$args));
 9214:     $r->print(&Apache::loncoursequeueadmin::update_request_queue('othdombydc',
 9215:                                                                  $env{'request.role.domain'}));
 9216:     return;
 9217: }
 9218: 
 9219: sub domain_adhoc_access {
 9220:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 9221:     my %domusage;
 9222:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 9223:     foreach my $role (keys(%{$roles})) {
 9224:         if (ref($domcurrent->{$role}) eq 'HASH') {
 9225:             my $access = $domcurrent->{$role}{'access'};
 9226:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 9227:                 $access = 'all';
 9228:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 9229:                                                                                           &Apache::lonnet::plaintext('da'));
 9230:             } elsif ($access eq 'status') {
 9231:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 9232:                     my @shown;
 9233:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 9234:                         unless ($type eq 'default') {
 9235:                             if ($usertypes->{$type}) {
 9236:                                 push(@shown,$usertypes->{$type});
 9237:                             }
 9238:                         }
 9239:                     }
 9240:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 9241:                         push(@shown,$othertitle);
 9242:                     }
 9243:                     if (@shown) {
 9244:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 9245:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 9246:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 9247:                     } else {
 9248:                         $domusage{$role} = &mt('No one in the domain');
 9249:                     }
 9250:                 }
 9251:             } elsif ($access eq 'inc') {
 9252:                 my @dominc = ();
 9253:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 9254:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 9255:                         my ($uname,$udom) = split(/:/,$user);
 9256:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9257:                     }
 9258:                     my $showninc = join(', ',@dominc);
 9259:                     if ($showninc ne '') {
 9260:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 9261:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 9262:                     } else {
 9263:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9264:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9265:                     }
 9266:                 }
 9267:             } elsif ($access eq 'exc') {
 9268:                 my @domexc = ();
 9269:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 9270:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 9271:                         my ($uname,$udom) = split(/:/,$user);
 9272:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 9273:                     }
 9274:                 }
 9275:                 my $shownexc = join(', ',@domexc);
 9276:                 if ($shownexc ne '') {
 9277:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 9278:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 9279:                 } else {
 9280:                     $domusage{$role} = &mt('No one in the domain');
 9281:                 }
 9282:             } elsif ($access eq 'none') {
 9283:                 $domusage{$role} = &mt('No one in the domain');
 9284:             } elsif ($access eq 'dh') {
 9285:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 9286:             } elsif ($access eq 'da') {
 9287:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 9288:             } elsif ($access eq 'all') {
 9289:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9290:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9291:             }
 9292:         } else {
 9293:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 9294:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 9295:         }
 9296:     }
 9297:     return %domusage;
 9298: }
 9299: 
 9300: sub get_domain_customroles {
 9301:     my ($cdom,$confname) = @_;
 9302:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 9303:     my %customroles;
 9304:     foreach my $key (keys(%existing)) {
 9305:         if ($key=~/^rolesdef\_(\w+)$/) {
 9306:             my $rolename = $1;
 9307:             my %privs;
 9308:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 9309:             $customroles{$rolename} = \%privs;
 9310:         }
 9311:     }
 9312:     return %customroles;
 9313: }
 9314: 
 9315: sub role_priv_table {
 9316:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 9317:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 9318:                    (ref($levelscurrent) eq 'HASH'));
 9319:     my %lt=&Apache::lonlocal::texthash (
 9320:                     'crl'  => 'Course Level Privilege',
 9321:                     'def'  => 'Domain Defaults',
 9322:                     'ove'  => 'Override in Course',
 9323:                     'ine'  => 'In effect',
 9324:                     'dis'  => 'Disabled',
 9325:                     'ena'  => 'Enabled',
 9326:                    );
 9327:     if ($crstype eq 'Community') {
 9328:         $lt{'ove'} = 'Override in Community',
 9329:     }
 9330:     my @status = ('Disabled','Enabled');
 9331:     my (%on,%off);
 9332:     if (ref($overridden) eq 'HASH') {
 9333:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 9334:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 9335:         }
 9336:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 9337:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 9338:         }
 9339:     }
 9340:     my $output=&Apache::loncommon::start_data_table().
 9341:                &Apache::loncommon::start_data_table_header_row().
 9342:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 9343:                '</th><th>'.$lt{'ine'}.'</th>'.
 9344:                &Apache::loncommon::end_data_table_header_row();
 9345:     foreach my $priv (sort(keys(%{$full}))) {
 9346:         next unless ($levels->{'course'}{$priv});
 9347:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 9348:         my ($default,$ineffect);
 9349:         if ($levelscurrent->{'course'}{$priv}) {
 9350:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9351:             $ineffect = $default;
 9352:         }
 9353:         my ($customstatus,$checked);
 9354:         $output .= &Apache::loncommon::start_data_table_row().
 9355:                    '<td>'.$privtext.'</td>'.
 9356:                    '<td>'.$default.'</td><td>';
 9357:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 9358:             if ($permission->{'owner'}) {
 9359:                 $checked = ' checked="checked"';
 9360:             }
 9361:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 9362:             $ineffect = $customstatus;
 9363:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 9364:             if ($permission->{'owner'}) {
 9365:                 $checked = ' checked="checked"';
 9366:             }
 9367:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 9368:             $ineffect = $customstatus;
 9369:         }
 9370:         if ($permission->{'owner'}) {
 9371:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 9372:         } else {
 9373:             $output .= $customstatus;
 9374:         }
 9375:         $output .= '</td><td>'.$ineffect.'</td>'.
 9376:                    &Apache::loncommon::end_data_table_row();
 9377:     }
 9378:     $output .= &Apache::loncommon::end_data_table();
 9379:     return $output;
 9380: }
 9381: 
 9382: sub get_adhocrole_settings {
 9383:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 9384:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 9385:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 9386:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 9387:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 9388:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 9389:             $settings->{$role}{'access'} = $curraccess;
 9390:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 9391:                 my @status = split(/,/,$rest);
 9392:                 my @currstatus;
 9393:                 foreach my $type (@status) {
 9394:                     if ($type eq 'default') {
 9395:                         push(@currstatus,$type);
 9396:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9397:                         push(@currstatus,$type);
 9398:                     }
 9399:                 }
 9400:                 if (@currstatus) {
 9401:                     $settings->{$role}{$curraccess} = \@currstatus;
 9402:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 9403:                     my @personnel = split(/,/,$rest);
 9404:                     $settings->{$role}{$curraccess} = \@personnel;
 9405:                 }
 9406:             }
 9407:         }
 9408:     }
 9409:     foreach my $role (keys(%{$customroles})) {
 9410:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 9411:             my %currentprivs;
 9412:             if (ref($customroles->{$role}) eq 'HASH') {
 9413:                 if (exists($customroles->{$role}{'course'})) {
 9414:                     my %full=();
 9415:                     my %levels= (
 9416:                                   course => {},
 9417:                                   domain => {},
 9418:                                   system => {},
 9419:                                 );
 9420:                     my %levelscurrent=(
 9421:                                         course => {},
 9422:                                         domain => {},
 9423:                                         system => {},
 9424:                                       );
 9425:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 9426:                     %currentprivs = %{$levelscurrent{'course'}};
 9427:                 }
 9428:             }
 9429:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 9430:                 next if ($item eq '');
 9431:                 my ($rule,$rest) = split(/=/,$item);
 9432:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 9433:                 foreach my $priv (split(/:/,$rest)) {
 9434:                     if ($priv ne '') {
 9435:                         if ($rule eq 'off') {
 9436:                             push(@{$overridden->{$role}{'off'}},$priv);
 9437:                             if ($currentprivs{$priv}) {
 9438:                                 push(@{$settings->{$role}{'off'}},$priv);
 9439:                             }
 9440:                         } else {
 9441:                             push(@{$overridden->{$role}{'on'}},$priv);
 9442:                             unless ($currentprivs{$priv}) {
 9443:                                 push(@{$settings->{$role}{'on'}},$priv);
 9444:                             }
 9445:                         }
 9446:                     }
 9447:                 }
 9448:             }
 9449:         }
 9450:     }
 9451:     return;
 9452: }
 9453: 
 9454: sub update_helpdeskaccess {
 9455:     my ($r,$permission,$brcrum) = @_;
 9456:     my $helpitem = 'Course_Helpdesk_Access';
 9457:     push (@{$brcrum},
 9458:              {href => '/adm/createuser?action=helpdesk',
 9459:               text => 'Helpdesk Access',
 9460:               help => $helpitem},
 9461:              {href => '/adm/createuser?action=helpdesk',
 9462:               text => 'Result',
 9463:               help => $helpitem}
 9464:          );
 9465:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 9466:     my $args = { bread_crumbs           => $brcrum,
 9467:                  bread_crumbs_component => $bread_crumbs_component};
 9468: 
 9469:     # print page header
 9470:     $r->print(&header('',$args));
 9471:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 9472:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 9473:         return;
 9474:     }
 9475:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 9476:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9477:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9478:     my $confname = $cdom.'-domainconfig';
 9479:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 9480:     my $crstype = &Apache::loncommon::course_type();
 9481:     my %customroles = &get_domain_customroles($cdom,$confname);
 9482:     my (%settings,%overridden);
 9483:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 9484:                             $types,\%customroles,\%settings,\%overridden);
 9485:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 9486:     my (%changed,%storehash,@todelete);
 9487: 
 9488:     if (keys(%customroles)) {
 9489:         my (%newsettings,@incrs);
 9490:         foreach my $role (keys(%customroles)) {
 9491:             $newsettings{$role} = {
 9492:                                     access => '',
 9493:                                     status => '',
 9494:                                     exc    => '',
 9495:                                     inc    => '',
 9496:                                     on     => '',
 9497:                                     off    => '',
 9498:                                   };
 9499:             my %current;
 9500:             if (ref($settings{$role}) eq 'HASH') {
 9501:                 %current = %{$settings{$role}};
 9502:             }
 9503:             if (ref($overridden{$role}) eq 'HASH') {
 9504:                 $current{'overridden'} = $overridden{$role};
 9505:             }
 9506:             if ($env{'form.'.$role.'_incrs'}) {
 9507:                 my $access = $env{'form.'.$role.'_access'};
 9508:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 9509:                     push(@incrs,$role);
 9510:                     unless ($current{'access'} eq $access) {
 9511:                         $changed{$role}{'access'} = 1;
 9512:                         $storehash{'internal.adhoc.'.$role} = $access;
 9513:                     }
 9514:                     if ($access eq 'status') {
 9515:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 9516:                         my @stored;
 9517:                         my @shownstatus;
 9518:                         if (ref($types) eq 'ARRAY') {
 9519:                             foreach my $type (sort(@statuses)) {
 9520:                                 if ($type eq 'default') {
 9521:                                     push(@stored,$type);
 9522:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 9523:                                     push(@stored,$type);
 9524:                                     push(@shownstatus,$usertypes->{$type});
 9525:                                 }
 9526:                             }
 9527:                             if (grep(/^default$/,@statuses)) {
 9528:                                 push(@shownstatus,$othertitle);
 9529:                             }
 9530:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9531:                         }
 9532:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 9533:                         if (ref($current{'status'}) eq 'ARRAY') {
 9534:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 9535:                             if (@diffs) {
 9536:                                 $changed{$role}{'status'} = 1;
 9537:                             }
 9538:                         } elsif (@stored) {
 9539:                             $changed{$role}{'status'} = 1;
 9540:                         }
 9541:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 9542:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 9543:                         my @newspecstaff;
 9544:                         my @stored;
 9545:                         my @currstaff;
 9546:                         foreach my $person (sort(@personnel)) {
 9547:                             if ($domhelpdesk{$person}) {
 9548:                                 push(@stored,$person);
 9549:                             }
 9550:                         }
 9551:                         if (ref($current{$access}) eq 'ARRAY') {
 9552:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 9553:                             if (@diffs) {
 9554:                                 $changed{$role}{$access} = 1;
 9555:                             }
 9556:                         } elsif (@stored) {
 9557:                             $changed{$role}{$access} = 1;
 9558:                         }
 9559:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 9560:                         foreach my $person (@stored) {
 9561:                             my ($uname,$udom) = split(/:/,$person);
 9562:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 9563:                         }
 9564:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 9565:                     }
 9566:                     $newsettings{$role}{'access'} = $access;
 9567:                 }
 9568:             } else {
 9569:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 9570:                     $changed{$role}{'access'} = 1;
 9571:                     $newsettings{$role} = {};
 9572:                     push(@todelete,'internal.adhoc.'.$role);
 9573:                 }
 9574:             }
 9575:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 9576:                 if (ref($current{'overridden'}) eq 'HASH') {
 9577:                     push(@todelete,'internal.adhocpriv.'.$role);
 9578:                 }
 9579:             } else {
 9580:                 my %full=();
 9581:                 my %levels= (
 9582:                              course => {},
 9583:                              domain => {},
 9584:                              system => {},
 9585:                             );
 9586:                 my %levelscurrent=(
 9587:                                    course => {},
 9588:                                    domain => {},
 9589:                                    system => {},
 9590:                                   );
 9591:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 9592:                 my (@updatedon,@updatedoff,@override);
 9593:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 9594:                 if (@override) {
 9595:                     foreach my $priv (sort(keys(%full))) {
 9596:                         next unless ($levels{'course'}{$priv});
 9597:                         if (grep(/^\Q$priv\E$/,@override)) {
 9598:                             if ($levelscurrent{'course'}{$priv}) {
 9599:                                 push(@updatedoff,$priv);
 9600:                             } else {
 9601:                                 push(@updatedon,$priv);
 9602:                             }
 9603:                         }
 9604:                     }
 9605:                 }
 9606:                 if (@updatedon) {
 9607:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 9608:                 }
 9609:                 if (@updatedoff) {
 9610:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 9611:                 }
 9612:                 if (ref($current{'overridden'}) eq 'HASH') {
 9613:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 9614:                         if (@updatedon) {
 9615:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 9616:                             if (@diffs) {
 9617:                                 $changed{$role}{'on'} = 1;
 9618:                             }
 9619:                         } else {
 9620:                             $changed{$role}{'on'} = 1;
 9621:                         }
 9622:                     } elsif (@updatedon) {
 9623:                         $changed{$role}{'on'} = 1;
 9624:                     }
 9625:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 9626:                         if (@updatedoff) {
 9627:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 9628:                             if (@diffs) {
 9629:                                 $changed{$role}{'off'} = 1;
 9630:                             }
 9631:                         } else {
 9632:                             $changed{$role}{'off'} = 1;
 9633:                         }
 9634:                     } elsif (@updatedoff) {
 9635:                         $changed{$role}{'off'} = 1;
 9636:                     }
 9637:                 } else {
 9638:                     if (@updatedon) {
 9639:                         $changed{$role}{'on'} = 1;
 9640:                     }
 9641:                     if (@updatedoff) {
 9642:                         $changed{$role}{'off'} = 1;
 9643:                     }
 9644:                 }
 9645:                 if (ref($changed{$role}) eq 'HASH') {
 9646:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 9647:                         my $newpriv;
 9648:                         if (@updatedon) {
 9649:                             $newpriv = 'on='.join(':',@updatedon);
 9650:                         }
 9651:                         if (@updatedoff) {
 9652:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 9653:                         }
 9654:                         if ($newpriv eq '') {
 9655:                             push(@todelete,'internal.adhocpriv.'.$role);
 9656:                         } else {
 9657:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 9658:                         }
 9659:                     }
 9660:                 }
 9661:             }
 9662:         }
 9663:         if (@incrs) {
 9664:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 9665:         } elsif (@todelete) {
 9666:             push(@todelete,'internal.adhocaccess');
 9667:         }
 9668:         if (keys(%changed)) {
 9669:             my ($putres,$delres);
 9670:             if (keys(%storehash)) {
 9671:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 9672:                 my %newenvhash;
 9673:                 foreach my $key (keys(%storehash)) {
 9674:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 9675:                 }
 9676:                 &Apache::lonnet::appenv(\%newenvhash);
 9677:             }
 9678:             if (@todelete) {
 9679:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 9680:                 foreach my $key (@todelete) {
 9681:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 9682:                 }
 9683:             }
 9684:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 9685:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 9686:                 my (%domcurrent,%ordered,%description,%domusage);
 9687:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 9688:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 9689:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 9690:                     }
 9691:                 }
 9692:                 my $count = 0;
 9693:                 foreach my $role (sort(keys(%customroles))) {
 9694:                     my ($order,$desc);
 9695:                     if (ref($domcurrent{$role}) eq 'HASH') {
 9696:                         $order = $domcurrent{$role}{'order'};
 9697:                         $desc = $domcurrent{$role}{'desc'};
 9698:                     }
 9699:                     if ($order eq '') {
 9700:                         $order = $count;
 9701:                     }
 9702:                     $ordered{$order} = $role;
 9703:                     if ($desc ne '') {
 9704:                         $description{$role} = $desc;
 9705:                     } else {
 9706:                         $description{$role}= $role;
 9707:                     }
 9708:                     $count++;
 9709:                 }
 9710:                 my @roles_by_num = ();
 9711:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 9712:                     push(@roles_by_num,$ordered{$item});
 9713:                 }
 9714:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 9715:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 9716:                 $r->print('<ul>');
 9717:                 foreach my $role (@roles_by_num) {
 9718:                     next unless (ref($changed{$role}) eq 'HASH');
 9719:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 9720:                               '<ul>');
 9721:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 9722:                         $r->print('<li>');
 9723:                         if ($env{'form.'.$role.'_incrs'}) {
 9724:                             if ($newsettings{$role}{'access'} eq 'all') {
 9725:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 9726:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 9727:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9728:                                               &Apache::lonnet::plaintext('dh')));
 9729:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 9730:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 9731:                                               &Apache::lonnet::plaintext('da')));
 9732:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 9733:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9734:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 9735:                                 if ($newsettings{$role}{'status'}) {
 9736:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 9737:                                     if (split(/,/,$rest) > 1) {
 9738:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 9739:                                                       $newsettings{$role}{'status'}));
 9740:                                     } else {
 9741:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 9742:                                                       $newsettings{$role}{'status'}));
 9743:                                     }
 9744:                                 } else {
 9745:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9746:                                 }
 9747:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 9748:                                 if ($newsettings{$role}{'exc'}) {
 9749:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 9750:                                 } else {
 9751:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 9752:                                 }
 9753:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 9754:                                 if ($newsettings{$role}{'inc'}) {
 9755:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 9756:                                 } else {
 9757:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 9758:                                 }
 9759:                             }
 9760:                         } else {
 9761:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 9762:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 9763:                         }
 9764:                         $r->print('</li>');
 9765:                     }
 9766:                     unless ($newsettings{$role}{'access'} eq 'none') {
 9767:                         if ($changed{$role}{'off'}) {
 9768:                             if ($newsettings{$role}{'off'}) {
 9769:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 9770:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 9771:                             } else {
 9772:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 9773:                             }
 9774:                         }
 9775:                         if ($changed{$role}{'on'}) {
 9776:                             if ($newsettings{$role}{'on'}) {
 9777:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 9778:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 9779:                             } else {
 9780:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 9781:                             }
 9782:                         }
 9783:                     }
 9784:                     $r->print('</ul></li>');
 9785:                 }
 9786:                 $r->print('</ul>');
 9787:             }
 9788:         } else {
 9789:             $r->print(&mt('No changes made to helpdesk access settings.'));
 9790:         }
 9791:     }
 9792:     return;
 9793: }
 9794: 
 9795: #-------------------------------------------------- functions for &phase_two
 9796: sub user_search_result {
 9797:     my ($context,$srch) = @_;
 9798:     my %allhomes;
 9799:     my %inst_matches;
 9800:     my %srch_results;
 9801:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 9802:     $srch->{'srchterm'} =~ s/\s+/ /g;
 9803:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 9804:         $response = &mt('Invalid search.');
 9805:     }
 9806:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 9807:         $response = &mt('Invalid search.');
 9808:     }
 9809:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 9810:         $response = &mt('Invalid search.');
 9811:     }
 9812:     if ($srch->{'srchterm'} eq '') {
 9813:         $response = &mt('You must enter a search term.');
 9814:     }
 9815:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 9816:         $response = &mt('Your search term must contain more than just spaces.');
 9817:     }
 9818:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 9819:         if (($srch->{'srchdomain'} eq '') || 
 9820: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 9821:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 9822:         }
 9823:     }
 9824:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 9825:         ($srch->{'srchin'} eq 'alc')) {
 9826:         if ($srch->{'srchby'} eq 'uname') {
 9827:             my $unamecheck = $srch->{'srchterm'};
 9828:             if ($srch->{'srchtype'} eq 'contains') {
 9829:                 if ($unamecheck !~ /^\w/) {
 9830:                     $unamecheck = 'a'.$unamecheck; 
 9831:                 }
 9832:             }
 9833:             if ($unamecheck !~ /^$match_username$/) {
 9834:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 9835:             }
 9836:         }
 9837:     }
 9838:     if ($response ne '') {
 9839:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 9840:     }
 9841:     if ($srch->{'srchin'} eq 'instd') {
 9842:         my $instd_chk = &instdirectorysrch_check($srch);
 9843:         if ($instd_chk ne 'ok') {
 9844:             my $domd_chk = &domdirectorysrch_check($srch);
 9845:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 9846:             if ($domd_chk eq 'ok') {
 9847:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 9848:             }
 9849:             $response .= '<br />';
 9850:         }
 9851:     } else {
 9852:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 9853:             my $domd_chk = &domdirectorysrch_check($srch);
 9854:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 9855:                 my $instd_chk = &instdirectorysrch_check($srch);
 9856:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 9857:                 if ($instd_chk eq 'ok') {
 9858:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 9859:                 }
 9860:                 $response .= '<br />';
 9861:             }
 9862:         }
 9863:     }
 9864:     if ($response ne '') {
 9865:         return ($currstate,$response);
 9866:     }
 9867:     if ($srch->{'srchby'} eq 'uname') {
 9868:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 9869:             if ($env{'form.forcenew'}) {
 9870:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 9871:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9872:                     if ($uhome eq 'no_host') {
 9873:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 9874:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 9875:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 9876:                     } else {
 9877:                         $currstate = 'modify';
 9878:                     }
 9879:                 } else {
 9880:                     $currstate = 'modify';
 9881:                 }
 9882:             } else {
 9883:                 if ($srch->{'srchin'} eq 'dom') {
 9884:                     if ($srch->{'srchtype'} eq 'exact') {
 9885:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 9886:                         if ($uhome eq 'no_host') {
 9887:                             ($currstate,$response,$forcenewuser) =
 9888:                                 &build_search_response($context,$srch,%srch_results);
 9889:                         } else {
 9890:                             $currstate = 'modify';
 9891:                             if ($env{'form.action'} eq 'accesslogs') {
 9892:                                 $currstate = 'activity';
 9893:                             }
 9894:                             my $uname = $srch->{'srchterm'};
 9895:                             my $udom = $srch->{'srchdomain'};
 9896:                             $srch_results{$uname.':'.$udom} =
 9897:                                 { &Apache::lonnet::get('environment',
 9898:                                                        ['firstname',
 9899:                                                         'lastname',
 9900:                                                         'permanentemail'],
 9901:                                                          $udom,$uname)
 9902:                                 };
 9903:                         }
 9904:                     } else {
 9905:                         %srch_results = &Apache::lonnet::usersearch($srch);
 9906:                         ($currstate,$response,$forcenewuser) =
 9907:                             &build_search_response($context,$srch,%srch_results);
 9908:                     }
 9909:                 } else {
 9910:                     my $courseusers = &get_courseusers();
 9911:                     if ($srch->{'srchtype'} eq 'exact') {
 9912:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 9913:                             $currstate = 'modify';
 9914:                         } else {
 9915:                             ($currstate,$response,$forcenewuser) =
 9916:                                 &build_search_response($context,$srch,%srch_results);
 9917:                         }
 9918:                     } else {
 9919:                         foreach my $user (keys(%$courseusers)) {
 9920:                             my ($cuname,$cudomain) = split(/:/,$user);
 9921:                             if ($cudomain eq $srch->{'srchdomain'}) {
 9922:                                 my $matched = 0;
 9923:                                 if ($srch->{'srchtype'} eq 'begins') {
 9924:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 9925:                                         $matched = 1;
 9926:                                     }
 9927:                                 } else {
 9928:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 9929:                                         $matched = 1;
 9930:                                     }
 9931:                                 }
 9932:                                 if ($matched) {
 9933:                                     $srch_results{$user} = 
 9934: 					{&Apache::lonnet::get('environment',
 9935: 							     ['firstname',
 9936: 							      'lastname',
 9937: 							      'permanentemail'],
 9938: 							      $cudomain,$cuname)};
 9939:                                 }
 9940:                             }
 9941:                         }
 9942:                         ($currstate,$response,$forcenewuser) =
 9943:                             &build_search_response($context,$srch,%srch_results);
 9944:                     }
 9945:                 }
 9946:             }
 9947:         } elsif ($srch->{'srchin'} eq 'alc') {
 9948:             $currstate = 'query';
 9949:         } elsif ($srch->{'srchin'} eq 'instd') {
 9950:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 9951:             if ($dirsrchres eq 'ok') {
 9952:                 ($currstate,$response,$forcenewuser) = 
 9953:                     &build_search_response($context,$srch,%srch_results);
 9954:             } else {
 9955:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 9956:                 $response = '<span class="LC_warning">'.
 9957:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 9958:                     '</span><br />'.
 9959:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 9960:                     '<br />'; 
 9961:             }
 9962:         }
 9963:     } else {
 9964:         if ($srch->{'srchin'} eq 'dom') {
 9965:             %srch_results = &Apache::lonnet::usersearch($srch);
 9966:             ($currstate,$response,$forcenewuser) = 
 9967:                 &build_search_response($context,$srch,%srch_results); 
 9968:         } elsif ($srch->{'srchin'} eq 'crs') {
 9969:             my $courseusers = &get_courseusers(); 
 9970:             foreach my $user (keys(%$courseusers)) {
 9971:                 my ($uname,$udom) = split(/:/,$user);
 9972:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 9973:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 9974:                 if ($srch->{'srchby'} eq 'lastname') {
 9975:                     if ((($srch->{'srchtype'} eq 'exact') && 
 9976:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 9977:                         (($srch->{'srchtype'} eq 'begins') &&
 9978:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 9979:                         (($srch->{'srchtype'} eq 'contains') &&
 9980:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 9981:                         $srch_results{$user} = {firstname => $names{'firstname'},
 9982:                                             lastname => $names{'lastname'},
 9983:                                             permanentemail => $emails{'permanentemail'},
 9984:                                            };
 9985:                     }
 9986:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 9987:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 9988:                     $srchlast =~ s/\s+$//;
 9989:                     $srchfirst =~ s/^\s+//;
 9990:                     if ($srch->{'srchtype'} eq 'exact') {
 9991:                         if (($names{'lastname'} eq $srchlast) &&
 9992:                             ($names{'firstname'} eq $srchfirst)) {
 9993:                             $srch_results{$user} = {firstname => $names{'firstname'},
 9994:                                                 lastname => $names{'lastname'},
 9995:                                                 permanentemail => $emails{'permanentemail'},
 9996: 
 9997:                                            };
 9998:                         }
 9999:                     } elsif ($srch->{'srchtype'} eq 'begins') {
10000:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
10001:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
10002:                             $srch_results{$user} = {firstname => $names{'firstname'},
10003:                                                 lastname => $names{'lastname'},
10004:                                                 permanentemail => $emails{'permanentemail'},
10005:                                                };
10006:                         }
10007:                     } else {
10008:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
10009:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
10010:                             $srch_results{$user} = {firstname => $names{'firstname'},
10011:                                                 lastname => $names{'lastname'},
10012:                                                 permanentemail => $emails{'permanentemail'},
10013:                                                };
10014:                         }
10015:                     }
10016:                 }
10017:             }
10018:             ($currstate,$response,$forcenewuser) = 
10019:                 &build_search_response($context,$srch,%srch_results); 
10020:         } elsif ($srch->{'srchin'} eq 'alc') {
10021:             $currstate = 'query';
10022:         } elsif ($srch->{'srchin'} eq 'instd') {
10023:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
10024:             if ($dirsrchres eq 'ok') {
10025:                 ($currstate,$response,$forcenewuser) = 
10026:                     &build_search_response($context,$srch,%srch_results);
10027:             } else {
10028:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
10029:                 $response = '<span class="LC_warning">'.
10030:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
10031:                     '</span><br />'.
10032:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
10033:                     '<br />';
10034:             }
10035:         }
10036:     }
10037:     return ($currstate,$response,$forcenewuser,\%srch_results);
10038: }
10039: 
10040: sub domdirectorysrch_check {
10041:     my ($srch) = @_;
10042:     my $response;
10043:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10044:                                              ['directorysrch'],$srch->{'srchdomain'});
10045:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10046:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10047:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
10048:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
10049:         }
10050:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
10051:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10052:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
10053:             }
10054:         }
10055:     }
10056:     return 'ok';
10057: }
10058: 
10059: sub instdirectorysrch_check {
10060:     my ($srch) = @_;
10061:     my $can_search = 0;
10062:     my $response;
10063:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
10064:                                              ['directorysrch'],$srch->{'srchdomain'});
10065:     my $showdom = &display_domain_info($srch->{'srchdomain'});
10066:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
10067:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
10068:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
10069:         }
10070:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
10071:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
10072:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
10073:             }
10074:             my @usertypes = split(/:/,$env{'environment.inststatus'});
10075:             if (!@usertypes) {
10076:                 push(@usertypes,'default');
10077:             }
10078:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
10079:                 foreach my $type (@usertypes) {
10080:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
10081:                         $can_search = 1;
10082:                         last;
10083:                     }
10084:                 }
10085:             }
10086:             if (!$can_search) {
10087:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
10088:                 my @longtypes; 
10089:                 foreach my $item (@usertypes) {
10090:                     if (defined($insttypes->{$item})) { 
10091:                         push (@longtypes,$insttypes->{$item});
10092:                     } elsif ($item eq 'default') {
10093:                         push (@longtypes,&mt('other')); 
10094:                     }
10095:                 }
10096:                 my $insttype_str = join(', ',@longtypes); 
10097:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
10098:             }
10099:         } else {
10100:             $can_search = 1;
10101:         }
10102:     } else {
10103:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
10104:     }
10105:     my %longtext = &Apache::lonlocal::texthash (
10106:                        uname     => 'username',
10107:                        lastfirst => 'last name, first name',
10108:                        lastname  => 'last name',
10109:                        contains  => 'contains',
10110:                        exact     => 'as exact match to',
10111:                        begins    => 'begins with',
10112:                    );
10113:     if ($can_search) {
10114:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
10115:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
10116:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
10117:             }
10118:         } else {
10119:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
10120:         }
10121:     }
10122:     if ($can_search) {
10123:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
10124:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
10125:                 return 'ok';
10126:             } else {
10127:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10128:             }
10129:         } else {
10130:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
10131:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
10132:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
10133:                 return 'ok';
10134:             } else {
10135:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
10136:             }
10137:         }
10138:     }
10139: }
10140: 
10141: sub get_courseusers {
10142:     my %advhash;
10143:     my $classlist = &Apache::loncoursedata::get_classlist();
10144:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
10145:     foreach my $role (sort(keys(%coursepersonnel))) {
10146:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
10147: 	    if (!exists($classlist->{$user})) {
10148: 		$classlist->{$user} = [];
10149: 	    }
10150:         }
10151:     }
10152:     return $classlist;
10153: }
10154: 
10155: sub build_search_response {
10156:     my ($context,$srch,%srch_results) = @_;
10157:     my ($currstate,$response,$forcenewuser);
10158:     my %names = (
10159:           'uname'     => 'username',
10160:           'lastname'  => 'last name',
10161:           'lastfirst' => 'last name, first name',
10162:           'crs'       => 'this course',
10163:           'dom'       => 'LON-CAPA domain',
10164:           'instd'     => 'the institutional directory for domain',
10165:     );
10166: 
10167:     my %single = (
10168:                    begins   => 'A match',
10169:                    contains => 'A match',
10170:                    exact    => 'An exact match',
10171:                  );
10172:     my %nomatch = (
10173:                    begins   => 'No match',
10174:                    contains => 'No match',
10175:                    exact    => 'No exact match',
10176:                   );
10177:     if (keys(%srch_results) > 1) {
10178:         $currstate = 'select';
10179:     } else {
10180:         if (keys(%srch_results) == 1) {
10181:             if ($env{'form.action'} eq 'accesslogs') {
10182:                 $currstate = 'activity';
10183:             } else {
10184:                 $currstate = 'modify';
10185:             }
10186:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
10187:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10188:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
10189:             }
10190:         } else { # Search has nothing found. Prepare message to user.
10191:             $response = '<span class="LC_warning">';
10192:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
10193:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
10194:                                  '<b>'.$srch->{'srchterm'}.'</b>',
10195:                                  &display_domain_info($srch->{'srchdomain'}));
10196:             } else {
10197:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
10198:                                  '<b>'.$srch->{'srchterm'}.'</b>');
10199:             }
10200:             $response .= '</span>';
10201: 
10202:             if ($srch->{'srchin'} ne 'alc') {
10203:                 $forcenewuser = 1;
10204:                 my $cansrchinst = 0; 
10205:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
10206:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
10207:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
10208:                         if ($domconfig{'directorysrch'}{'available'}) {
10209:                             $cansrchinst = 1;
10210:                         } 
10211:                     }
10212:                 }
10213:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
10214:                      ($srch->{'srchby'} eq 'lastname')) &&
10215:                     ($srch->{'srchin'} eq 'dom')) {
10216:                     if ($cansrchinst) {
10217:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
10218:                     }
10219:                 }
10220:                 if ($srch->{'srchin'} eq 'crs') {
10221:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
10222:                 }
10223:             }
10224:             my $createdom = $env{'request.role.domain'};
10225:             if ($context eq 'requestcrs') {
10226:                 if ($env{'form.coursedom'} ne '') {
10227:                     $createdom = $env{'form.coursedom'};
10228:                 }
10229:             }
10230:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
10231:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
10232:                 my $cancreate =
10233:                     &Apache::lonuserutils::can_create_user($createdom,$context);
10234:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
10235:                 if ($cancreate) {
10236:                     my $showdom = &display_domain_info($createdom); 
10237:                     $response .= '<br /><br />'
10238:                                 .'<b>'.&mt('To add a new user:').'</b>'
10239:                                 .'<br />';
10240:                     if ($context eq 'requestcrs') {
10241:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
10242:                     } else {
10243:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
10244:                     }
10245:                     $response .='<ul><li>'
10246:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
10247:                                 .'</li><li>'
10248:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
10249:                                 .'</li><li>'
10250:                                 .&mt('Provide the proposed username')
10251:                                 .'</li><li>'
10252:                                 .&mt("Click 'Search'")
10253:                                 .'</li></ul><br />';
10254:                 } else {
10255:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
10256:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
10257:                         $response .= '<br /><br />';
10258:                         if ($context eq 'requestcrs') {
10259:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
10260:                         } else {
10261:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
10262:                         }
10263:                         $response .= '<br />'
10264:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
10265:                                         ,' <a'.$helplink.'>'
10266:                                         ,'</a>')
10267:                                      .'<br />';
10268:                     }
10269:                 }
10270:             }
10271:         }
10272:     }
10273:     return ($currstate,$response,$forcenewuser);
10274: }
10275: 
10276: sub display_domain_info {
10277:     my ($dom) = @_;
10278:     my $output = $dom;
10279:     if ($dom ne '') { 
10280:         my $domdesc = &Apache::lonnet::domain($dom,'description');
10281:         if ($domdesc ne '') {
10282:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
10283:         }
10284:     }
10285:     return $output;
10286: }
10287: 
10288: sub crumb_utilities {
10289:     my %elements = (
10290:        crtuser => {
10291:            srchterm => 'text',
10292:            srchin => 'selectbox',
10293:            srchby => 'selectbox',
10294:            srchtype => 'selectbox',
10295:            srchdomain => 'selectbox',
10296:        },
10297:        crtusername => {
10298:            srchterm => 'text',
10299:            srchdomain => 'selectbox',
10300:        },
10301:        docustom => {
10302:            rolename => 'selectbox',
10303:            newrolename => 'textbox',
10304:        },
10305:        studentform => {
10306:            srchterm => 'text',
10307:            srchin => 'selectbox',
10308:            srchby => 'selectbox',
10309:            srchtype => 'selectbox',
10310:            srchdomain => 'selectbox',
10311:        },
10312:     );
10313: 
10314:     my $jsback .= qq|
10315: function backPage(formname,prevphase,prevstate) {
10316:     if (typeof prevphase == 'undefined') {
10317:         formname.phase.value = '';
10318:     }
10319:     else {  
10320:         formname.phase.value = prevphase;
10321:     }
10322:     if (typeof prevstate == 'undefined') {
10323:         formname.currstate.value = '';
10324:     }
10325:     else {
10326:         formname.currstate.value = prevstate;
10327:     }
10328:     formname.submit();
10329: }
10330: |;
10331:     return ($jsback,\%elements);
10332: }
10333: 
10334: sub course_level_table {
10335:     my ($inccourses,$showcredits,$defaultcredits) = @_;
10336:     return unless (ref($inccourses) eq 'HASH');
10337:     my $table = '';
10338: # Custom Roles?
10339: 
10340:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10341:     my %lt=&Apache::lonlocal::texthash(
10342:             'exs'  => "Existing sections",
10343:             'new'  => "Define new section",
10344:             'ssd'  => "Set Start Date",
10345:             'sed'  => "Set End Date",
10346:             'crl'  => "Course Level",
10347:             'act'  => "Activate",
10348:             'rol'  => "Role",
10349:             'ext'  => "Extent",
10350:             'grs'  => "Section",
10351:             'crd'  => "Credits",
10352:             'sta'  => "Start",
10353:             'end'  => "End"
10354:     );
10355: 
10356:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
10357: 	my $thiscourse=$protectedcourse;
10358: 	$thiscourse=~s:_:/:g;
10359: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
10360:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
10361: 	my $area=$coursedata{'description'};
10362:         my $crstype=$coursedata{'type'};
10363: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
10364: 	my ($domain,$cnum)=split(/\//,$thiscourse);
10365:         my %sections_count;
10366:         if (defined($env{'request.course.id'})) {
10367:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
10368:                 %sections_count = 
10369: 		    &Apache::loncommon::get_sections($domain,$cnum);
10370:             }
10371:         }
10372:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
10373: 	foreach my $role (@roles) {
10374:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
10375: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
10376:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
10377:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10378:                                             $plrole,\%sections_count,\%lt,
10379:                                             $showcredits,$defaultcredits,$crstype);
10380:             } elsif ($env{'request.course.sec'} ne '') {
10381:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
10382:                                              $env{'request.course.sec'})) {
10383:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10384:                                                 $plrole,\%sections_count,\%lt,
10385:                                                 $showcredits,$defaultcredits,$crstype);
10386:                 }
10387:             }
10388:         }
10389:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
10390:             foreach my $cust (sort(keys(%customroles))) {
10391:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
10392:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
10393:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
10394:                                             $cust,\%sections_count,\%lt,
10395:                                             $showcredits,$defaultcredits,$crstype);
10396:             }
10397: 	}
10398:     }
10399:     return '' if ($table eq ''); # return nothing if there is nothing 
10400:                                  # in the table
10401:     my $result;
10402:     if (!$env{'request.course.id'}) {
10403:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
10404:     }
10405:     $result .= 
10406: &Apache::loncommon::start_data_table().
10407: &Apache::loncommon::start_data_table_header_row().
10408: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10409: '<th>'.$lt{'ext'}.'</th><th>'."\n";
10410:     if ($showcredits) {
10411:         $result .= $lt{'crd'}.'</th>';
10412:     }
10413:     $result .=
10414: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
10415: '<th>'.$lt{'end'}.'</th>'.
10416: &Apache::loncommon::end_data_table_header_row().
10417: $table.
10418: &Apache::loncommon::end_data_table();
10419:     return $result;
10420: }
10421: 
10422: sub course_level_row {
10423:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
10424:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
10425:     my $creditem;
10426:     my $row = &Apache::loncommon::start_data_table_row().
10427:               ' <td><input type="checkbox" name="act_'.
10428:               $protectedcourse.'_'.$role.'" /></td>'."\n".
10429:               ' <td>'.$plrole.'</td>'."\n".
10430:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
10431:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
10432:         $row .= 
10433:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
10434:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
10435:     } else {
10436:         $row .= '<td>&nbsp;</td>';
10437:     }
10438:     if (($role eq 'cc') || ($role eq 'co')) {
10439:         $row .= '<td>&nbsp;</td>';
10440:     } elsif ($env{'request.course.sec'} ne '') {
10441:         $row .= ' <td><input type="hidden" value="'.
10442:                 $env{'request.course.sec'}.'" '.
10443:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
10444:                 $env{'request.course.sec'}.'</td>';
10445:     } else {
10446:         if (ref($sections_count) eq 'HASH') {
10447:             my $currsec = 
10448:                 &Apache::lonuserutils::course_sections($sections_count,
10449:                                                        $protectedcourse.'_'.$role);
10450:             $row .= '<td><table class="LC_createuser">'."\n".
10451:                     '<tr class="LC_section_row">'."\n".
10452:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
10453:                        $currsec.'</td>'."\n".
10454:                      ' <td>&nbsp;&nbsp;</td>'."\n".
10455:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
10456:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
10457:                      '" value="" />'.
10458:                      '<input type="hidden" '.
10459:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
10460:                      '</tr></table></td>'."\n";
10461:         } else {
10462:             $row .= '<td><input type="text" size="10" '.
10463:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
10464:         }
10465:     }
10466:     $row .= <<ENDTIMEENTRY;
10467: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
10468: <a href=
10469: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
10470: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
10471: <a href=
10472: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
10473: ENDTIMEENTRY
10474:     $row .= &Apache::loncommon::end_data_table_row();
10475:     return $row;
10476: }
10477: 
10478: sub course_level_dc {
10479:     my ($dcdom,$showcredits) = @_;
10480:     my %customroles=&Apache::lonuserutils::my_custom_roles();
10481:     my @roles = &Apache::lonuserutils::roles_by_context('course');
10482:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
10483:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
10484:                       '<input type="hidden" name="dccourse" value="" />';
10485:     my $courseform=&Apache::loncommon::selectcourse_link
10486:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
10487:     my $credit_elem;
10488:     if ($showcredits) {
10489:         $credit_elem = 'credits';
10490:     }
10491:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
10492:     my %lt=&Apache::lonlocal::texthash(
10493:                     'rol'  => "Role",
10494:                     'grs'  => "Section",
10495:                     'exs'  => "Existing sections",
10496:                     'new'  => "Define new section", 
10497:                     'sta'  => "Start",
10498:                     'end'  => "End",
10499:                     'ssd'  => "Set Start Date",
10500:                     'sed'  => "Set End Date",
10501:                     'scc'  => "Course/Community",
10502:                     'crd'  => "Credits",
10503:                   );
10504:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
10505:                  &Apache::loncommon::start_data_table().
10506:                  &Apache::loncommon::start_data_table_header_row().
10507:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
10508:                  '<th>'.$lt{'grs'}.'</th>'."\n";
10509:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
10510:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
10511:                  &Apache::loncommon::end_data_table_header_row();
10512:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
10513:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
10514:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
10515:                      '<td valign="top"><br /><select name="role">'."\n";
10516:     foreach my $role (@roles) {
10517:         my $plrole=&Apache::lonnet::plaintext($role);
10518:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
10519:     }
10520:     if ( keys(%customroles) > 0) {
10521:         foreach my $cust (sort(keys(%customroles))) {
10522:             my $custrole='cr_cr_'.$env{'user.domain'}.
10523:                     '_'.$env{'user.name'}.'_'.$cust;
10524:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
10525:         }
10526:     }
10527:     $otheritems .= '</select></td><td>'.
10528:                      '<table border="0" cellspacing="0" cellpadding="0">'.
10529:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
10530:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
10531:                      '<td>&nbsp;&nbsp;</td>'.
10532:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
10533:                      '<input type="text" name="newsec" value="" />'.
10534:                      '<input type="hidden" name="section" value="" />'.
10535:                      '<input type="hidden" name="groups" value="" />'.
10536:                      '<input type="hidden" name="crstype" value="" /></td>'.
10537:                      '</tr></table></td>'."\n";
10538:     if ($showcredits) {
10539:         $otheritems .= '<td><br />'."\n".
10540:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
10541:     }
10542:     $otheritems .= <<ENDTIMEENTRY;
10543: <td><br /><input type="hidden" name="start" value='' />
10544: <a href=
10545: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
10546: <td><br /><input type="hidden" name="end" value='' />
10547: <a href=
10548: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
10549: ENDTIMEENTRY
10550:     $otheritems .= &Apache::loncommon::end_data_table_row().
10551:                    &Apache::loncommon::end_data_table()."\n";
10552:     return $cb_jscript.$hiddenitems.$header.$otheritems;
10553: }
10554: 
10555: sub update_selfenroll_config {
10556:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
10557:     return unless (ref($currsettings) eq 'HASH');
10558:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
10559:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10560:     my (%changes,%warning);
10561:     my $curr_types;
10562:     my %noedit;
10563:     unless ($context eq 'domain') {
10564:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
10565:     }
10566:     if (ref($row) eq 'ARRAY') {
10567:         foreach my $item (@{$row}) {
10568:             next if ($noedit{$item});
10569:             if ($item eq 'enroll_dates') {
10570:                 my (%currenrolldate,%newenrolldate);
10571:                 foreach my $type ('start','end') {
10572:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
10573:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
10574:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
10575:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
10576:                     }
10577:                 }
10578:             } elsif ($item eq 'access_dates') {
10579:                 my (%currdate,%newdate);
10580:                 foreach my $type ('start','end') {
10581:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
10582:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
10583:                     if ($newdate{$type} ne $currdate{$type}) {
10584:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
10585:                     }
10586:                 }
10587:             } elsif ($item eq 'types') {
10588:                 $curr_types = $currsettings->{'selfenroll_'.$item};
10589:                 if ($env{'form.selfenroll_all'}) {
10590:                     if ($curr_types ne '*') {
10591:                         $changes{'internal.selfenroll_types'} = '*';
10592:                     } else {
10593:                         next;
10594:                     }
10595:                 } else {
10596:                     my %currdoms;
10597:                     my @entries = split(/;/,$curr_types);
10598:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
10599:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
10600:                     my $newnum = 0;
10601:                     my @latesttypes;
10602:                     foreach my $num (@activations) {
10603:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
10604:                         if (@types > 0) {
10605:                             @types = sort(@types);
10606:                             my $typestr = join(',',@types);
10607:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
10608:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10609:                             $currdoms{$typedom} = 1;
10610:                             $newnum ++;
10611:                         }
10612:                     }
10613:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
10614:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
10615:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
10616:                             if (@types > 0) {
10617:                                 @types = sort(@types);
10618:                                 my $typestr = join(',',@types);
10619:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
10620:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
10621:                                 $currdoms{$typedom} = 1;
10622:                                 $newnum ++;
10623:                             }
10624:                         }
10625:                     }
10626:                     if ($env{'form.selfenroll_newdom'} ne '') {
10627:                         my $typedom = $env{'form.selfenroll_newdom'};
10628:                         if ((!defined($currdoms{$typedom})) && 
10629:                             (&Apache::lonnet::domain($typedom) ne '')) {
10630:                             my $typestr;
10631:                             my ($othertitle,$usertypes,$types) = 
10632:                                 &Apache::loncommon::sorted_inst_types($typedom);
10633:                             my $othervalue = 'any';
10634:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
10635:                                 if (@{$types} > 0) {
10636:                                     my @esc_types = map { &escape($_); } @{$types};
10637:                                     $othervalue = 'other';
10638:                                     $typestr = join(',',(@esc_types,$othervalue));
10639:                                 }
10640:                                 $typestr = $othervalue;
10641:                             } else {
10642:                                 $typestr = $othervalue;
10643:                             } 
10644:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
10645:                             $newnum ++ ;
10646:                         }
10647:                     }
10648:                     my $selfenroll_types = join(';',@latesttypes);
10649:                     if ($selfenroll_types ne $curr_types) {
10650:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
10651:                     }
10652:                 }
10653:             } elsif ($item eq 'limit') {
10654:                 my $newlimit = $env{'form.selfenroll_limit'};
10655:                 my $newcap = $env{'form.selfenroll_cap'};
10656:                 $newcap =~s/\s+//g;
10657:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10658:                 $currlimit = 'none' if ($currlimit eq '');
10659:                 my $currcap = $currsettings->{'selfenroll_cap'};
10660:                 if ($newlimit ne $currlimit) {
10661:                     if ($newlimit ne 'none') {
10662:                         if ($newcap =~ /^\d+$/) {
10663:                             if ($newcap ne $currcap) {
10664:                                 $changes{'internal.selfenroll_cap'} = $newcap;
10665:                             }
10666:                             $changes{'internal.selfenroll_limit'} = $newlimit;
10667:                         } else {
10668:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10669:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
10670:                         }
10671:                     } elsif ($currcap ne '') {
10672:                         $changes{'internal.selfenroll_cap'} = '';
10673:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
10674:                     }
10675:                 } elsif ($currlimit ne 'none') {
10676:                     if ($newcap =~ /^\d+$/) {
10677:                         if ($newcap ne $currcap) {
10678:                             $changes{'internal.selfenroll_cap'} = $newcap;
10679:                         }
10680:                     } else {
10681:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
10682:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
10683:                     }
10684:                 }
10685:             } elsif ($item eq 'approval') {
10686:                 my (@currnotified,@newnotified);
10687:                 my $currapproval = $currsettings->{'selfenroll_approval'};
10688:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
10689:                 if ($currnotifylist ne '') {
10690:                     @currnotified = split(/,/,$currnotifylist);
10691:                     @currnotified = sort(@currnotified);
10692:                 }
10693:                 my $newapproval = $env{'form.selfenroll_approval'};
10694:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
10695:                 @newnotified = sort(@newnotified);
10696:                 if ($newapproval ne $currapproval) {
10697:                     $changes{'internal.selfenroll_approval'} = $newapproval;
10698:                     if (!$newapproval) {
10699:                         if ($currnotifylist ne '') {
10700:                             $changes{'internal.selfenroll_notifylist'} = '';
10701:                         }
10702:                     } else {
10703:                         my @differences =  
10704:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10705:                         if (@differences > 0) {
10706:                             if (@newnotified > 0) {
10707:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10708:                             } else {
10709:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10710:                             }
10711:                         }
10712:                     }
10713:                 } else {
10714:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
10715:                     if (@differences > 0) {
10716:                         if (@newnotified > 0) {
10717:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
10718:                         } else {
10719:                             $changes{'internal.selfenroll_notifylist'} = '';
10720:                         }
10721:                     }
10722:                 }
10723:             } else {
10724:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
10725:                 my $newval = $env{'form.selfenroll_'.$item};
10726:                 if ($item eq 'section') {
10727:                     $newval = $env{'form.sections'};
10728:                     if (defined($curr_groups{$newval})) {
10729:                         $newval = $curr_val;
10730:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
10731:                                           &mt('Group names and section names must be distinct');
10732:                     } elsif ($newval eq 'all') {
10733:                         $newval = $curr_val;
10734:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
10735:                     }
10736:                     if ($newval eq '') {
10737:                         $newval = 'none';
10738:                     }
10739:                 }
10740:                 if ($newval ne $curr_val) {
10741:                     $changes{'internal.selfenroll_'.$item} = $newval;
10742:                 }
10743:             }
10744:         }
10745:         if (keys(%warning) > 0) {
10746:             foreach my $item (@{$row}) {
10747:                 if (exists($warning{$item})) {
10748:                     $r->print($warning{$item}.'<br />');
10749:                 }
10750:             } 
10751:         }
10752:         if (keys(%changes) > 0) {
10753:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
10754:             if ($putresult eq 'ok') {
10755:                 if ((exists($changes{'internal.selfenroll_types'})) ||
10756:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
10757:                     (exists($changes{'internal.selfenroll_end_date'}))) {
10758:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
10759:                                                                 $cnum,undef,undef,'Course');
10760:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
10761:                     if (ref($crsinfo{$cid}) eq 'HASH') {
10762:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
10763:                             if (exists($changes{'internal.'.$item})) {
10764:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
10765:                             }
10766:                         }
10767:                         my $crsputresult =
10768:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
10769:                                                          $chome,'notime');
10770:                     }
10771:                 }
10772:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
10773:                 foreach my $item (@{$row}) {
10774:                     my $title = $item;
10775:                     if (ref($lt) eq 'HASH') {
10776:                         $title = $lt->{$item};
10777:                     }
10778:                     if ($item eq 'enroll_dates') {
10779:                         foreach my $type ('start','end') {
10780:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
10781:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
10782:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10783:                                           $title,$type,$newdate).'</li>');
10784:                             }
10785:                         }
10786:                     } elsif ($item eq 'access_dates') {
10787:                         foreach my $type ('start','end') {
10788:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
10789:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
10790:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
10791:                                           $title,$type,$newdate).'</li>');
10792:                             }
10793:                         }
10794:                     } elsif ($item eq 'limit') {
10795:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
10796:                             (exists($changes{'internal.selfenroll_cap'}))) {
10797:                             my ($newval,$newcap);
10798:                             if ($changes{'internal.selfenroll_cap'} ne '') {
10799:                                 $newcap = $changes{'internal.selfenroll_cap'}
10800:                             } else {
10801:                                 $newcap = $currsettings->{'selfenroll_cap'};
10802:                             }
10803:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
10804:                                 $newval = &mt('No limit');
10805:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
10806:                                      'allstudents') {
10807:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10808:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10809:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10810:                             } else {
10811:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
10812:                                 if ($currlimit eq 'allstudents') {
10813:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
10814:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
10815:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
10816:                                 }
10817:                             }
10818:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10819:                         }
10820:                     } elsif ($item eq 'approval') {
10821:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
10822:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
10823:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
10824:                             my ($newval,$newnotify);
10825:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
10826:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
10827:                             } else {   
10828:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
10829:                             }
10830:                             if (exists($changes{'internal.selfenroll_approval'})) {
10831:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
10832:                                     $changes{'internal.selfenroll_approval'} = '0';
10833:                                 }
10834:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
10835:                             } else {
10836:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
10837:                                 if ($currapproval !~ /^[012]$/) {
10838:                                     $currapproval = 0;
10839:                                 }
10840:                                 $newval = $selfdescs{'approval'}{$currapproval};
10841:                             }
10842:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
10843:                             if ($newnotify) {
10844:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
10845:                             } else {
10846:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
10847:                             }
10848:                             $r->print('</li>'."\n");
10849:                         }
10850:                     } else {
10851:                         if (exists($changes{'internal.selfenroll_'.$item})) {
10852:                             my $newval = $changes{'internal.selfenroll_'.$item};
10853:                             if ($item eq 'types') {
10854:                                 if ($newval eq '') {
10855:                                     $newval = &mt('None');
10856:                                 } elsif ($newval eq '*') {
10857:                                     $newval = &mt('Any user in any domain');
10858:                                 }
10859:                             } elsif ($item eq 'registered') {
10860:                                 if ($newval eq '1') {
10861:                                     $newval = &mt('Yes');
10862:                                 } elsif ($newval eq '0') {
10863:                                     $newval = &mt('No');
10864:                                 }
10865:                             }
10866:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
10867:                         }
10868:                     }
10869:                 }
10870:                 $r->print('</ul>');
10871:                 if ($env{'course.'.$cid.'.description'} ne '') {
10872:                     my %newenvhash;
10873:                     foreach my $key (keys(%changes)) {
10874:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
10875:                     }
10876:                     &Apache::lonnet::appenv(\%newenvhash);
10877:                 }
10878:             } else {
10879:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
10880:                           &mt('The error was: [_1].',$putresult));
10881:             }
10882:         } else {
10883:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10884:         }
10885:     } else {
10886:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
10887:     }
10888:     my $visactions = &cat_visibility($cdom);
10889:     my ($cathash,%cattype);
10890:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
10891:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10892:         $cathash = $domconfig{'coursecategories'}{'cats'};
10893:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
10894:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
10895:     } else {
10896:         $cathash = {};
10897:         $cattype{'auth'} = 'std';
10898:         $cattype{'unauth'} = 'std';
10899:     }
10900:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
10901:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10902:                   '<br />'.
10903:                   '<br />'.$visactions->{'take'}.'<ul>'.
10904:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
10905:                   '</ul>');
10906:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
10907:         if ($currsettings->{'uniquecode'}) {
10908:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
10909:         } else {
10910:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10911:                   '<br />'.
10912:                   '<br />'.$visactions->{'take'}.'<ul>'.
10913:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
10914:                   '</ul><br />');
10915:         }
10916:     } else {
10917:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
10918:         if (ref($visactions) eq 'HASH') {
10919:             if (!$visible) {
10920:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
10921:                           '<br />');
10922:                 if (ref($vismsgs) eq 'ARRAY') {
10923:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
10924:                     foreach my $item (@{$vismsgs}) {
10925:                         $r->print('<li>'.$visactions->{$item}.'</li>');
10926:                     }
10927:                     $r->print('</ul>');
10928:                 }
10929:                 $r->print($cansetvis);
10930:             }
10931:         }
10932:     } 
10933:     return;
10934: }
10935: 
10936: #---------------------------------------------- end functions for &phase_two
10937: 
10938: #--------------------------------- functions for &phase_two and &phase_three
10939: 
10940: #--------------------------end of functions for &phase_two and &phase_three
10941: 
10942: 1;
10943: __END__
10944: 
10945: 

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