File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.160.6.118.2.14: download - view: text, annotated - select for diffs
Wed Jul 5 17:08:22 2023 UTC (11 months, 1 week ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in 1.267 (part), 1.320, 1.321, 1.325, 1.326, 1.337, 1.351,
  1.363, 1.384, 1.390, 1.391, 1.392, 1.405, 1.419, 1.420, 1.421, 1.422, 1.423,
  1.424, 1.425, 1.426 (part)

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.160.6.118.2.14 2023/07/05 17:08:22 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: ###############################################################
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::domainprefs.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40: Handles configuration of a LON-CAPA domain.  
   41: 
   42: This is part of the LearningOnline Network with CAPA project
   43: described at http://www.lon-capa.org.
   44: 
   45: 
   46: =head1 OVERVIEW
   47: 
   48: Each institution using LON-CAPA will typically have a single domain designated 
   49: for use by individuals affiliated with the institution.  Accordingly, each domain
   50: may define a default set of logos and a color scheme which can be used to "brand"
   51: the LON-CAPA instance. In addition, an institution will typically have a language
   52: and timezone which are used for the majority of courses.
   53: 
   54: LON-CAPA provides a mechanism to display and modify these defaults, as well as a 
   55: host of other domain-wide settings which determine the types of functionality
   56: available to users and courses in the domain.
   57: 
   58: There is also a mechanism to configure cataloging of courses in the domain, and
   59: controls on the operation of automated processes which govern such things as
   60: roster updates, user directory updates and processing of course requests.
   61: 
   62: The domain coordination manual which is built dynamically on install/update of 
   63: LON-CAPA from the relevant help items provides more information about domain 
   64: configuration.
   65: 
   66: Most of the domain settings are stored in the configuration.db GDBM file which is
   67: housed on the primary library server for the domain in /home/httpd/lonUsers/$dom,
   68: where $dom is the domain.  The configuration.db stores settings in a number of 
   69: frozen hashes of hashes.  In a few cases, domain information must be uploaded to
   70: the domain as files (e.g., image files for logos etc., or plain text files for
   71: bubblesheet formats).  In this case the domainprefs.pm must be running in a user
   72: session hosted on the primary library server in the domain, as these files are 
   73: stored in author space belonging to a special $dom-domainconfig user.   
   74: 
   75: domainprefs.pm in combination with lonconfigsettings.pm will retrieve and display
   76: the current settings, and provides an interface to make modifications.
   77: 
   78: =head1 SUBROUTINES
   79: 
   80: =over
   81: 
   82: =item print_quotas()
   83: 
   84: Inputs: 4 
   85: 
   86: $dom,$settings,$rowtotal,$action.
   87: 
   88: $dom is the domain, $settings is a reference to a hash of current settings for
   89: the current context, $rowtotal is a reference to the scalar used to record the 
   90: number of rows displayed on the page, and $action is the context (quotas, 
   91: requestcourses or requestauthor).
   92: 
   93: The print_quotas routine was orginally created to display/store information
   94: about default quota sizes for portfolio spaces for the different types of 
   95: institutional affiliation in the domain (e.g., Faculty, Staff, Student etc.), 
   96: but is now also used to manage availability of user tools: 
   97: i.e., blogs, aboutme page, and portfolios, and the course request tool,
   98: used by course owners to request creation of a course, and to display/store
   99: default quota sizes for Authoring Spaces.
  100: 
  101: Outputs: 1
  102: 
  103: $datatable  - HTML containing form elements which allow settings to be changed. 
  104: 
  105: In the case of course requests, radio buttons are displayed for each institutional
  106: affiliate type (and also default, and _LC_adv) for each of the course types 
  107: (official, unofficial, community, textbook, and lti).
  108: In each case the radio buttons allow the selection of one of four values:
  109: 
  110: 0, approval, validate, autolimit=N (where N is blank, or a positive integer).
  111: which have the following effects:
  112: 
  113: 0
  114: 
  115: =over
  116: 
  117: - course requests are not allowed for this course types/affiliation
  118: 
  119: =back
  120: 
  121: approval 
  122: 
  123: =over 
  124: 
  125: - course requests must be approved by a Doman Coordinator in the 
  126: course's domain
  127: 
  128: =back
  129: 
  130: validate 
  131: 
  132: =over
  133: 
  134: - an institutional validation (e.g., check requestor is instructor
  135: of record) needs to be passed before the course will be created.  The required
  136: validation is in localenroll.pm on the primary library server for the course 
  137: domain.
  138: 
  139: =back
  140: 
  141: autolimit 
  142: 
  143: =over
  144:  
  145: - course requests will be processed automatically up to a limit of
  146: N requests for the course type for the particular requestor.
  147: If N is undefined, there is no limit to the number of course requests
  148: which a course owner may submit and have processed automatically. 
  149: 
  150: =back
  151: 
  152: =item modify_quotas() 
  153: 
  154: =back
  155: 
  156: =cut
  157: 
  158: package Apache::domainprefs;
  159: 
  160: use strict;
  161: use Apache::Constants qw(:common :http);
  162: use Apache::lonnet;
  163: use Apache::loncommon();
  164: use Apache::lonhtmlcommon();
  165: use Apache::lonlocal;
  166: use Apache::lonmsg();
  167: use Apache::lonconfigsettings;
  168: use Apache::lonuserutils();
  169: use Apache::loncoursequeueadmin();
  170: use Apache::courseprefs();
  171: use LONCAPA qw(:DEFAULT :match);
  172: use LONCAPA::Enrollment;
  173: use LONCAPA::lonauthcgi();
  174: use File::Copy;
  175: use Locale::Language;
  176: use DateTime::TimeZone;
  177: use DateTime::Locale;
  178: use Time::HiRes qw( sleep );
  179: use Net::CIDR;
  180: use Crypt::CBC;
  181: 
  182: my $registered_cleanup;
  183: my $modified_urls;
  184: 
  185: sub handler {
  186:     my $r=shift;
  187:     if ($r->header_only) {
  188:         &Apache::loncommon::content_type($r,'text/html');
  189:         $r->send_http_header;
  190:         return OK;
  191:     }
  192: 
  193:     my $context = 'domain';
  194:     my $dom = $env{'request.role.domain'};
  195:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  196:     if (&Apache::lonnet::allowed('mau',$dom)) {
  197:         &Apache::loncommon::content_type($r,'text/html');
  198:         $r->send_http_header;
  199:     } else {
  200:         $env{'user.error.msg'}=
  201:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  202:         return HTTP_NOT_ACCEPTABLE;
  203:     }
  204: 
  205:     $registered_cleanup=0;
  206:     @{$modified_urls}=();
  207: 
  208:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  209:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  210:                                             ['phase','actions']);
  211:     my $phase = 'pickactions';
  212:     if ( exists($env{'form.phase'}) ) {
  213:         $phase = $env{'form.phase'};
  214:     }
  215:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  216:     my %domconfig =
  217:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  218:                 'quotas','autoenroll','autoupdate','autocreate',
  219:                 'directorysrch','usercreation','usermodification',
  220:                 'contacts','defaults','scantron','coursecategories',
  221:                 'serverstatuses','requestcourses','helpsettings',
  222:                 'coursedefaults','usersessions','loadbalancing',
  223:                 'requestauthor','selfenrollment','inststatus',
  224:                 'passwords','ltitools','toolsec','lti','ltisec',
  225:                 'wafproxy','ipaccess'],$dom);
  226:     my %encconfig =
  227:         &Apache::lonnet::get_dom('encconfig',['ltitools','lti','linkprot'],$dom,undef,1);
  228:     my ($checked_is_home,$is_home);
  229:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  230:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  231:             my $home = &Apache::lonnet::domain($dom,'primary');
  232:             unless (($home eq 'no_host') || ($home eq '')) {
  233:                 my @ids=&Apache::lonnet::current_machine_ids();
  234:                 if (grep(/^\Q$home\E$/,@ids)) {
  235:                     $is_home = 1;
  236:                 }
  237:             }
  238:             $checked_is_home = 1;
  239:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  240:                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
  241:                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
  242:                     $domconfig{'ltitools'}{$id}{'key'} = $encconfig{'ltitools'}{$id}{'key'};
  243:                     if (($is_home) && ($phase eq 'process')) {
  244:                         $domconfig{'ltitools'}{$id}{'secret'} = $encconfig{'ltitools'}{$id}{'secret'};
  245:                     }
  246:                 }
  247:             }
  248:         }
  249:     }
  250:     if (ref($domconfig{'lti'}) eq 'HASH') {
  251:         if (ref($encconfig{'lti'}) eq 'HASH') {
  252:             unless ($checked_is_home) {
  253:                 my $home = &Apache::lonnet::domain($dom,'primary');
  254:                 unless (($home eq 'no_host') || ($home eq '')) {
  255:                     my @ids=&Apache::lonnet::current_machine_ids();
  256:                     if (grep(/^\Q$home\E$/,@ids)) {
  257:                         $is_home = 1;
  258:                     }
  259:                 }
  260:                 $checked_is_home = 1;
  261:             }
  262:             foreach my $id (keys(%{$domconfig{'lti'}})) {
  263:                 if ((ref($domconfig{'lti'}{$id}) eq 'HASH') &&
  264:                     (ref($encconfig{'lti'}{$id}) eq 'HASH')) {
  265:                     $domconfig{'lti'}{$id}{'key'} = $encconfig{'lti'}{$id}{'key'};
  266:                     if (($is_home) && ($phase eq 'process')) {
  267:                         $domconfig{'lti'}{$id}{'secret'} = $encconfig{'lti'}{$id}{'secret'};
  268:                     }
  269:                 }
  270:             }
  271:         }
  272:     }
  273:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
  274:         if (ref($domconfig{'ltisec'}{'linkprot'}) eq 'HASH') {
  275:             if (ref($encconfig{'linkprot'}) eq 'HASH') {
  276:                 foreach my $id (keys(%{$domconfig{'ltisec'}{'linkprot'}})) {
  277:                     unless ($id =~ /^\d+$/) {
  278:                         delete($domconfig{'ltisec'}{'linkprot'}{$id});
  279:                     }
  280:                     if ((ref($domconfig{'ltisec'}{'linkprot'}{$id}) eq 'HASH') &&
  281:                         (ref($encconfig{'linkprot'}{$id}) eq 'HASH')) {
  282:                         foreach my $item ('key','secret') {
  283:                             $domconfig{'ltisec'}{'linkprot'}{$id}{$item} = $encconfig{'linkprot'}{$id}{$item};
  284:                         }
  285:                     }
  286:                 }
  287:             }
  288:         }
  289:     }
  290:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  291:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  292:                        'contacts','usercreation','selfcreation','usermodification',
  293:                        'scantron','requestcourses','requestauthor','coursecategories',
  294:                        'serverstatuses','helpsettings','coursedefaults',
  295:                        'ltitools','selfenrollment','usersessions','lti');
  296:     my %existing;
  297:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  298:         %existing = %{$domconfig{'loadbalancing'}};
  299:     }
  300:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  301:         push(@prefs_order,'loadbalancing');
  302:     }
  303:     my %prefs = (
  304:         'rolecolors' =>
  305:                    { text => 'Default color schemes',
  306:                      help => 'Domain_Configuration_Color_Schemes',
  307:                      header => [{col1 => 'Student Settings',
  308:                                  col2 => '',},
  309:                                 {col1 => 'Coordinator Settings',
  310:                                  col2 => '',},
  311:                                 {col1 => 'Author Settings',
  312:                                  col2 => '',},
  313:                                 {col1 => 'Administrator Settings',
  314:                                  col2 => '',}],
  315:                       print => \&print_rolecolors,
  316:                       modify => \&modify_rolecolors,
  317:                     },
  318:         'login' =>
  319:                     { text => 'Log-in page options',
  320:                       help => 'Domain_Configuration_Login_Page',
  321:                       header => [{col1 => 'Log-in Page Items',
  322:                                   col2 => '',},
  323:                                  {col1 => 'Log-in Help',
  324:                                   col2 => 'Value'},
  325:                                  {col1 => 'Custom HTML in document head',
  326:                                   col2 => 'Value'},
  327:                                  {col1 => 'SSO',
  328:                                   col2 => 'Dual login: SSO and non-SSO options'},
  329:                                 ],
  330:                       print => \&print_login,
  331:                       modify => \&modify_login,
  332:                     },
  333:         'defaults' => 
  334:                     { text => 'Default authentication/language/timezone/portal/types',
  335:                       help => 'Domain_Configuration_LangTZAuth',
  336:                       header => [{col1 => 'Setting',
  337:                                   col2 => 'Value'},
  338:                                  {col1 => 'Institutional user types',
  339:                                   col2 => 'Name displayed'},
  340:                                  {col1 => 'Mapping for missing usernames via standard log-in',
  341:                                   col2 => 'Rules in use'}],
  342:                       print => \&print_defaults,
  343:                       modify => \&modify_defaults,
  344:                     },
  345:         'wafproxy' =>
  346:                     { text => 'Web Application Firewall/Reverse Proxy',
  347:                       help => 'Domain_Configuration_WAF_Proxy',
  348:                       header => [{col1 => 'Domain(s)',
  349:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  350:                                  },
  351:                                  {col1 => 'Domain(s)',
  352:                                   col2 => 'WAF Configuration',}],
  353:                       print => \&print_wafproxy,
  354:                       modify => \&modify_wafproxy,
  355:                     },
  356:         'passwords' =>
  357:                     { text => 'Passwords (Internal authentication)',
  358:                       help => 'Domain_Configuration_Passwords',
  359:                       header => [{col1 => 'Resetting Forgotten Password',
  360:                                   col2 => 'Settings'},
  361:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  362:                                   col2 => 'Settings'},
  363:                                  {col1 => 'Rules for LON-CAPA Passwords',
  364:                                   col2 => 'Settings'},
  365:                                  {col1 => 'Course Owner Changing Student Passwords',
  366:                                   col2 => 'Settings'}],
  367:                       print => \&print_passwords,
  368:                       modify => \&modify_passwords,
  369:                     },
  370:         'quotas' => 
  371:                     { text => 'Blogs, personal pages/timezones, webDAV/quotas, portfolio',
  372:                       help => 'Domain_Configuration_Quotas',
  373:                       header => [{col1 => 'User affiliation',
  374:                                   col2 => 'Available tools',
  375:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  376:                       print => \&print_quotas,
  377:                       modify => \&modify_quotas,
  378:                     },
  379:         'autoenroll' =>
  380:                    { text => 'Auto-enrollment settings',
  381:                      help => 'Domain_Configuration_Auto_Enrollment',
  382:                      header => [{col1 => 'Configuration setting',
  383:                                  col2 => 'Value(s)'}],
  384:                      print => \&print_autoenroll,
  385:                      modify => \&modify_autoenroll,
  386:                    },
  387:         'autoupdate' => 
  388:                    { text => 'Auto-update settings',
  389:                      help => 'Domain_Configuration_Auto_Updates',
  390:                      header => [{col1 => 'Setting',
  391:                                  col2 => 'Value',},
  392:                                 {col1 => 'Setting',
  393:                                  col2 => 'Affiliation'},
  394:                                 {col1 => 'User population',
  395:                                  col2 => 'Updatable user data'}],
  396:                      print => \&print_autoupdate,
  397:                      modify => \&modify_autoupdate,
  398:                   },
  399:         'autocreate' => 
  400:                   { text => 'Auto-course creation settings',
  401:                      help => 'Domain_Configuration_Auto_Creation',
  402:                      header => [{col1 => 'Configuration Setting',
  403:                                  col2 => 'Value',}],
  404:                      print => \&print_autocreate,
  405:                      modify => \&modify_autocreate,
  406:                   },
  407:         'directorysrch' => 
  408:                   { text => 'Directory searches',
  409:                     help => 'Domain_Configuration_InstDirectory_Search',
  410:                     header => [{col1 => 'Institutional Directory Setting',
  411:                                 col2 => 'Value',},
  412:                                {col1 => 'LON-CAPA Directory Setting',
  413:                                 col2 => 'Value',}],
  414:                     print => \&print_directorysrch,
  415:                     modify => \&modify_directorysrch,
  416:                   },
  417:         'contacts' =>
  418:                   { text => 'E-mail addresses and helpform',
  419:                     help => 'Domain_Configuration_Contact_Info',
  420:                     header => [{col1 => 'Default e-mail addresses',
  421:                                 col2 => 'Value',},
  422:                                {col1 => 'Recipient(s) for notifications',
  423:                                 col2 => 'Value',},
  424:                                {col1 => 'Nightly status check e-mail',
  425:                                 col2 => 'Settings',},
  426:                                {col1 => 'Ask helpdesk form settings',
  427:                                 col2 => 'Value',},],
  428:                     print => \&print_contacts,
  429:                     modify => \&modify_contacts,
  430:                   },
  431:         'usercreation' => 
  432:                   { text => 'User creation',
  433:                     help => 'Domain_Configuration_User_Creation',
  434:                     header => [{col1 => 'Format rule type',
  435:                                 col2 => 'Format rules in force'},
  436:                                {col1 => 'User account creation',
  437:                                 col2 => 'Usernames which may be created',},
  438:                                {col1 => 'Context',
  439:                                 col2 => 'Assignable authentication types'}],
  440:                     print => \&print_usercreation,
  441:                     modify => \&modify_usercreation,
  442:                   },
  443:         'selfcreation' => 
  444:                   { text => 'Users self-creating accounts',
  445:                     help => 'Domain_Configuration_Self_Creation', 
  446:                     header => [{col1 => 'Self-creation with institutional username',
  447:                                 col2 => 'Enabled?'},
  448:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  449:                                 col2 => 'Information user can enter'},
  450:                                {col1 => 'Self-creation with e-mail verification',
  451:                                 col2 => 'Settings'}],
  452:                     print => \&print_selfcreation,
  453:                     modify => \&modify_selfcreation,
  454:                   },
  455:         'usermodification' =>
  456:                   { text => 'User modification',
  457:                     help => 'Domain_Configuration_User_Modification',
  458:                     header => [{col1 => 'Target user has role',
  459:                                 col2 => 'User information updatable in author context'},
  460:                                {col1 => 'Target user has role',
  461:                                 col2 => 'User information updatable in course context'}],
  462:                     print => \&print_usermodification,
  463:                     modify => \&modify_usermodification,
  464:                   },
  465:         'scantron' =>
  466:                   { text => 'Bubblesheet format',
  467:                     help => 'Domain_Configuration_Scantron_Format',
  468:                     header => [ {col1 => 'Bubblesheet format file',
  469:                                  col2 => ''},
  470:                                 {col1 => 'Bubblesheet data upload formats',
  471:                                  col2 => 'Settings'}],
  472:                     print => \&print_scantron,
  473:                     modify => \&modify_scantron,
  474:                   },
  475:         'requestcourses' => 
  476:                  {text => 'Request creation of courses',
  477:                   help => 'Domain_Configuration_Request_Courses',
  478:                   header => [{col1 => 'User affiliation',
  479:                               col2 => 'Availability/Processing of requests',},
  480:                              {col1 => 'Setting',
  481:                               col2 => 'Value'},
  482:                              {col1 => 'Available textbooks',
  483:                               col2 => ''},
  484:                              {col1 => 'Available templates',
  485:                               col2 => ''},
  486:                              {col1 => 'Validation (not official courses)',
  487:                               col2 => 'Value'},],
  488:                   print => \&print_quotas,
  489:                   modify => \&modify_quotas,
  490:                  },
  491:         'requestauthor' =>
  492:                  {text => 'Request Authoring Space',
  493:                   help => 'Domain_Configuration_Request_Author',
  494:                   header => [{col1 => 'User affiliation',
  495:                               col2 => 'Availability/Processing of requests',},
  496:                              {col1 => 'Setting',
  497:                               col2 => 'Value'}],
  498:                   print => \&print_quotas,
  499:                   modify => \&modify_quotas,
  500:                  },
  501:         'coursecategories' =>
  502:                   { text => 'Cataloging of courses/communities',
  503:                     help => 'Domain_Configuration_Cataloging_Courses',
  504:                     header => [{col1 => 'Catalog type/availability',
  505:                                 col2 => '',},
  506:                                {col1 => 'Category settings for standard catalog',
  507:                                 col2 => '',},
  508:                                {col1 => 'Categories',
  509:                                 col2 => '',
  510:                                }],
  511:                     print => \&print_coursecategories,
  512:                     modify => \&modify_coursecategories,
  513:                   },
  514:         'serverstatuses' =>
  515:                  {text   => 'Access to server status pages',
  516:                   help   => 'Domain_Configuration_Server_Status',
  517:                   header => [{col1 => 'Status Page',
  518:                               col2 => 'Other named users',
  519:                               col3 => 'Specific IPs',
  520:                             }],
  521:                   print => \&print_serverstatuses,
  522:                   modify => \&modify_serverstatuses,
  523:                  },
  524:         'helpsettings' =>
  525:                  {text   => 'Support settings',
  526:                   help   => 'Domain_Configuration_Help_Settings',
  527:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  528:                               col2 => 'Value'},
  529:                              {col1 => 'Helpdesk Roles',
  530:                               col2 => 'Settings'},],
  531:                   print  => \&print_helpsettings,
  532:                   modify => \&modify_helpsettings,
  533:                  },
  534:         'coursedefaults' => 
  535:                  {text => 'Course/Community defaults',
  536:                   help => 'Domain_Configuration_Course_Defaults',
  537:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  538:                               col2 => 'Value',},
  539:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  540:                               col2 => 'Value',},],
  541:                   print => \&print_coursedefaults,
  542:                   modify => \&modify_coursedefaults,
  543:                  },
  544:         'selfenrollment' => 
  545:                  {text   => 'Self-enrollment in Course/Community',
  546:                   help   => 'Domain_Configuration_Selfenrollment',
  547:                   header => [{col1 => 'Configuration Rights',
  548:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  549:                              {col1 => 'Defaults',
  550:                               col2 => 'Value'},
  551:                              {col1 => 'Self-enrollment validation (optional)',
  552:                               col2 => 'Value'},],
  553:                   print => \&print_selfenrollment,
  554:                   modify => \&modify_selfenrollment,
  555:                  },
  556:         'usersessions' =>
  557:                  {text  => 'User session hosting/offloading',
  558:                   help  => 'Domain_Configuration_User_Sessions',
  559:                   header => [{col1 => 'Domain server',
  560:                               col2 => 'Servers to offload sessions to when busy'},
  561:                              {col1 => 'Hosting of users from other domains',
  562:                               col2 => 'Rules'},
  563:                              {col1 => "Hosting domain's own users elsewhere",
  564:                               col2 => 'Rules'}],
  565:                   print => \&print_usersessions,
  566:                   modify => \&modify_usersessions,
  567:                  },
  568:         'loadbalancing' =>
  569:                  {text  => 'Dedicated Load Balancer(s)',
  570:                   help  => 'Domain_Configuration_Load_Balancing',
  571:                   header => [{col1 => 'Balancers',
  572:                               col2 => 'Default destinations',
  573:                               col3 => 'User affiliation',
  574:                               col4 => 'Overrides'},
  575:                             ],
  576:                   print => \&print_loadbalancing,
  577:                   modify => \&modify_loadbalancing,
  578:                  },
  579:         'ltitools' =>
  580:                  {text => 'External Tools (LTI)',
  581:                   help => 'Domain_Configuration_LTI_Tools',
  582:                   header => [{col1 => 'Encryption of shared secrets',
  583:                               col2 => 'Settings'},
  584:                              {col1 => 'Rules for shared secrets',
  585:                               col2 => 'Settings'},
  586:                              {col1 => 'Providers',
  587:                               col2 => 'Settings',}],
  588:                   print => \&print_ltitools,
  589:                   modify => \&modify_ltitools,
  590:                  },
  591:         'lti' =>
  592:                  {text => 'LTI Link Protection and LTI Consumers',
  593:                   help => 'Domain_Configuration_LTI_Provider',
  594:                   header => [{col1 => 'Encryption of shared secrets',
  595:                               col2 => 'Settings'},
  596:                              {col1 => 'Rules for shared secrets',
  597:                               col2 => 'Settings'},
  598:                              {col1 => 'Link Protectors',
  599:                               col2 => 'Settings'},
  600:                              {col1 => 'Consumers',
  601:                               col2 => 'Settings'},],
  602:                   print => \&print_lti,
  603:                   modify => \&modify_lti,
  604:                  },
  605:         'ipaccess' =>
  606:                        {text => 'IP-based access control',
  607:                         help => 'Domain_Configuration_IP_Access',
  608:                         header => [{col1 => 'Setting',
  609:                                     col2 => 'Value'},],
  610:                         print  => \&print_ipaccess,
  611:                         modify => \&modify_ipaccess,
  612:                        },
  613:     );
  614:     if (keys(%servers) > 1) {
  615:         $prefs{'login'}  = { text   => 'Log-in page options',
  616:                              help   => 'Domain_Configuration_Login_Page',
  617:                             header => [{col1 => 'Log-in Service',
  618:                                         col2 => 'Server Setting',},
  619:                                        {col1 => 'Log-in Page Items',
  620:                                         col2 => 'Settings'},
  621:                                        {col1 => 'Log-in Help',
  622:                                         col2 => 'Value'},
  623:                                        {col1 => 'Custom HTML in document head',
  624:                                         col2 => 'Value'},
  625:                                        {col1 => 'SSO',
  626:                                         col2 => 'Dual login: SSO and non-SSO options'},
  627:                                       ],
  628:                             print => \&print_login,
  629:                             modify => \&modify_login,
  630:                            };
  631:     }
  632: 
  633:     my @roles = ('student','coordinator','author','admin');
  634:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  635:     &Apache::lonhtmlcommon::add_breadcrumb
  636:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  637:       text=>"Settings to display/modify"});
  638:     my $confname = $dom.'-domainconfig';
  639: 
  640:     if ($phase eq 'process') {
  641:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  642:                                                               \%prefs,\%domconfig,$confname,\@roles);
  643:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  644:             $r->rflush();
  645:             &devalidate_remote_domconfs($dom,$result);
  646:         }
  647:     } elsif ($phase eq 'display') {
  648:         my $js = &recaptcha_js().
  649:                  &toggle_display_js();
  650:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  651:             my ($othertitle,$usertypes,$types) =
  652:                 &Apache::loncommon::sorted_inst_types($dom);
  653:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  654:                                           $domconfig{'loadbalancing'}).
  655:                    &new_spares_js().
  656:                    &common_domprefs_js().
  657:                    &Apache::loncommon::javascript_array_indexof();
  658:         }
  659:         if (grep(/^requestcourses$/,@actions)) {
  660:             my $javascript_validations;
  661:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  662:             $js .= <<END;
  663: <script type="text/javascript">
  664: $javascript_validations
  665: </script>
  666: $coursebrowserjs
  667: END
  668:         } elsif (grep(/^ipaccess$/,@actions)) {
  669:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  670:         }
  671:         if (grep(/^selfcreation$/,@actions)) {
  672:             $js .= &selfcreate_javascript();
  673:         }
  674:         if (grep(/^contacts$/,@actions)) {
  675:             $js .= &contacts_javascript();
  676:         }
  677:         if (grep(/^scantron$/,@actions)) {
  678:             $js .= &scantron_javascript();
  679:         }
  680:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  681:     } else {
  682: # check if domconfig user exists for the domain.
  683:         my $servadm = $r->dir_config('lonAdmEMail');
  684:         my ($configuserok,$author_ok,$switchserver) =
  685:             &config_check($dom,$confname,$servadm);
  686:         unless ($configuserok eq 'ok') {
  687:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  688:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  689:                           $confname).
  690:                       '<br />'
  691:             );
  692:             if ($switchserver) {
  693:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  694:                           '<br />'.
  695:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  696:                           '<br />'.
  697:                           &mt('The "[_1]" user can be created automatically when a Domain Coordinator visits the web-based "Set domain configuration" screen, in a session hosted on the primary library server.',$confname).
  698:                           '<br />'.
  699:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  700:                 );
  701:             } else {
  702:                 $r->print(&mt('To create that user from the command line run the ./UPDATE script found in the top level directory of the extracted LON-CAPA tarball.').
  703:                           '<br />'.
  704:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  705:                 );
  706:             }
  707:             $r->print(&Apache::loncommon::end_page());
  708:             return OK;
  709:         }
  710:         if (keys(%domconfig) == 0) {
  711:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  712:             my @ids=&Apache::lonnet::current_machine_ids();
  713:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  714:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  715:                 my @loginimages = ('img','logo','domlogo','login');
  716:                 my $custom_img_count = 0;
  717:                 foreach my $img (@loginimages) {
  718:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  719:                         $custom_img_count ++;
  720:                     }
  721:                 }
  722:                 foreach my $role (@roles) {
  723:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  724:                         $custom_img_count ++;
  725:                     }
  726:                 }
  727:                 if ($custom_img_count > 0) {
  728:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  729:                     my $switch_server = &check_switchserver($dom,$confname);
  730:                     $r->print(
  731:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  732:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  733:     &mt("Thereafter, (with a Domain Coordinator role selected in the domain) you will be able to update settings when logged in to any server in the LON-CAPA network.").'<br />'.
  734:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  735:                     if ($switch_server) {
  736:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  737:                     }
  738:                     $r->print(&Apache::loncommon::end_page());
  739:                     return OK;
  740:                 }
  741:             }
  742:         }
  743:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  744:     }
  745:     return OK;
  746: }
  747: 
  748: sub process_changes {
  749:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  750:     my %domconfig;
  751:     if (ref($values) eq 'HASH') {
  752:         %domconfig = %{$values};
  753:     }
  754:     my $output;
  755:     if ($action eq 'login') {
  756:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  757:     } elsif ($action eq 'rolecolors') {
  758:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  759:                                      $lastactref,%domconfig);
  760:     } elsif ($action eq 'quotas') {
  761:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  762:     } elsif ($action eq 'autoenroll') {
  763:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  764:     } elsif ($action eq 'autoupdate') {
  765:         $output = &modify_autoupdate($dom,%domconfig);
  766:     } elsif ($action eq 'autocreate') {
  767:         $output = &modify_autocreate($dom,%domconfig);
  768:     } elsif ($action eq 'directorysrch') {
  769:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  770:     } elsif ($action eq 'usercreation') {
  771:         $output = &modify_usercreation($dom,%domconfig);
  772:     } elsif ($action eq 'selfcreation') {
  773:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  774:     } elsif ($action eq 'usermodification') {
  775:         $output = &modify_usermodification($dom,%domconfig);
  776:     } elsif ($action eq 'contacts') {
  777:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  778:     } elsif ($action eq 'defaults') {
  779:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  780:     } elsif ($action eq 'scantron') {
  781:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  782:     } elsif ($action eq 'coursecategories') {
  783:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  784:     } elsif ($action eq 'serverstatuses') {
  785:         $output = &modify_serverstatuses($dom,%domconfig);
  786:     } elsif ($action eq 'requestcourses') {
  787:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  788:     } elsif ($action eq 'requestauthor') {
  789:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  790:     } elsif ($action eq 'helpsettings') {
  791:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  792:     } elsif ($action eq 'coursedefaults') {
  793:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  794:     } elsif ($action eq 'selfenrollment') {
  795:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  796:     } elsif ($action eq 'usersessions') {
  797:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  798:     } elsif ($action eq 'loadbalancing') {
  799:         $output = &modify_loadbalancing($dom,%domconfig);
  800:     } elsif ($action eq 'ltitools') {
  801:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  802:     } elsif ($action eq 'lti') {
  803:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  804:     } elsif ($action eq 'passwords') {
  805:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  806:     } elsif ($action eq 'wafproxy') {
  807:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  808:     } elsif ($action eq 'ipaccess') {
  809:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  810:     }
  811:     return $output;
  812: }
  813: 
  814: sub print_config_box {
  815:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  816:     my $rowtotal = 0;
  817:     my $output;
  818:     if ($action eq 'coursecategories') {
  819:         $output = &coursecategories_javascript($settings);
  820:     } elsif ($action eq 'defaults') {
  821:         $output = &defaults_javascript($settings); 
  822:     } elsif ($action eq 'passwords') {
  823:         $output = &passwords_javascript($action);
  824:     } elsif ($action eq 'helpsettings') {
  825:         my (%privs,%levelscurrent);
  826:         my %full=();
  827:         my %levels=(
  828:                      course => {},
  829:                      domain => {},
  830:                      system => {},
  831:                    );
  832:         my $context = 'domain';
  833:         my $crstype = 'Course';
  834:         my $formname = 'display';
  835:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  836:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  837:         $output =
  838:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  839:                                                       \@templateroles);
  840:     } elsif ($action eq 'ltitools') {
  841:         $output .= &Apache::lonconfigsettings::ltitools_javascript($settings);
  842:     } elsif ($action eq 'lti') {
  843:         $output .= &passwords_javascript('ltisecrets')."\n".
  844:                    &lti_javascript($dom,$settings);
  845:     } elsif ($action eq 'wafproxy') {
  846:         $output .= &wafproxy_javascript($dom);
  847:     } elsif ($action eq 'autoupdate') {
  848:         $output .= &autoupdate_javascript();
  849:     } elsif ($action eq 'autoenroll') {
  850:         $output .= &autoenroll_javascript();
  851:     } elsif ($action eq 'login') {
  852:         $output .= &saml_javascript();
  853:     } elsif ($action eq 'ipaccess') {
  854:         $output .= &ipaccess_javascript($settings);
  855:     }
  856:     $output .=
  857:          '<table class="LC_nested_outer">
  858:           <tr>
  859:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  860:            &mt($item->{text}).'&nbsp;'.
  861:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  862:           '</tr>';
  863:     $rowtotal ++;
  864:     my $numheaders = 1;
  865:     if (ref($item->{'header'}) eq 'ARRAY') {
  866:         $numheaders = scalar(@{$item->{'header'}});
  867:     }
  868:     if ($numheaders > 1) {
  869:         my $colspan = '';
  870:         my $rightcolspan = '';
  871:         my $leftnobr = '';
  872:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  873:             ($action eq 'directorysrch') ||
  874:             (($action eq 'login') && ($numheaders < 5))) {
  875:             $colspan = ' colspan="2"';
  876:         }
  877:         if ($action eq 'usersessions') {
  878:             $rightcolspan = ' colspan="3"'; 
  879:         }
  880:         if ($action eq 'passwords') {
  881:             $leftnobr = ' LC_nobreak';
  882:         }
  883:         $output .= '
  884:           <tr>
  885:            <td>
  886:             <table class="LC_nested">
  887:              <tr class="LC_info_row">
  888:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  889:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  890:              </tr>';
  891:         $rowtotal ++;
  892:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  893:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  894:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
  895:             ($action eq 'helpsettings') || ($action eq 'contacts') || ($action eq 'wafproxy') ||
  896:             ($action eq 'lti') || ($action eq 'ltitools')) {
  897:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  898:         } elsif ($action eq 'passwords') {
  899:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  900:         } elsif ($action eq 'coursecategories') {
  901:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  902:         } elsif ($action eq 'scantron') {
  903:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  904:         } elsif ($action eq 'login') {
  905:             if ($numheaders == 5) {
  906:                 $colspan = ' colspan="2"';
  907:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  908:             } else {
  909:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  910:             }
  911:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  912:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  913:         } elsif ($action eq 'rolecolors') {
  914:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  915:         }
  916:         $output .= '
  917:            </table>
  918:           </td>
  919:          </tr>
  920:          <tr>
  921:            <td>
  922:             <table class="LC_nested">
  923:              <tr class="LC_info_row">
  924:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  925:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  926:              </tr>';
  927:             $rowtotal ++;
  928:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  929:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  930:             ($action eq 'usersessions') || ($action eq 'coursecategories') ||
  931:             ($action eq 'contacts') || ($action eq 'passwords') || 
  932:             ($action eq 'defaults') || ($action eq 'lti') ||
  933:             ($action eq 'ltitools')) {
  934:             if ($action eq 'coursecategories') {
  935:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  936:                 $colspan = ' colspan="2"';
  937:             } elsif ($action eq 'passwords') {
  938:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  939:             } else {
  940:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  941:             }
  942:             $output .= '
  943:            </table>
  944:           </td>
  945:          </tr>
  946:          <tr>
  947:            <td>
  948:             <table class="LC_nested">
  949:              <tr class="LC_info_row">
  950:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  951:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  952:              </tr>'."\n";
  953:             if ($action eq 'coursecategories') {
  954:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  955:             } elsif (($action eq 'contacts') || ($action eq 'passwords')) {
  956:                 if ($action eq 'passwords') {
  957:                     $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
  958:                 } else {
  959:                     $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
  960:                 }
  961:                 $output .= '
  962:              </tr>
  963:             </table>
  964:            </td>
  965:           </tr>
  966:           <tr>
  967:            <td>
  968:             <table class="LC_nested">
  969:              <tr class="LC_info_row">
  970:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  971:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
  972:                 if ($action eq 'passwords') {
  973:                     $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
  974:                 } else {
  975:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  976:                 }
  977:                 $output .= '
  978:             </table>
  979:           </td>
  980:          </tr>
  981:          <tr>';
  982:             } else {
  983:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  984:             }
  985:             $rowtotal ++;
  986:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  987:                  ($action eq 'directorysrch') || ($action eq 'helpsettings') ||
  988:                  ($action eq 'wafproxy')) {
  989:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  990:         } elsif ($action eq 'scantron') {
  991:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
  992:         } elsif ($action eq 'login') {
  993:             if ($numheaders == 5) {
  994:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
  995:            </table>
  996:           </td>
  997:          </tr>
  998:          <tr>
  999:            <td>
 1000:             <table class="LC_nested">
 1001:              <tr class="LC_info_row">
 1002:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1003:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1004:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1005:                 $rowtotal ++;
 1006:             } else {
 1007:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1008:             }
 1009:             $output .= '
 1010:            </table>
 1011:           </td>
 1012:          </tr>
 1013:          <tr>
 1014:            <td>
 1015:             <table class="LC_nested">
 1016:              <tr class="LC_info_row">';
 1017:             if ($numheaders == 5) {
 1018:                 $output .= '
 1019:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1020:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1021:              </tr>';
 1022:             } else {
 1023:                 $output .= '
 1024:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1025:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1026:              </tr>';
 1027:             }
 1028:             $rowtotal ++;
 1029:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
 1030:            </table>
 1031:           </td>
 1032:          </tr>
 1033:          <tr>
 1034:            <td>
 1035:             <table class="LC_nested">
 1036:              <tr class="LC_info_row">';
 1037:             if ($numheaders == 5) {
 1038:                 $output .= '
 1039:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1040:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1041:              </tr>';
 1042:             } else {
 1043:                 $output .= '
 1044:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1045:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1046:              </tr>';
 1047:             }
 1048:             $rowtotal ++;
 1049:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1050:         } elsif ($action eq 'requestcourses') {
 1051:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1052:             $rowtotal ++;
 1053:             $output .= &print_studentcode($settings,\$rowtotal).'
 1054:            </table>
 1055:           </td>
 1056:          </tr>
 1057:          <tr>
 1058:            <td>
 1059:             <table class="LC_nested">
 1060:              <tr class="LC_info_row">
 1061:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1062:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1063:                        &textbookcourses_javascript($settings).
 1064:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1065:             </table>
 1066:            </td>
 1067:           </tr>
 1068:          <tr>
 1069:            <td>
 1070:             <table class="LC_nested">
 1071:              <tr class="LC_info_row">
 1072:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1073:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1074:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1075:             </table>
 1076:            </td>
 1077:           </tr>
 1078:           <tr>
 1079:            <td>
 1080:             <table class="LC_nested">
 1081:              <tr class="LC_info_row">
 1082:               <td class="LC_left_item"'.$colspan.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1083:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1084:              </tr>'.
 1085:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1086:         } elsif ($action eq 'requestauthor') {
 1087:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1088:             $rowtotal ++;
 1089:         } elsif ($action eq 'rolecolors') {
 1090:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1091:            </table>
 1092:           </td>
 1093:          </tr>
 1094:          <tr>
 1095:            <td>
 1096:             <table class="LC_nested">
 1097:              <tr class="LC_info_row">
 1098:               <td class="LC_left_item"'.$colspan.' valign="top">'.
 1099:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1100:               <td class="LC_right_item" valign="top">'.
 1101:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1102:              </tr>'.
 1103:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1104:            </table>
 1105:           </td>
 1106:          </tr>
 1107:          <tr>
 1108:            <td>
 1109:             <table class="LC_nested">
 1110:              <tr class="LC_info_row">
 1111:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1112:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1113:              </tr>'.
 1114:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1115:             $rowtotal += 2;
 1116:         }
 1117:     } else {
 1118:         $output .= '
 1119:           <tr>
 1120:            <td>
 1121:             <table class="LC_nested">
 1122:              <tr class="LC_info_row">';
 1123:         if ($action eq 'login') {
 1124:             $output .= '  
 1125:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1126:         } elsif ($action eq 'serverstatuses') {
 1127:             $output .= '
 1128:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1129:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1130: 
 1131:         } else {
 1132:             $output .= '
 1133:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1134:         }
 1135:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1136:             $output .= '<td class="LC_left_item" valign="top">'.
 1137:                        &mt($item->{'header'}->[0]->{'col2'});
 1138:             if ($action eq 'serverstatuses') {
 1139:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1140:             } 
 1141:         } else {
 1142:             $output .= '<td class="LC_right_item" valign="top">'.
 1143:                        &mt($item->{'header'}->[0]->{'col2'});
 1144:         }
 1145:         $output .= '</td>';
 1146:         if ($item->{'header'}->[0]->{'col3'}) {
 1147:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1148:                 $output .= '<td class="LC_left_item" valign="top">'.
 1149:                             &mt($item->{'header'}->[0]->{'col3'});
 1150:             } else {
 1151:                 $output .= '<td class="LC_right_item" valign="top">'.
 1152:                            &mt($item->{'header'}->[0]->{'col3'});
 1153:             }
 1154:             if ($action eq 'serverstatuses') {
 1155:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1156:             }
 1157:             $output .= '</td>';
 1158:         }
 1159:         if ($item->{'header'}->[0]->{'col4'}) {
 1160:             $output .= '<td class="LC_right_item" valign="top">'.
 1161:                        &mt($item->{'header'}->[0]->{'col4'});
 1162:         }
 1163:         $output .= '</tr>';
 1164:         $rowtotal ++;
 1165:         if ($action eq 'quotas') {
 1166:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1167:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1168:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') ||
 1169:                  ($action eq 'ipaccess')) {
 1170:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1171:         }
 1172:     }
 1173:     $output .= '
 1174:    </table>
 1175:   </td>
 1176:  </tr>
 1177: </table><br />';
 1178:     return ($output,$rowtotal);
 1179: }
 1180: 
 1181: sub print_login {
 1182:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1183:     my ($css_class,$datatable,$switchserver,%lt);
 1184:     my %choices = &login_choices();
 1185:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1186:         %lt = &login_file_options();
 1187:         $switchserver = &check_switchserver($dom,$confname);
 1188:     }
 1189:     if ($caller eq 'service') {
 1190:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1191:         my $choice = $choices{'disallowlogin'};
 1192:         $css_class = ' class="LC_odd_row"';
 1193:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1194:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1195:                       '<th>'.$choices{'server'}.'</th>'.
 1196:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1197:                       '<th>'.$choices{'custompath'}.'</th>'.
 1198:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1199:         my %disallowed;
 1200:         if (ref($settings) eq 'HASH') {
 1201:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1202:                %disallowed = %{$settings->{'loginvia'}};
 1203:             }
 1204:         }
 1205:         foreach my $lonhost (sort(keys(%servers))) {
 1206:             my $direct = 'selected="selected"';
 1207:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1208:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1209:                     $direct = '';
 1210:                 }
 1211:             }
 1212:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1213:                           '<td><select name="'.$lonhost.'_server">'.
 1214:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1215:                           '</option>';
 1216:             foreach my $hostid (sort(keys(%servers))) {
 1217:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1218:                 my $selected = '';
 1219:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1220:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1221:                         $selected = 'selected="selected"';
 1222:                     }
 1223:                 }
 1224:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1225:                               $servers{$hostid}.'</option>';
 1226:             }
 1227:             $datatable .= '</select></td>'.
 1228:                           '<td><select name="'.$lonhost.'_serverpath">';
 1229:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1230:                 my $pathname = $path;
 1231:                 if ($path eq 'custom') {
 1232:                     $pathname = &mt('Custom Path').' ->';
 1233:                 }
 1234:                 my $selected = '';
 1235:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1236:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1237:                         $selected = 'selected="selected"';
 1238:                     }
 1239:                 } elsif ($path eq '') {
 1240:                     $selected = 'selected="selected"';
 1241:                 }
 1242:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1243:             }
 1244:             $datatable .= '</select></td>';
 1245:             my ($custom,$exempt);
 1246:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1247:                 $custom = $disallowed{$lonhost}{'custompath'};
 1248:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1249:             }
 1250:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1251:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1252:                           '</tr>';
 1253:         }
 1254:         $datatable .= '</table></td></tr>';
 1255:         return $datatable;
 1256:     } elsif ($caller eq 'page') {
 1257:         my %defaultchecked = ( 
 1258:                                'coursecatalog' => 'on',
 1259:                                'helpdesk'      => 'on',
 1260:                                'adminmail'     => 'off',
 1261:                                'newuser'       => 'off',
 1262:                              );
 1263:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1264:         my (%checkedon,%checkedoff);
 1265:         foreach my $item (@toggles) {
 1266:             if ($defaultchecked{$item} eq 'on') { 
 1267:                 $checkedon{$item} = ' checked="checked" ';
 1268:                 $checkedoff{$item} = ' ';
 1269:             } elsif ($defaultchecked{$item} eq 'off') {
 1270:                 $checkedoff{$item} = ' checked="checked" ';
 1271:                 $checkedon{$item} = ' ';
 1272:             }
 1273:         }
 1274:         my @images = ('img','logo','domlogo','login');
 1275:         my @alttext = ('img','logo','domlogo');
 1276:         my @logintext = ('textcol','bgcol');
 1277:         my @bgs = ('pgbg','mainbg','sidebg');
 1278:         my @links = ('link','alink','vlink');
 1279:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1280:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1281:         my (%is_custom,%designs);
 1282:         my %defaults = (
 1283:                        font => $defaultdesign{'login.font'},
 1284:                        );
 1285:         foreach my $item (@images) {
 1286:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1287:             $defaults{'showlogo'}{$item} = 1;
 1288:         }
 1289:         foreach my $item (@bgs) {
 1290:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1291:         }
 1292:         foreach my $item (@logintext) {
 1293:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1294:         }
 1295:         foreach my $item (@links) {
 1296:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1297:         }
 1298:         if (ref($settings) eq 'HASH') {
 1299:             foreach my $item (@toggles) {
 1300:                 if ($settings->{$item} eq '1') {
 1301:                     $checkedon{$item} =  ' checked="checked" ';
 1302:                     $checkedoff{$item} = ' ';
 1303:                 } elsif ($settings->{$item} eq '0') {
 1304:                     $checkedoff{$item} =  ' checked="checked" ';
 1305:                     $checkedon{$item} = ' ';
 1306:                 }
 1307:             }
 1308:             foreach my $item (@images) {
 1309:                 if (defined($settings->{$item})) {
 1310:                     $designs{$item} = $settings->{$item};
 1311:                     $is_custom{$item} = 1;
 1312:                 }
 1313:                 if (defined($settings->{'showlogo'}{$item})) {
 1314:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1315:                 }
 1316:             }
 1317:             foreach my $item (@alttext) {
 1318:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1319:                     if ($settings->{'alttext'}->{$item} ne '') {
 1320:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1321:                     }
 1322:                 }
 1323:             }
 1324:             foreach my $item (@logintext) {
 1325:                 if ($settings->{$item} ne '') {
 1326:                     $designs{'logintext'}{$item} = $settings->{$item};
 1327:                     $is_custom{$item} = 1;
 1328:                 }
 1329:             }
 1330:             if ($settings->{'font'} ne '') {
 1331:                 $designs{'font'} = $settings->{'font'};
 1332:                 $is_custom{'font'} = 1;
 1333:             }
 1334:             foreach my $item (@bgs) {
 1335:                 if ($settings->{$item} ne '') {
 1336:                     $designs{'bgs'}{$item} = $settings->{$item};
 1337:                     $is_custom{$item} = 1;
 1338:                 }
 1339:             }
 1340:             foreach my $item (@links) {
 1341:                 if ($settings->{$item} ne '') {
 1342:                     $designs{'links'}{$item} = $settings->{$item};
 1343:                     $is_custom{$item} = 1;
 1344:                 }
 1345:             }
 1346:         } else {
 1347:             if ($designhash{$dom.'.login.font'} ne '') {
 1348:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1349:                 $is_custom{'font'} = 1;
 1350:             }
 1351:             foreach my $item (@images) {
 1352:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1353:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1354:                     $is_custom{$item} = 1;
 1355:                 }
 1356:             }
 1357:             foreach my $item (@bgs) {
 1358:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1359:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1360:                     $is_custom{$item} = 1;
 1361:                 }
 1362:             }
 1363:             foreach my $item (@links) {
 1364:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1365:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1366:                     $is_custom{$item} = 1;
 1367:                 }
 1368:             }
 1369:         }
 1370:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1371:                                                       logo => 'Institution Logo',
 1372:                                                       domlogo => 'Domain Logo',
 1373:                                                       login => 'Login box');
 1374:         my $itemcount = 1;
 1375:         foreach my $item (@toggles) {
 1376:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1377:             $datatable .=  
 1378:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1379:                 '</td><td>'.
 1380:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1381:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1382:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1383:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1384:                 '</tr>';
 1385:             $itemcount ++;
 1386:         }
 1387:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1388:         $datatable .= '</tr></table></td></tr>';
 1389:     } elsif ($caller eq 'help') {
 1390:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1391:         my $itemcount = 1;
 1392:         $defaulturl = '/adm/loginproblems.html';
 1393:         $defaulttype = 'default';
 1394:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1395:         my @currlangs;
 1396:         if (ref($settings) eq 'HASH') {
 1397:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1398:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1399:                     next if ($settings->{'helpurl'}{$key} eq '');
 1400:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1401:                     $type{$key} = 'custom';
 1402:                     unless ($key eq 'nolang') {
 1403:                         push(@currlangs,$key);
 1404:                     }
 1405:                 }
 1406:             } elsif ($settings->{'helpurl'} ne '') {
 1407:                 $type{'nolang'} = 'custom';
 1408:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1409:             }
 1410:         }
 1411:         foreach my $lang ('nolang',sort(@currlangs)) {
 1412:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1413:             $datatable .= '<tr'.$css_class.'>';
 1414:             if ($url{$lang} eq '') {
 1415:                 $url{$lang} = $defaulturl;
 1416:             }
 1417:             if ($type{$lang} eq '') {
 1418:                 $type{$lang} = $defaulttype;
 1419:             }
 1420:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1421:             if ($lang eq 'nolang') {
 1422:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1423:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1424:             } else {
 1425:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1426:                                   $langchoices{$lang},
 1427:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1428:             }
 1429:             $datatable .= '</span></td>'."\n".
 1430:                           '<td class="LC_left_item">';
 1431:             if ($type{$lang} eq 'custom') {
 1432:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1433:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1434:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1435:             } else {
 1436:                 $datatable .= $lt{'upl'};
 1437:             }
 1438:             $datatable .='<br />';
 1439:             if ($switchserver) {
 1440:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1441:             } else {
 1442:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1443:             }
 1444:             $datatable .= '</td></tr>';
 1445:             $itemcount ++;
 1446:         }
 1447:         my @addlangs;
 1448:         foreach my $lang (sort(keys(%langchoices))) {
 1449:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1450:             push(@addlangs,$lang);
 1451:         }
 1452:         if (@addlangs > 0) {
 1453:             my %toadd;
 1454:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1455:             $toadd{''} = &mt('Select');
 1456:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1457:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1458:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1459:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1460:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1461:             if ($switchserver) {
 1462:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1463:             } else {
 1464:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1465:             }
 1466:             $datatable .= '</td></tr>';
 1467:             $itemcount ++;
 1468:         }
 1469:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1470:     } elsif ($caller eq 'headtag') {
 1471:         my %domservers = &Apache::lonnet::get_servers($dom);
 1472:         my $choice = $choices{'headtag'};
 1473:         $css_class = ' class="LC_odd_row"';
 1474:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1475:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1476:                       '<th>'.$choices{'current'}.'</th>'.
 1477:                       '<th>'.$choices{'action'}.'</th>'.
 1478:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1479:         my (%currurls,%currexempt);
 1480:         if (ref($settings) eq 'HASH') {
 1481:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1482:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1483:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1484:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1485:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1486:                     }
 1487:                 }
 1488:             }
 1489:         }
 1490:         foreach my $lonhost (sort(keys(%domservers))) {
 1491:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1492:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1493:             if ($currurls{$lonhost}) {
 1494:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1495:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1496:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1497:                               '">'.$lt{'curr'}.'</a></td>'.
 1498:                               '<td><span class="LC_nobreak"><label>'.
 1499:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1500:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1501:             } else {
 1502:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1503:             }
 1504:             $datatable .='<br />';
 1505:             if ($switchserver) {
 1506:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1507:             } else {
 1508:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1509:             }
 1510:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1511:         }
 1512:         $datatable .= '</table></td></tr>';
 1513:     } elsif ($caller eq 'saml') {
 1514:         my %domservers = &Apache::lonnet::get_servers($dom);
 1515:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1516:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1517:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1518:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1519:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlwindow,%samlnotsso,%styleon,%styleoff);
 1520:         foreach my $lonhost (keys(%domservers)) {
 1521:             $samlurl{$lonhost} = '/adm/sso';
 1522:             $styleon{$lonhost} = 'display:none';
 1523:             $styleoff{$lonhost} = '';
 1524:         }
 1525:         if ((ref($settings) eq 'HASH') && (ref($settings->{'saml'}) eq 'HASH')) {
 1526:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1527:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1528:                     $saml{$lonhost} = 1;
 1529:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1530:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1531:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1532:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1533:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1534:                     $samlwindow{$lonhost} = $settings->{'saml'}{$lonhost}{'window'};
 1535:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1536:                     $styleon{$lonhost} = '';
 1537:                     $styleoff{$lonhost} = 'display:none';
 1538:                 } else {
 1539:                     $styleon{$lonhost} = 'display:none';
 1540:                     $styleoff{$lonhost} = '';
 1541:                 }
 1542:             }
 1543:         }
 1544:         my $itemcount = 1;
 1545:         foreach my $lonhost (sort(keys(%domservers))) {
 1546:             my $samlon = ' ';
 1547:             my $samloff = ' checked="checked" ';
 1548:             if ($saml{$lonhost}) {
 1549:                 $samlon = $samloff;
 1550:                 $samloff = ' ';
 1551:             }
 1552:             my $samlwinon = '';
 1553:             my $samlwinoff = ' checked="checked"';
 1554:             if ($samlwindow{$lonhost}) {
 1555:                 $samlwinon = $samlwinoff;
 1556:                 $samlwinoff = '';
 1557:             }
 1558:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1559:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1560:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1561:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1562:                           &mt('No').'</label>'.('&nbsp;'x2).
 1563:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1564:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1565:                           &mt('Yes').'</label></span></td>'.
 1566:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1567:                           '<table width="100%"><tr><th colspan="3" align="center">'.&mt('SSO').'</th></tr>'.
 1568:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1569:                           '<th>'.&mt('Alt Text').'</th></tr>'.
 1570:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="20" value="'.
 1571:                           $samltext{$lonhost}.'" /></td><td>';
 1572:             if ($samlimg{$lonhost}) {
 1573:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1574:                               '<span class="LC_nobreak"><label>'.
 1575:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1576:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1577:             } else {
 1578:                 $datatable .= $lt{'upl'};
 1579:             }
 1580:             $datatable .='<br />';
 1581:             if ($switchserver) {
 1582:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1583:             } else {
 1584:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1585:             }
 1586:             $datatable .= '</td>'.
 1587:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="25" '.
 1588:                           'value="'.$samlalt{$lonhost}.'" /></td></tr></table><br />'.
 1589:                           '<table width="100%"><tr><th colspan="3" align="center">'.&mt('SSO').'</th><th align="center">'.
 1590:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1591:                           '<tr><th>'.&mt('URL').'</th><th>'.&mt('Tool Tip').'</th>'.
 1592:                           '<th>'.&mt('Pop-up if iframe').'</th><th>'.&mt('Text').'</th></tr>'.
 1593:                           '<tr'.$css_class.'>'.
 1594:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="30" '.
 1595:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1596:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="20">'.
 1597:                           $samltitle{$lonhost}.'</textarea></td>'.
 1598:                           '<td><label><input type="radio" name="saml_window_'.$lonhost.'" value=""'.$samlwinoff.'>'.
 1599:                           &mt('No').'</label>'.('&nbsp;'x2).'<label><input type="radio" '.
 1600:                           'name="saml_window_'.$lonhost.'" value="1"'.$samlwinon.'>'.&mt('Yes').'</label></td>'.
 1601:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="12" '.
 1602:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1603:                           '</table></td>'.
 1604:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1605:            $itemcount ++;
 1606:         }
 1607:         $datatable .= '</table></td></tr>';
 1608:     }
 1609:     return $datatable;
 1610: }
 1611: 
 1612: sub login_choices {
 1613:     my %choices =
 1614:         &Apache::lonlocal::texthash (
 1615:             coursecatalog => 'Display Course/Community Catalog link?',
 1616:             adminmail     => "Display Administrator's E-mail Address?",
 1617:             helpdesk      => 'Display "Contact Helpdesk" link',
 1618:             disallowlogin => "Login page requests redirected",
 1619:             hostid        => "Server",
 1620:             server        => "Redirect to:",
 1621:             serverpath    => "Path",
 1622:             custompath    => "Custom", 
 1623:             exempt        => "Exempt IP(s)",
 1624:             directlogin   => "No redirect",
 1625:             newuser       => "Link to create a user account",
 1626:             img           => "Header",
 1627:             logo          => "Main Logo",
 1628:             domlogo       => "Domain Logo",
 1629:             login         => "Log-in Header", 
 1630:             textcol       => "Text color",
 1631:             bgcol         => "Box color",
 1632:             bgs           => "Background colors",
 1633:             links         => "Link colors",
 1634:             font          => "Font color",
 1635:             pgbg          => "Header",
 1636:             mainbg        => "Page",
 1637:             sidebg        => "Login box",
 1638:             link          => "Link",
 1639:             alink         => "Active link",
 1640:             vlink         => "Visited link",
 1641:             headtag       => "Custom markup",
 1642:             action        => "Action",
 1643:             current       => "Current",
 1644:             samllanding   => "Dual login?",
 1645:             samloptions   => "Options",
 1646:             alttext       => "Alt text",
 1647:         );
 1648:     return %choices;
 1649: }
 1650: 
 1651: sub login_file_options {
 1652:       return &Apache::lonlocal::texthash(
 1653:                                            del     => 'Delete?',
 1654:                                            rep     => 'Replace:',
 1655:                                            upl     => 'Upload:',
 1656:                                            curr    => 'View contents',
 1657:                                            default => 'Default',
 1658:                                            custom  => 'Custom',
 1659:                                            none    => 'None',
 1660:       );
 1661: }
 1662: 
 1663: sub print_ipaccess {
 1664:     my ($dom,$settings,$rowtotal) = @_;
 1665:     my $css_class;
 1666:     my $itemcount = 0;
 1667:     my $datatable;
 1668:     my %ordered;
 1669:     if (ref($settings) eq 'HASH') {
 1670:         foreach my $item (keys(%{$settings})) {
 1671:             if (ref($settings->{$item}) eq 'HASH') {
 1672:                 my $num = $settings->{$item}{'order'};
 1673:                 if ($num eq '') {
 1674:                     $num = scalar(keys(%{$settings}));
 1675:                 }
 1676:                 $ordered{$num} = $item;
 1677:             }
 1678:         }
 1679:     }
 1680:     my $maxnum = scalar(keys(%ordered));
 1681:     if (keys(%ordered)) {
 1682:         my @items = sort { $a <=> $b } keys(%ordered);
 1683:         for (my $i=0; $i<@items; $i++) {
 1684:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1685:             my $item = $ordered{$items[$i]};
 1686:             my ($name,$ipranges,%commblocks,%courses);
 1687:             if (ref($settings->{$item}) eq 'HASH') {
 1688:                 $name = $settings->{$item}->{'name'};
 1689:                 $ipranges = $settings->{$item}->{'ip'};
 1690:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1691:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1692:                 }
 1693:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1694:                     %courses = %{$settings->{$item}->{'courses'}};
 1695:                 }
 1696:             }
 1697:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1698:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1699:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1700:             for (my $k=0; $k<=$maxnum; $k++) {
 1701:                 my $vpos = $k+1;
 1702:                 my $selstr;
 1703:                 if ($k == $i) {
 1704:                     $selstr = ' selected="selected" ';
 1705:                 }
 1706:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1707:             }
 1708:             $datatable .= '</select>'.('&nbsp;'x2).
 1709:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1710:                 &mt('Delete?').'</label></span></td>'.
 1711:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1712:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1713:                 '</td></tr>';
 1714:             $itemcount ++;
 1715:         }
 1716:     }
 1717:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1718:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1719:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1720:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1721:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1722:     for (my $k=0; $k<$maxnum+1; $k++) {
 1723:         my $vpos = $k+1;
 1724:         my $selstr;
 1725:         if ($k == $maxnum) {
 1726:             $selstr = ' selected="selected" ';
 1727:         }
 1728:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1729:     }
 1730:     $datatable .= '</select>&nbsp;'."\n".
 1731:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1732:                   '<td colspan="2">'.
 1733:                   &ipaccess_options('add',$itemcount,$dom).
 1734:                   '</td>'."\n".
 1735:                   '</tr>'."\n";
 1736:     $$rowtotal ++;
 1737:     return $datatable;
 1738: }
 1739: 
 1740: sub ipaccess_options {
 1741:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1742:     my (%currblocks,%currcourses,$output);
 1743:     if (ref($blocksref) eq 'HASH') {
 1744:         %currblocks = %{$blocksref};
 1745:     }
 1746:     if (ref($coursesref) eq 'HASH') {
 1747:         %currcourses = %{$coursesref};
 1748:     }
 1749:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1750:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1751:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1752:               '</span></fieldset>'.
 1753:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1754:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1755:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1756:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1757:               $ipranges.'</textarea></fieldset>'.
 1758:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1759:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1760:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1761:               '<table>';
 1762:     foreach my $cid (sort(keys(%currcourses))) {
 1763:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1764:         $output .= '<tr><td><span class="LC_nobreak">'.
 1765:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1766:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1767:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1768:     }
 1769:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1770:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1771:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1772:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1773:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1774:                '</span></td></tr></table>'."\n".
 1775:                '</fieldset>';
 1776:     return $output;
 1777: }
 1778: 
 1779: sub blocker_checkboxes {
 1780:     my ($num,$blocks) = @_;
 1781:     my ($typeorder,$types) = &commblocktype_text();
 1782:     my $numinrow = 6;
 1783:     my $output = '<table>';
 1784:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1785:         my $block = $typeorder->[$i];
 1786:         my $blockstatus;
 1787:         if (ref($blocks) eq 'HASH') {
 1788:             if ($blocks->{$block} eq 'on') {
 1789:                 $blockstatus = 'checked="checked"';
 1790:             }
 1791:         }
 1792:         my $rem = $i%($numinrow);
 1793:         if ($rem == 0) {
 1794:             if ($i > 0) {
 1795:                 $output .= '</tr>';
 1796:             }
 1797:             $output .= '<tr>';
 1798:         }
 1799:         if ($i == scalar(@{$typeorder})-1) {
 1800:             my $colsleft = $numinrow-$rem;
 1801:             if ($colsleft > 1) {
 1802:                 $output .= '<td colspan="'.$colsleft.'">';
 1803:             } else {
 1804:                 $output .= '<td>';
 1805:             }
 1806:         } else {
 1807:             $output .= '<td>';
 1808:         }
 1809:         my $item = 'ipaccess_block_'.$num;
 1810:         if ($blockstatus) {
 1811:             $blockstatus = ' '.$blockstatus;
 1812:         }
 1813:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1814:                    '<input type="checkbox" name="'.$item.'"'.
 1815:                    $blockstatus.' value="'.$block.'"'.' />'.
 1816:                    $types->{$block}.'</label></span>'."\n".
 1817:                    '<br /></td>';
 1818:     }
 1819:     $output .= '</tr></table>';
 1820:     return $output;
 1821: }
 1822: 
 1823: sub commblocktype_text {
 1824:     my %types = &Apache::lonlocal::texthash(
 1825:         'com' => 'Messaging',
 1826:         'chat' => 'Chat Room',
 1827:         'boards' => 'Discussion',
 1828:         'port' => 'Portfolio',
 1829:         'groups' => 'Groups',
 1830:         'blogs' => 'Blogs',
 1831:         'about' => 'User Information',
 1832:         'printout' => 'Printouts',
 1833:         'passwd' => 'Change Password',
 1834:         'grades' => 'Gradebook',
 1835:         'search' => 'Course search',
 1836:         'wishlist' => 'Stored links',
 1837:         'annotate' => 'Annotations',
 1838:     );
 1839:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1840:     return ($typeorder,\%types);
 1841: }
 1842: 
 1843: sub print_rolecolors {
 1844:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1845:     my %choices = &color_font_choices();
 1846:     my @bgs = ('pgbg','tabbg','sidebg');
 1847:     my @links = ('link','alink','vlink');
 1848:     my @images = ('img');
 1849:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1850:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1851:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1852:     my (%is_custom,%designs);
 1853:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1854:     if (ref($settings) eq 'HASH') {
 1855:         if (ref($settings->{$role}) eq 'HASH') {
 1856:             if ($settings->{$role}->{'img'} ne '') {
 1857:                 $designs{'img'} = $settings->{$role}->{'img'};
 1858:                 $is_custom{'img'} = 1;
 1859:             }
 1860:             if ($settings->{$role}->{'font'} ne '') {
 1861:                 $designs{'font'} = $settings->{$role}->{'font'};
 1862:                 $is_custom{'font'} = 1;
 1863:             }
 1864:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1865:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1866:                 $is_custom{'fontmenu'} = 1;
 1867:             }
 1868:             foreach my $item (@bgs) {
 1869:                 if ($settings->{$role}->{$item} ne '') {
 1870:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1871:                     $is_custom{$item} = 1;
 1872:                 }
 1873:             }
 1874:             foreach my $item (@links) {
 1875:                 if ($settings->{$role}->{$item} ne '') {
 1876:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1877:                     $is_custom{$item} = 1;
 1878:                 }
 1879:             }
 1880:         }
 1881:     } else {
 1882:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1883:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1884:             $is_custom{'img'} = 1;
 1885:         }
 1886:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1887:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1888:             $is_custom{'fontmenu'} = 1; 
 1889:         }
 1890:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1891:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1892:             $is_custom{'font'} = 1;
 1893:         }
 1894:         foreach my $item (@bgs) {
 1895:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1896:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1897:                 $is_custom{$item} = 1;
 1898:             
 1899:             }
 1900:         }
 1901:         foreach my $item (@links) {
 1902:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1903:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1904:                 $is_custom{$item} = 1;
 1905:             }
 1906:         }
 1907:     }
 1908:     my $itemcount = 1;
 1909:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1910:     $datatable .= '</tr></table></td></tr>';
 1911:     return $datatable;
 1912: }
 1913: 
 1914: sub role_defaults {
 1915:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1916:     my %defaults;
 1917:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1918:         return %defaults;
 1919:     }
 1920:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1921:     if ($role eq 'login') {
 1922:         %defaults = (
 1923:                        font => $defaultdesign{$role.'.font'},
 1924:                     );
 1925:         if (ref($logintext) eq 'ARRAY') {
 1926:             foreach my $item (@{$logintext}) {
 1927:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1928:             }
 1929:         }
 1930:         foreach my $item (@{$images}) {
 1931:             $defaults{'showlogo'}{$item} = 1;
 1932:         }
 1933:     } else {
 1934:         %defaults = (
 1935:                        img => $defaultdesign{$role.'.img'},
 1936:                        font => $defaultdesign{$role.'.font'},
 1937:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1938:                     );
 1939:     }
 1940:     foreach my $item (@{$bgs}) {
 1941:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1942:     }
 1943:     foreach my $item (@{$links}) {
 1944:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1945:     }
 1946:     foreach my $item (@{$images}) {
 1947:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1948:     }
 1949:     return %defaults;
 1950: }
 1951: 
 1952: sub display_color_options {
 1953:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1954:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1955:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1956:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1957:     my $datatable = '<tr'.$css_class.'>'.
 1958:         '<td>'.$choices->{'font'}.'</td>';
 1959:     if (!$is_custom->{'font'}) {
 1960:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1961:     } else {
 1962:         $datatable .= '<td>&nbsp;</td>';
 1963:     }
 1964:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1965: 
 1966:     $datatable .= '<td><span class="LC_nobreak">'.
 1967:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1968:                   ' value="'.$current_color.'" />&nbsp;'.
 1969:                   '&nbsp;</span></td></tr>';
 1970:     unless ($role eq 'login') { 
 1971:         $datatable .= '<tr'.$css_class.'>'.
 1972:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1973:         if (!$is_custom->{'fontmenu'}) {
 1974:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1975:         } else {
 1976:             $datatable .= '<td>&nbsp;</td>';
 1977:         }
 1978: 	$current_color = $designs->{'fontmenu'} ?
 1979: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1980:         $datatable .= '<td><span class="LC_nobreak">'.
 1981:                       '<input class="colorchooser" type="text" size="10" name="'
 1982: 		      .$role.'_fontmenu"'.
 1983:                       ' value="'.$current_color.'" />&nbsp;'.
 1984:                       '&nbsp;</span></td></tr>';
 1985:     }
 1986:     my $switchserver = &check_switchserver($dom,$confname);
 1987:     foreach my $img (@{$images}) {
 1988: 	$itemcount ++;
 1989:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1990:         $datatable .= '<tr'.$css_class.'>'.
 1991:                       '<td>'.$choices->{$img};
 1992:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 1993:         if ($role eq 'login') {
 1994:             if ($img eq 'login') {
 1995:                 $login_hdr_pick =
 1996:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1997:                 $logincolors =
 1998:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1999:                                        $designs,$defaults);
 2000:             } else {
 2001:                 if ($img ne 'domlogo') {
 2002:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 2003:                 }
 2004:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 2005:                     $alttext = $designs->{'alttext'}{$img};
 2006:                 }
 2007:             }
 2008:         }
 2009:         $datatable .= '</td>';
 2010:         if ($designs->{$img} ne '') {
 2011:             $imgfile = $designs->{$img};
 2012: 	    $img_import = ($imgfile =~ m{^/adm/});
 2013:         } else {
 2014:             $imgfile = $defaults->{$img};
 2015:         }
 2016:         if ($imgfile) {
 2017:             my ($showfile,$fullsize);
 2018:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 2019:                 my $urldir = $1;
 2020:                 my $filename = $2;
 2021:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 2022:                 if (@info) {
 2023:                     my $thumbfile = 'tn-'.$filename;
 2024:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 2025:                     if (@thumb) {
 2026:                         $showfile = $urldir.'/'.$thumbfile;
 2027:                     } else {
 2028:                         $showfile = $imgfile;
 2029:                     }
 2030:                 } else {
 2031:                     $showfile = '';
 2032:                 }
 2033:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 2034:                 $showfile = $imgfile;
 2035:                 my $imgdir = $1;
 2036:                 my $filename = $2;
 2037:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 2038:                     $showfile = "/$imgdir/tn-".$filename;
 2039:                 } else {
 2040:                     my $input = $londocroot.$imgfile;
 2041:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 2042:                     if (!-e $output) {
 2043:                         my ($width,$height) = &thumb_dimensions();
 2044:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 2045:                         if ($fullwidth ne '' && $fullheight ne '') {
 2046:                             if ($fullwidth > $width && $fullheight > $height) { 
 2047:                                 my $size = $width.'x'.$height;
 2048:                                 my @args = ('convert','-sample',$size,$input,$output);
 2049:                                 system({$args[0]} @args);
 2050:                                 $showfile = "/$imgdir/tn-".$filename;
 2051:                             }
 2052:                         }
 2053:                     }
 2054:                 }
 2055:             }
 2056:             if ($showfile) {
 2057:                 if ($showfile =~ m{^/(adm|res)/}) {
 2058:                     if ($showfile =~ m{^/res/}) {
 2059:                         my $local_showfile =
 2060:                             &Apache::lonnet::filelocation('',$showfile);
 2061:                         &Apache::lonnet::repcopy($local_showfile);
 2062:                     }
 2063:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 2064:                 }
 2065:                 if ($imgfile) {
 2066:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 2067:                         if ($imgfile =~ m{^/res/}) {
 2068:                             my $local_imgfile =
 2069:                                 &Apache::lonnet::filelocation('',$imgfile);
 2070:                             &Apache::lonnet::repcopy($local_imgfile);
 2071:                         }
 2072:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 2073:                     } else {
 2074:                         $fullsize = $imgfile;
 2075:                     }
 2076:                 }
 2077:                 $datatable .= '<td>';
 2078:                 if ($img eq 'login') {
 2079:                     $datatable .= $login_hdr_pick;
 2080:                 } 
 2081:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 2082:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 2083:             } else {
 2084:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2085:                               &mt('Upload:').'<br />';
 2086:             }
 2087:         } else {
 2088:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2089:                           &mt('Upload:').'<br />';
 2090:         }
 2091:         if ($switchserver) {
 2092:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2093:         } else {
 2094:             if ($img ne 'login') { # suppress file selection for Log-in header
 2095:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 2096:             }
 2097:         }
 2098:         if (($role eq 'login') && ($img ne 'login')) {
 2099:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 2100:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 2101:                           '</label></span>';
 2102:         }
 2103:         $datatable .= '</td></tr>';
 2104:     }
 2105:     $itemcount ++;
 2106:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2107:     $datatable .= '<tr'.$css_class.'>'.
 2108:                   '<td>'.$choices->{'bgs'}.'</td>';
 2109:     my $bgs_def;
 2110:     foreach my $item (@{$bgs}) {
 2111:         if (!$is_custom->{$item}) {
 2112:             $bgs_def .= '<td><span class="LC_nobreak">'.$choices->{$item}.'</span>&nbsp;<span class="css_default_'.$role.'_'.$item.'" style="background-color: '.$defaults->{'bgs'}{$item}.';">&nbsp;&nbsp;&nbsp;</span><br />'.$defaults->{'bgs'}{$item}.'</td>';
 2113:         }
 2114:     }
 2115:     if ($bgs_def) {
 2116:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2117:     } else {
 2118:         $datatable .= '<td>&nbsp;</td>';
 2119:     }
 2120:     $datatable .= '<td class="LC_right_item">'.
 2121:                   '<table border="0"><tr>';
 2122: 
 2123:     foreach my $item (@{$bgs}) {
 2124:         $datatable .= '<td align="center">'.$choices->{$item};
 2125: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2126:         if ($designs->{'bgs'}{$item}) {
 2127:             $datatable .= '&nbsp;';
 2128:         }
 2129:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2130:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2131:     }
 2132:     $datatable .= '</tr></table></td></tr>';
 2133:     $itemcount ++;
 2134:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2135:     $datatable .= '<tr'.$css_class.'>'.
 2136:                   '<td>'.$choices->{'links'}.'</td>';
 2137:     my $links_def;
 2138:     foreach my $item (@{$links}) {
 2139:         if (!$is_custom->{$item}) {
 2140:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2141:         }
 2142:     }
 2143:     if ($links_def) {
 2144:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2145:     } else {
 2146:         $datatable .= '<td>&nbsp;</td>';
 2147:     }
 2148:     $datatable .= '<td class="LC_right_item">'.
 2149:                   '<table border="0"><tr>';
 2150:     foreach my $item (@{$links}) {
 2151: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2152:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 2153:         if ($designs->{'links'}{$item}) {
 2154:             $datatable.='&nbsp;';
 2155:         }
 2156:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2157:                       '" /></td>';
 2158:     }
 2159:     $$rowtotal += $itemcount;
 2160:     return $datatable;
 2161: }
 2162: 
 2163: sub logo_display_options {
 2164:     my ($img,$defaults,$designs) = @_;
 2165:     my $checkedon;
 2166:     if (ref($defaults) eq 'HASH') {
 2167:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2168:             if ($defaults->{'showlogo'}{$img}) {
 2169:                 $checkedon = 'checked="checked" ';     
 2170:             }
 2171:         } 
 2172:     }
 2173:     if (ref($designs) eq 'HASH') {
 2174:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2175:             if (defined($designs->{'showlogo'}{$img})) {
 2176:                 if ($designs->{'showlogo'}{$img} == 0) {
 2177:                     $checkedon = '';
 2178:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2179:                     $checkedon = 'checked="checked" ';
 2180:                 }
 2181:             }
 2182:         }
 2183:     }
 2184:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2185:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2186:            &mt('show').'</label>'."\n";
 2187: }
 2188: 
 2189: sub login_header_options  {
 2190:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2191:     my $output = '';
 2192:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2193:         $output .= &mt('Text default(s):').'<br />';
 2194:         if (!$is_custom->{'textcol'}) {
 2195:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2196:                        '&nbsp;&nbsp;&nbsp;';
 2197:         }
 2198:         if (!$is_custom->{'bgcol'}) {
 2199:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2200:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2201:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2202:         }
 2203:         $output .= '<br />';
 2204:     }
 2205:     $output .='<br />';
 2206:     return $output;
 2207: }
 2208: 
 2209: sub login_text_colors {
 2210:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2211:     my $color_menu = '<table border="0"><tr>';
 2212:     foreach my $item (@{$logintext}) {
 2213:         $color_menu .= '<td align="center">'.$choices->{$item};
 2214:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2215:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2216:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2217:     }
 2218:     $color_menu .= '</tr></table><br />';
 2219:     return $color_menu;
 2220: }
 2221: 
 2222: sub image_changes {
 2223:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2224:     my $output;
 2225:     if ($img eq 'login') {
 2226:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2227:     } elsif (!$is_custom) {
 2228:         if ($img ne 'domlogo') {
 2229:             $output = &mt('Default image:').'<br />';
 2230:         } else {
 2231:             $output = &mt('Default in use:').'<br />';
 2232:         }
 2233:     }
 2234:     if ($img ne 'login') {
 2235:         if ($img_import) {
 2236:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2237:         }
 2238:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2239:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2240:         if ($is_custom) {
 2241:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2242:                        '<input type="checkbox" name="'.
 2243:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2244:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2245:         } else {
 2246:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 2247:         }
 2248:     }
 2249:     return $output;
 2250: }
 2251: 
 2252: sub print_quotas {
 2253:     my ($dom,$settings,$rowtotal,$action) = @_;
 2254:     my $context;
 2255:     if ($action eq 'quotas') {
 2256:         $context = 'tools';
 2257:     } else {
 2258:         $context = $action;
 2259:     }
 2260:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2261:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2262:     my $typecount = 0;
 2263:     my ($css_class,%titles);
 2264:     if ($context eq 'requestcourses') {
 2265:         @usertools = ('official','unofficial','community','textbook','lti');
 2266:         @options =('norequest','approval','validate','autolimit');
 2267:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2268:         %titles = &courserequest_titles();
 2269:     } elsif ($context eq 'requestauthor') {
 2270:         @usertools = ('author');
 2271:         @options = ('norequest','approval','automatic');
 2272:         %titles = &authorrequest_titles();
 2273:     } else {
 2274:         @usertools = ('aboutme','blog','webdav','portfolio','timezone');
 2275:         %titles = &tool_titles();
 2276:     }
 2277:     if (ref($types) eq 'ARRAY') {
 2278:         foreach my $type (@{$types}) {
 2279:             my ($currdefquota,$currauthorquota);
 2280:             unless (($context eq 'requestcourses') ||
 2281:                     ($context eq 'requestauthor')) {
 2282:                 if (ref($settings) eq 'HASH') {
 2283:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2284:                         $currdefquota = $settings->{defaultquota}->{$type};
 2285:                     } else {
 2286:                         $currdefquota = $settings->{$type};
 2287:                     }
 2288:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2289:                         $currauthorquota = $settings->{authorquota}->{$type};
 2290:                     }
 2291:                 }
 2292:             }
 2293:             if (defined($usertypes->{$type})) {
 2294:                 $typecount ++;
 2295:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2296:                 $datatable .= '<tr'.$css_class.'>'.
 2297:                               '<td>'.$usertypes->{$type}.'</td>'.
 2298:                               '<td class="LC_left_item">';
 2299:                 if ($context eq 'requestcourses') {
 2300:                     $datatable .= '<table><tr>';
 2301:                 }
 2302:                 my %cell;  
 2303:                 foreach my $item (@usertools) {
 2304:                     if ($context eq 'requestcourses') {
 2305:                         my ($curroption,$currlimit);
 2306:                         if (ref($settings) eq 'HASH') {
 2307:                             if (ref($settings->{$item}) eq 'HASH') {
 2308:                                 $curroption = $settings->{$item}->{$type};
 2309:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2310:                                     $currlimit = $1; 
 2311:                                 }
 2312:                             }
 2313:                         }
 2314:                         if (!$curroption) {
 2315:                             $curroption = 'norequest';
 2316:                         }
 2317:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2318:                         foreach my $option (@options) {
 2319:                             my $val = $option;
 2320:                             if ($option eq 'norequest') {
 2321:                                 $val = 0;  
 2322:                             }
 2323:                             if ($option eq 'validate') {
 2324:                                 my $canvalidate = 0;
 2325:                                 if (ref($validations{$item}) eq 'HASH') { 
 2326:                                     if ($validations{$item}{$type}) {
 2327:                                         $canvalidate = 1;
 2328:                                     }
 2329:                                 }
 2330:                                 next if (!$canvalidate);
 2331:                             }
 2332:                             my $checked = '';
 2333:                             if ($option eq $curroption) {
 2334:                                 $checked = ' checked="checked"';
 2335:                             } elsif ($option eq 'autolimit') {
 2336:                                 if ($curroption =~ /^autolimit/) {
 2337:                                     $checked = ' checked="checked"';
 2338:                                 }                       
 2339:                             } 
 2340:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2341:                                   '<input type="radio" name="crsreq_'.$item.
 2342:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2343:                                   $titles{$option}.'</label>';
 2344:                             if ($option eq 'autolimit') {
 2345:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2346:                                                 $item.'_limit_'.$type.'" size="1" '.
 2347:                                                 'value="'.$currlimit.'" />';
 2348:                             }
 2349:                             $cell{$item} .= '</span> ';
 2350:                             if ($option eq 'autolimit') {
 2351:                                 $cell{$item} .= $titles{'unlimited'};
 2352:                             }
 2353:                         }
 2354:                     } elsif ($context eq 'requestauthor') {
 2355:                         my $curroption;
 2356:                         if (ref($settings) eq 'HASH') {
 2357:                             $curroption = $settings->{$type};
 2358:                         }
 2359:                         if (!$curroption) {
 2360:                             $curroption = 'norequest';
 2361:                         }
 2362:                         foreach my $option (@options) {
 2363:                             my $val = $option;
 2364:                             if ($option eq 'norequest') {
 2365:                                 $val = 0;
 2366:                             }
 2367:                             my $checked = '';
 2368:                             if ($option eq $curroption) {
 2369:                                 $checked = ' checked="checked"';
 2370:                             }
 2371:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2372:                                   '<input type="radio" name="authorreq_'.$type.
 2373:                                   '" value="'.$val.'"'.$checked.' />'.
 2374:                                   $titles{$option}.'</label></span>&nbsp; ';
 2375:                         }
 2376:                     } else {
 2377:                         my $checked = 'checked="checked" ';
 2378:                         if ($item eq 'timezone') {
 2379:                             $checked = '';
 2380:                         }
 2381:                         if (ref($settings) eq 'HASH') {
 2382:                             if (ref($settings->{$item}) eq 'HASH') {
 2383:                                 if (!$settings->{$item}->{$type}) {
 2384:                                     $checked = '';
 2385:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2386:                                     $checked =  'checked="checked" ';
 2387:                                 }
 2388:                             }
 2389:                         }
 2390:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2391:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2392:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2393:                                       '</label></span>&nbsp; ';
 2394:                     }
 2395:                 }
 2396:                 if ($context eq 'requestcourses') {
 2397:                     $datatable .= '</tr><tr>';
 2398:                     foreach my $item (@usertools) {
 2399:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2400:                     }
 2401:                     $datatable .= '</tr></table>';
 2402:                 }
 2403:                 $datatable .= '</td>';
 2404:                 unless (($context eq 'requestcourses') ||
 2405:                         ($context eq 'requestauthor')) {
 2406:                     $datatable .= 
 2407:                               '<td class="LC_right_item">'.
 2408:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2409:                               '<input type="text" name="quota_'.$type.
 2410:                               '" value="'.$currdefquota.
 2411:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2412:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2413:                               '<input type="text" name="authorquota_'.$type.
 2414:                               '" value="'.$currauthorquota.
 2415:                               '" size="5" /></span></td>';
 2416:                 }
 2417:                 $datatable .= '</tr>';
 2418:             }
 2419:         }
 2420:     }
 2421:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2422:         $defaultquota = '20';
 2423:         $authorquota = '500';
 2424:         if (ref($settings) eq 'HASH') {
 2425:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2426:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2427:             } elsif (defined($settings->{'default'})) {
 2428:                 $defaultquota = $settings->{'default'};
 2429:             }
 2430:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2431:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2432:             }
 2433:         }
 2434:     }
 2435:     $typecount ++;
 2436:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2437:     $datatable .= '<tr'.$css_class.'>'.
 2438:                   '<td>'.$othertitle.'</td>'.
 2439:                   '<td class="LC_left_item">';
 2440:     if ($context eq 'requestcourses') {
 2441:         $datatable .= '<table><tr>';
 2442:     }
 2443:     my %defcell;
 2444:     foreach my $item (@usertools) {
 2445:         if ($context eq 'requestcourses') {
 2446:             my ($curroption,$currlimit);
 2447:             if (ref($settings) eq 'HASH') {
 2448:                 if (ref($settings->{$item}) eq 'HASH') {
 2449:                     $curroption = $settings->{$item}->{'default'};
 2450:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2451:                         $currlimit = $1;
 2452:                     }
 2453:                 }
 2454:             }
 2455:             if (!$curroption) {
 2456:                 $curroption = 'norequest';
 2457:             }
 2458:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2459:             foreach my $option (@options) {
 2460:                 my $val = $option;
 2461:                 if ($option eq 'norequest') {
 2462:                     $val = 0;
 2463:                 }
 2464:                 if ($option eq 'validate') {
 2465:                     my $canvalidate = 0;
 2466:                     if (ref($validations{$item}) eq 'HASH') {
 2467:                         if ($validations{$item}{'default'}) {
 2468:                             $canvalidate = 1;
 2469:                         }
 2470:                     }
 2471:                     next if (!$canvalidate);
 2472:                 }
 2473:                 my $checked = '';
 2474:                 if ($option eq $curroption) {
 2475:                     $checked = ' checked="checked"';
 2476:                 } elsif ($option eq 'autolimit') {
 2477:                     if ($curroption =~ /^autolimit/) {
 2478:                         $checked = ' checked="checked"';
 2479:                     }
 2480:                 }
 2481:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2482:                                   '<input type="radio" name="crsreq_'.$item.
 2483:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2484:                                   $titles{$option}.'</label>';
 2485:                 if ($option eq 'autolimit') {
 2486:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2487:                                        $item.'_limit_default" size="1" '.
 2488:                                        'value="'.$currlimit.'" />';
 2489:                 }
 2490:                 $defcell{$item} .= '</span> ';
 2491:                 if ($option eq 'autolimit') {
 2492:                     $defcell{$item} .= $titles{'unlimited'};
 2493:                 }
 2494:             }
 2495:         } elsif ($context eq 'requestauthor') {
 2496:             my $curroption;
 2497:             if (ref($settings) eq 'HASH') {
 2498:                 $curroption = $settings->{'default'};
 2499:             }
 2500:             if (!$curroption) {
 2501:                 $curroption = 'norequest';
 2502:             }
 2503:             foreach my $option (@options) {
 2504:                 my $val = $option;
 2505:                 if ($option eq 'norequest') {
 2506:                     $val = 0;
 2507:                 }
 2508:                 my $checked = '';
 2509:                 if ($option eq $curroption) {
 2510:                     $checked = ' checked="checked"';
 2511:                 }
 2512:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2513:                               '<input type="radio" name="authorreq_default"'.
 2514:                               ' value="'.$val.'"'.$checked.' />'.
 2515:                               $titles{$option}.'</label></span>&nbsp; ';
 2516:             }
 2517:         } else {
 2518:             my $checked = 'checked="checked" ';
 2519:             if (ref($settings) eq 'HASH') {
 2520:                 if (ref($settings->{$item}) eq 'HASH') {
 2521:                     if ($settings->{$item}->{'default'} == 0) {
 2522:                         $checked = '';
 2523:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2524:                         $checked = 'checked="checked" ';
 2525:                     }
 2526:                 }
 2527:             }
 2528:             $datatable .= '<span class="LC_nobreak"><label>'.
 2529:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2530:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2531:                           '</label></span>&nbsp; ';
 2532:         }
 2533:     }
 2534:     if ($context eq 'requestcourses') {
 2535:         $datatable .= '</tr><tr>';
 2536:         foreach my $item (@usertools) {
 2537:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2538:         }
 2539:         $datatable .= '</tr></table>';
 2540:     }
 2541:     $datatable .= '</td>';
 2542:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2543:         $datatable .= '<td class="LC_right_item">'.
 2544:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2545:                       '<input type="text" name="defaultquota" value="'.
 2546:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2547:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2548:                       '<input type="text" name="authorquota" value="'.
 2549:                       $authorquota.'" size="5" /></span></td>';
 2550:     }
 2551:     $datatable .= '</tr>';
 2552:     $typecount ++;
 2553:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2554:     $datatable .= '<tr'.$css_class.'>'.
 2555:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2556:     if ($context eq 'requestcourses') {
 2557:         $datatable .= &mt('(overrides affiliation, if set)').
 2558:                       '</td>'.
 2559:                       '<td class="LC_left_item">'.
 2560:                       '<table><tr>';
 2561:     } else {
 2562:         $datatable .= &mt('(overrides affiliation, if checked)').
 2563:                       '</td>'.
 2564:                       '<td class="LC_left_item" colspan="2">'.
 2565:                       '<br />';
 2566:     }
 2567:     my %advcell;
 2568:     foreach my $item (@usertools) {
 2569:         if ($context eq 'requestcourses') {
 2570:             my ($curroption,$currlimit);
 2571:             if (ref($settings) eq 'HASH') {
 2572:                 if (ref($settings->{$item}) eq 'HASH') {
 2573:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2574:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2575:                         $currlimit = $1;
 2576:                     }
 2577:                 }
 2578:             }
 2579:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2580:             my $checked = '';
 2581:             if ($curroption eq '') {
 2582:                 $checked = ' checked="checked"';
 2583:             }
 2584:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2585:                                '<input type="radio" name="crsreq_'.$item.
 2586:                                '__LC_adv" value=""'.$checked.' />'.
 2587:                                &mt('No override set').'</label></span>&nbsp; ';
 2588:             foreach my $option (@options) {
 2589:                 my $val = $option;
 2590:                 if ($option eq 'norequest') {
 2591:                     $val = 0;
 2592:                 }
 2593:                 if ($option eq 'validate') {
 2594:                     my $canvalidate = 0;
 2595:                     if (ref($validations{$item}) eq 'HASH') {
 2596:                         if ($validations{$item}{'_LC_adv'}) {
 2597:                             $canvalidate = 1;
 2598:                         }
 2599:                     }
 2600:                     next if (!$canvalidate);
 2601:                 }
 2602:                 my $checked = '';
 2603:                 if ($val eq $curroption) {
 2604:                     $checked = ' checked="checked"';
 2605:                 } elsif ($option eq 'autolimit') {
 2606:                     if ($curroption =~ /^autolimit/) {
 2607:                         $checked = ' checked="checked"';
 2608:                     }
 2609:                 }
 2610:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2611:                                   '<input type="radio" name="crsreq_'.$item.
 2612:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2613:                                   $titles{$option}.'</label>';
 2614:                 if ($option eq 'autolimit') {
 2615:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2616:                                        $item.'_limit__LC_adv" size="1" '.
 2617:                                        'value="'.$currlimit.'" />';
 2618:                 }
 2619:                 $advcell{$item} .= '</span> ';
 2620:                 if ($option eq 'autolimit') {
 2621:                     $advcell{$item} .= $titles{'unlimited'};
 2622:                 }
 2623:             }
 2624:         } elsif ($context eq 'requestauthor') {
 2625:             my $curroption;
 2626:             if (ref($settings) eq 'HASH') {
 2627:                 $curroption = $settings->{'_LC_adv'};
 2628:             }
 2629:             my $checked = '';
 2630:             if ($curroption eq '') {
 2631:                 $checked = ' checked="checked"';
 2632:             }
 2633:             $datatable .= '<span class="LC_nobreak"><label>'.
 2634:                           '<input type="radio" name="authorreq__LC_adv"'.
 2635:                           ' value=""'.$checked.' />'.
 2636:                           &mt('No override set').'</label></span>&nbsp; ';
 2637:             foreach my $option (@options) {
 2638:                 my $val = $option;
 2639:                 if ($option eq 'norequest') {
 2640:                     $val = 0;
 2641:                 }
 2642:                 my $checked = '';
 2643:                 if ($val eq $curroption) {
 2644:                     $checked = ' checked="checked"';
 2645:                 }
 2646:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2647:                               '<input type="radio" name="authorreq__LC_adv"'.
 2648:                               ' value="'.$val.'"'.$checked.' />'.
 2649:                               $titles{$option}.'</label></span>&nbsp; ';
 2650:             }
 2651:         } else {
 2652:             my $checked = 'checked="checked" ';
 2653:             if (ref($settings) eq 'HASH') {
 2654:                 if (ref($settings->{$item}) eq 'HASH') {
 2655:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2656:                         $checked = '';
 2657:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2658:                         $checked = 'checked="checked" ';
 2659:                     }
 2660:                 }
 2661:             }
 2662:             $datatable .= '<span class="LC_nobreak"><label>'.
 2663:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2664:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2665:                           '</label></span>&nbsp; ';
 2666:         }
 2667:     }
 2668:     if ($context eq 'requestcourses') {
 2669:         $datatable .= '</tr><tr>';
 2670:         foreach my $item (@usertools) {
 2671:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2672:         }
 2673:         $datatable .= '</tr></table>';
 2674:     }
 2675:     $datatable .= '</td></tr>';
 2676:     $$rowtotal += $typecount;
 2677:     return $datatable;
 2678: }
 2679: 
 2680: sub print_requestmail {
 2681:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2682:     my ($now,$datatable,%currapp);
 2683:     $now = time;
 2684:     if (ref($settings) eq 'HASH') {
 2685:         if (ref($settings->{'notify'}) eq 'HASH') {
 2686:             if ($settings->{'notify'}{'approval'} ne '') {
 2687:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2688:             }
 2689:         }
 2690:     }
 2691:     my $numinrow = 2;
 2692:     my $css_class;
 2693:     if ($$rowtotal%2) {
 2694:         $css_class = 'LC_odd_row';
 2695:     }
 2696:     if ($customcss) {
 2697:         $css_class .= " $customcss";
 2698:     }
 2699:     $css_class =~ s/^\s+//;
 2700:     if ($css_class) {
 2701:         $css_class = ' class="'.$css_class.'"';
 2702:     }
 2703:     if ($rowstyle) {
 2704:         $css_class .= ' style="'.$rowstyle.'"';
 2705:     }
 2706:     my $text;
 2707:     if ($action eq 'requestcourses') {
 2708:         $text = &mt('Receive notification of course requests requiring approval');
 2709:     } elsif ($action eq 'requestauthor') {
 2710:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2711:     } else {
 2712:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2713:     }
 2714:     $datatable = '<tr'.$css_class.'>'.
 2715:                  ' <td>'.$text.'</td>'.
 2716:                  ' <td class="LC_left_item">';
 2717:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2718:                                                  $action.'notifyapproval',%currapp);
 2719:     if ($numdc > 0) {
 2720:         $datatable .= $table;
 2721:     } else {
 2722:         $datatable .= &mt('There are no active Domain Coordinators');
 2723:     }
 2724:     $datatable .='</td></tr>';
 2725:     return $datatable;
 2726: }
 2727: 
 2728: sub print_studentcode {
 2729:     my ($settings,$rowtotal) = @_;
 2730:     my $rownum = 0; 
 2731:     my ($output,%current);
 2732:     my @crstypes = ('official','unofficial','community','textbook','lti');
 2733:     if (ref($settings) eq 'HASH') {
 2734:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2735:             foreach my $type (@crstypes) {
 2736:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2737:             }
 2738:         }
 2739:     }
 2740:     $output .= '<tr>'.
 2741:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2742:                '<td class="LC_left_item">';
 2743:     foreach my $type (@crstypes) {
 2744:         my $check = ' ';
 2745:         if ($current{$type}) {
 2746:             $check = ' checked="checked" ';
 2747:         }
 2748:         $output .= '<span class="LC_nobreak"><label>'.
 2749:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2750:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2751:     }
 2752:     $output .= '</td></tr>';
 2753:     $$rowtotal ++;
 2754:     return $output;
 2755: }
 2756: 
 2757: sub print_textbookcourses {
 2758:     my ($dom,$type,$settings,$rowtotal) = @_;
 2759:     my $rownum = 0;
 2760:     my $css_class;
 2761:     my $itemcount = 1;
 2762:     my $maxnum = 0;
 2763:     my $bookshash;
 2764:     if (ref($settings) eq 'HASH') {
 2765:         $bookshash = $settings->{$type};
 2766:     }
 2767:     my %ordered;
 2768:     if (ref($bookshash) eq 'HASH') {
 2769:         foreach my $item (keys(%{$bookshash})) {
 2770:             if (ref($bookshash->{$item}) eq 'HASH') {
 2771:                 my $num = $bookshash->{$item}{'order'};
 2772:                 $ordered{$num} = $item;
 2773:             }
 2774:         }
 2775:     }
 2776:     my $confname = $dom.'-domainconfig';
 2777:     my $switchserver = &check_switchserver($dom,$confname);
 2778:     my $maxnum = scalar(keys(%ordered));
 2779:     my $datatable;
 2780:     if (keys(%ordered)) {
 2781:         my @items = sort { $a <=> $b } keys(%ordered);
 2782:         for (my $i=0; $i<@items; $i++) {
 2783:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2784:             my $key = $ordered{$items[$i]};
 2785:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2786:             my $coursetitle = $coursehash{'description'};
 2787:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2788:             if (ref($bookshash->{$key}) eq 'HASH') {
 2789:                 $subject = $bookshash->{$key}->{'subject'};
 2790:                 $title = $bookshash->{$key}->{'title'};
 2791:                 if ($type eq 'textbooks') {
 2792:                     $publisher = $bookshash->{$key}->{'publisher'};
 2793:                     $author = $bookshash->{$key}->{'author'};
 2794:                     $image = $bookshash->{$key}->{'image'};
 2795:                     if ($image ne '') {
 2796:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2797:                         my $imagethumb = "$path/tn-".$imagefile;
 2798:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2799:                     }
 2800:                 }
 2801:             }
 2802:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2803:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2804:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2805:             for (my $k=0; $k<=$maxnum; $k++) {
 2806:                 my $vpos = $k+1;
 2807:                 my $selstr;
 2808:                 if ($k == $i) {
 2809:                     $selstr = ' selected="selected" ';
 2810:                 }
 2811:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2812:             }
 2813:             $datatable .= '</select>'.('&nbsp;'x2).
 2814:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2815:                 &mt('Delete?').'</label></span></td>'.
 2816:                 '<td colspan="2">'.
 2817:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2818:                 ('&nbsp;'x2).
 2819:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2820:             if ($type eq 'textbooks') {
 2821:                 $datatable .= ('&nbsp;'x2).
 2822:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2823:                               ('&nbsp;'x2).
 2824:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2825:                               ('&nbsp;'x2).
 2826:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2827:                 if ($image) {
 2828:                     $datatable .= $imgsrc.
 2829:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2830:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2831:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2832:                 }
 2833:                 if ($switchserver) {
 2834:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2835:                 } else {
 2836:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2837:                 }
 2838:             }
 2839:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2840:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2841:                           $coursetitle.'</span></td></tr>'."\n";
 2842:             $itemcount ++;
 2843:         }
 2844:     }
 2845:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2846:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2847:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2848:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2849:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2850:     for (my $k=0; $k<$maxnum+1; $k++) {
 2851:         my $vpos = $k+1;
 2852:         my $selstr;
 2853:         if ($k == $maxnum) {
 2854:             $selstr = ' selected="selected" ';
 2855:         }
 2856:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2857:     }
 2858:     $datatable .= '</select>&nbsp;'."\n".
 2859:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2860:                   '<td colspan="2">'.
 2861:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2862:                   ('&nbsp;'x2).
 2863:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2864:                   ('&nbsp;'x2);
 2865:     if ($type eq 'textbooks') {
 2866:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2867:                       ('&nbsp;'x2).
 2868:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2869:                       ('&nbsp;'x2).
 2870:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2871:         if ($switchserver) {
 2872:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2873:         } else {
 2874:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2875:         }
 2876:         $datatable .= '</span>'."\n";
 2877:     }
 2878:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2879:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2880:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2881:                   &Apache::loncommon::selectcourse_link
 2882:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2883:                   '</span></td>'."\n".
 2884:                   '</tr>'."\n";
 2885:     $itemcount ++;
 2886:     return $datatable;
 2887: }
 2888: 
 2889: sub textbookcourses_javascript {
 2890:     my ($settings) = @_;
 2891:     return unless(ref($settings) eq 'HASH');
 2892:     my (%ordered,%total,%jstext);
 2893:     foreach my $type ('textbooks','templates') {
 2894:         $total{$type} = 0;
 2895:         if (ref($settings->{$type}) eq 'HASH') {
 2896:             foreach my $item (keys(%{$settings->{$type}})) {
 2897:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2898:                     my $num = $settings->{$type}->{$item}{'order'};
 2899:                     $ordered{$type}{$num} = $item;
 2900:                 }
 2901:             }
 2902:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2903:         }
 2904:         my @jsarray = ();
 2905:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2906:             push(@jsarray,$ordered{$type}{$item});
 2907:         }
 2908:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2909:     }
 2910:     return <<"ENDSCRIPT";
 2911: <script type="text/javascript">
 2912: // <![CDATA[
 2913: function reorderBooks(form,item,caller) {
 2914:     var changedVal;
 2915: $jstext{'textbooks'};
 2916: $jstext{'templates'};
 2917:     var newpos;
 2918:     var maxh;
 2919:     if (caller == 'textbooks') {  
 2920:         newpos = 'textbooks_addbook_pos';
 2921:         maxh = 1 + $total{'textbooks'};
 2922:     } else {
 2923:         newpos = 'templates_addbook_pos';
 2924:         maxh = 1 + $total{'templates'};
 2925:     }
 2926:     var current = new Array;
 2927:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2928:     if (item == newpos) {
 2929:         changedVal = newitemVal;
 2930:     } else {
 2931:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2932:         current[newitemVal] = newpos;
 2933:     }
 2934:     if (caller == 'textbooks') {
 2935:         for (var i=0; i<textbooks.length; i++) {
 2936:             var elementName = 'textbooks_'+textbooks[i];
 2937:             if (elementName != item) {
 2938:                 if (form.elements[elementName]) {
 2939:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2940:                     current[currVal] = elementName;
 2941:                 }
 2942:             }
 2943:         }
 2944:     }
 2945:     if (caller == 'templates') {
 2946:         for (var i=0; i<templates.length; i++) {
 2947:             var elementName = 'templates_'+templates[i];
 2948:             if (elementName != item) {
 2949:                 if (form.elements[elementName]) {
 2950:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2951:                     current[currVal] = elementName;
 2952:                 }
 2953:             }
 2954:         }
 2955:     }
 2956:     var oldVal;
 2957:     for (var j=0; j<maxh; j++) {
 2958:         if (current[j] == undefined) {
 2959:             oldVal = j;
 2960:         }
 2961:     }
 2962:     if (oldVal < changedVal) {
 2963:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2964:            var elementName = current[k];
 2965:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2966:         }
 2967:     } else {
 2968:         for (var k=changedVal; k<oldVal; k++) {
 2969:             var elementName = current[k];
 2970:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2971:         }
 2972:     }
 2973:     return;
 2974: }
 2975: 
 2976: // ]]>
 2977: </script>
 2978: 
 2979: ENDSCRIPT
 2980: }
 2981: 
 2982: sub ltitools_javascript {
 2983:     my ($settings) = @_;
 2984:     my $togglejs = &ltitools_toggle_js();
 2985:     unless (ref($settings) eq 'HASH') {
 2986:         return $togglejs;
 2987:     }
 2988:     my (%ordered,$total,%jstext);
 2989:     $total = 0;
 2990:     foreach my $item (keys(%{$settings})) {
 2991:         if (ref($settings->{$item}) eq 'HASH') {
 2992:             my $num = $settings->{$item}{'order'};
 2993:             $ordered{$num} = $item;
 2994:         }
 2995:     }
 2996:     $total = scalar(keys(%{$settings}));
 2997:     my @jsarray = ();
 2998:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2999:         push(@jsarray,$ordered{$item});
 3000:     }
 3001:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 3002:     return <<"ENDSCRIPT";
 3003: <script type="text/javascript">
 3004: // <![CDATA[
 3005: function reorderLTITools(form,item) {
 3006:     var changedVal;
 3007: $jstext
 3008:     var newpos = 'ltitools_add_pos';
 3009:     var maxh = 1 + $total;
 3010:     var current = new Array;
 3011:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3012:     if (item == newpos) {
 3013:         changedVal = newitemVal;
 3014:     } else {
 3015:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3016:         current[newitemVal] = newpos;
 3017:     }
 3018:     for (var i=0; i<ltitools.length; i++) {
 3019:         var elementName = 'ltitools_'+ltitools[i];
 3020:         if (elementName != item) {
 3021:             if (form.elements[elementName]) {
 3022:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3023:                 current[currVal] = elementName;
 3024:             }
 3025:         }
 3026:     }
 3027:     var oldVal;
 3028:     for (var j=0; j<maxh; j++) {
 3029:         if (current[j] == undefined) {
 3030:             oldVal = j;
 3031:         }
 3032:     }
 3033:     if (oldVal < changedVal) {
 3034:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3035:            var elementName = current[k];
 3036:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3037:         }
 3038:     } else {
 3039:         for (var k=changedVal; k<oldVal; k++) {
 3040:             var elementName = current[k];
 3041:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3042:         }
 3043:     }
 3044:     return;
 3045: }
 3046: 
 3047: // ]]>
 3048: </script>
 3049: 
 3050: $togglejs
 3051: 
 3052: ENDSCRIPT
 3053: }
 3054: 
 3055: sub ltitools_toggle_js {
 3056:     return <<"ENDSCRIPT";
 3057: <script type="text/javascript">
 3058: // <![CDATA[
 3059: 
 3060: function toggleLTITools(form,setting,item) {
 3061:     var radioname = '';
 3062:     var divid = '';
 3063:     if ((setting == 'passback') || (setting == 'roster')) {
 3064:         radioname = 'ltitools_'+setting+'_'+item;
 3065:         divid = 'ltitools_'+setting+'time_'+item;
 3066:         var num = form.elements[radioname].length;
 3067:         if (num) {
 3068:             var setvis = '';
 3069:             for (var i=0; i<num; i++) {
 3070:                 if (form.elements[radioname][i].checked) {
 3071:                     if (form.elements[radioname][i].value == '1') {
 3072:                         if (document.getElementById(divid)) {
 3073:                             document.getElementById(divid).style.display = 'inline-block';
 3074:                         }
 3075:                         setvis = 1;
 3076:                     }
 3077:                     break;
 3078:                 }
 3079:             }
 3080:         }
 3081:         if (!setvis) {
 3082:             if (document.getElementById(divid)) {
 3083:                 document.getElementById(divid).style.display = 'none';
 3084:             }
 3085:         }
 3086:     }
 3087:     if (setting == 'user') {
 3088:         divid = 'ltitools_'+setting+'_div_'+item;
 3089:         var checkid = 'ltitools_'+setting+'_field_'+item;
 3090:         if (document.getElementById(divid)) {
 3091:             if (document.getElementById(checkid)) {
 3092:                 if (document.getElementById(checkid).checked) {
 3093:                     document.getElementById(divid).style.display = 'inline-block';
 3094:                 } else {
 3095:                     document.getElementById(divid).style.display = 'none';
 3096:                 }
 3097:             }
 3098:         }
 3099:     }
 3100:     return;
 3101: }
 3102: // ]]>
 3103: </script>
 3104: 
 3105: ENDSCRIPT
 3106: }
 3107: 
 3108: sub wafproxy_javascript {
 3109:     my ($dom) = @_;
 3110:     return <<"ENDSCRIPT";
 3111: <script type="text/javascript">
 3112: // <![CDATA[
 3113: function updateWAF() {
 3114:     if (document.getElementById('wafproxy_remoteip')) {
 3115:         var wafremote = 0;
 3116:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 3117:             wafremote = 1;
 3118:         }
 3119:         var fields = new Array('header','trust');
 3120:         for (var i=0; i<fields.length; i++) {
 3121:             if (document.getElementById('wafproxy_'+fields[i])) {
 3122:                 if (wafremote == 1) {
 3123:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 3124:                 }
 3125:                 else {
 3126:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 3127:                 }
 3128:             }
 3129:         }
 3130:         if (document.getElementById('wafproxyranges_$dom')) {
 3131:             if (wafremote == 1) {
 3132:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3133:             } else {
 3134:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3135:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 3136:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 3137:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3138:                         }
 3139:                     }
 3140:                 }
 3141:             }
 3142:         }
 3143:     }
 3144:     return;
 3145: }
 3146: 
 3147: function checkWAF() {
 3148:     if (document.getElementById('wafproxy_remoteip')) {
 3149:         var wafvpn = 0;
 3150:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3151:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3152:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3153:                     wafvpn = 1;
 3154:                 }
 3155:                 break;
 3156:             }
 3157:         }
 3158:         var vpn = new Array('vpnint','vpnext');
 3159:         for (var i=0; i<vpn.length; i++) {
 3160:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3161:                 if (wafvpn == 1) {
 3162:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3163:                 }
 3164:                 else {
 3165:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3166:                 }
 3167:             }
 3168:         }
 3169:         if (document.getElementById('wafproxyranges_$dom')) {
 3170:             if (wafvpn == 1) {
 3171:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3172:             }
 3173:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3174:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3175:             }
 3176:         }
 3177:     }
 3178:     return;
 3179: }
 3180: 
 3181: function toggleWAF() {
 3182:     if (document.getElementById('wafproxy_table')) {
 3183:         var wafproxy = 0;
 3184:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3185:              if (document.display.wafproxy_${dom}[i].checked) {
 3186:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3187:                      wafproxy = 1;
 3188:                      break;
 3189:                 }
 3190:             }
 3191:         }
 3192:         if (wafproxy == 1) {
 3193:             document.getElementById('wafproxy_table').style.display='inline';
 3194:         }
 3195:         else {
 3196:            document.getElementById('wafproxy_table').style.display='none';
 3197:         }
 3198:         if (document.getElementById('wafproxyrow_${dom}')) {
 3199:             if (wafproxy == 1) {
 3200:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3201:             }
 3202:             else {
 3203:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3204:             }
 3205:         }
 3206:         if (document.getElementById('nowafproxyrow_$dom')) {
 3207:             if (wafproxy == 1) {
 3208:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3209:             }
 3210:             else {
 3211:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3212:             }
 3213:         }
 3214:     }
 3215:     return;
 3216: }
 3217: // ]]>
 3218: </script>
 3219: 
 3220: ENDSCRIPT
 3221: }
 3222: 
 3223: sub lti_javascript {
 3224:     my ($dom,$settings) = @_;
 3225:     my $togglejs = &lti_toggle_js($dom);
 3226:     my $linkprot_js = &Apache::courseprefs::linkprot_javascript();
 3227:     unless (ref($settings) eq 'HASH') {
 3228:         return $togglejs.'
 3229: <script type="text/javascript">
 3230: // <![CDATA[
 3231: 
 3232: '.$linkprot_js.'
 3233: 
 3234: // ]]>
 3235: </script>
 3236: ';
 3237:     }
 3238:     my (%ordered,$total,%jstext);
 3239:     $total = scalar(keys(%{$settings}));
 3240:     foreach my $item (keys(%{$settings})) {
 3241:         if (ref($settings->{$item}) eq 'HASH') {
 3242:             my $num = $settings->{$item}{'order'};
 3243:             if ($num eq '') {
 3244:                 $num = $total - 1;
 3245:             }
 3246:             $ordered{$num} = $item;
 3247:         }
 3248:     }
 3249:     my @jsarray = ();
 3250:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3251:         push(@jsarray,$ordered{$item});
 3252:     }
 3253:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3254:     return <<"ENDSCRIPT";
 3255: <script type="text/javascript">
 3256: // <![CDATA[
 3257: function reorderLTI(form,item) {
 3258:     var changedVal;
 3259: $jstext
 3260:     var newpos = 'lti_pos_add';
 3261:     var maxh = 1 + $total;
 3262:     var current = new Array;
 3263:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3264:     if (item == newpos) {
 3265:         changedVal = newitemVal;
 3266:     } else {
 3267:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3268:         current[newitemVal] = newpos;
 3269:     }
 3270:     for (var i=0; i<lti.length; i++) {
 3271:         var elementName = 'lti_pos_'+lti[i];
 3272:         if (elementName != item) {
 3273:             if (form.elements[elementName]) {
 3274:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3275:                 current[currVal] = elementName;
 3276:             }
 3277:         }
 3278:     }
 3279:     var oldVal;
 3280:     for (var j=0; j<maxh; j++) {
 3281:         if (current[j] == undefined) {
 3282:             oldVal = j;
 3283:         }
 3284:     }
 3285:     if (oldVal < changedVal) {
 3286:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3287:            var elementName = current[k];
 3288:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3289:         }
 3290:     } else {
 3291:         for (var k=changedVal; k<oldVal; k++) {
 3292:             var elementName = current[k];
 3293:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3294:         }
 3295:     }
 3296:     return;
 3297: }
 3298: 
 3299: $linkprot_js
 3300: 
 3301: // ]]>
 3302: </script>
 3303: 
 3304: $togglejs
 3305: 
 3306: ENDSCRIPT
 3307: }
 3308: 
 3309: sub lti_toggle_js {
 3310:     my ($dom) = @_;
 3311:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3312:                             localauth => 'Local auth argument',
 3313:                             krb       => 'Kerberos domain',
 3314:                          );
 3315:     my $crsincalert = &mt('"User\'s identity sent" needs to be set to "Yes" first,[_1] before setting "Course\'s identity sent" to "Yes"',"\n");
 3316:     &js_escape(\$crsincalert);
 3317:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 3318:     my $primary = &Apache::lonnet::domain($dom,'primary');
 3319:     my $course_servers = "'".join("','",keys(%servers))."'";
 3320:     return <<"ENDSCRIPT";
 3321: <script type="text/javascript">
 3322: // <![CDATA[
 3323: 
 3324: function toggleLTI(form,setting,item) {
 3325:     if ((setting == 'requser') || (setting == 'crsinc')) {
 3326:         var usrfieldsets = document.getElementsByClassName('ltioption_usr_'+item);
 3327:         var setvis = '';
 3328:         var radioname = 'lti_requser_'+item;
 3329:         var num = form.elements[radioname].length;
 3330:         if (num) {
 3331:             for (var i=0; i<num; i++) {
 3332:                 if (form.elements[radioname][i].checked) {
 3333:                     if (form.elements[radioname][i].value == '1') {
 3334:                         setvis = 1;
 3335:                         break;
 3336:                     }
 3337:                 }
 3338:             }
 3339:         }
 3340:         if (usrfieldsets.length) {
 3341:             for (var j=0; j<usrfieldsets.length; j++) {
 3342:                 if (setvis) {
 3343:                     usrfieldsets[j].style.display = 'block';
 3344:                 } else {
 3345:                     usrfieldsets[j].style.display = 'none';
 3346:                 }
 3347:             }
 3348:         }
 3349:         var crsfieldsets = document.getElementsByClassName('ltioption_crs_'+item);
 3350:         if (crsfieldsets.length) {
 3351:             radioname = 'lti_crsinc_'+item;
 3352:             var num = form.elements[radioname].length;
 3353:             if (num) {
 3354:                 var crsvis = '';
 3355:                 for (var i=0; i<num; i++) {
 3356:                     if (form.elements[radioname][i].checked) {
 3357:                         if (form.elements[radioname][i].value == '1') {
 3358:                             if (setvis == '') {
 3359:                                 if (setting == 'crsinc'){
 3360:                                     alert("$crsincalert");
 3361:                                     form.elements[radioname][0].checked = true;
 3362:                                 }
 3363:                             } else {
 3364:                                 crsvis = 1;
 3365:                             }
 3366:                             break;
 3367:                         }
 3368:                     }
 3369:                 }
 3370:                 setvis = crsvis;
 3371:             }
 3372:             for (var j=0; j<crsfieldsets.length; j++) {
 3373:                 if (setvis) {
 3374:                     crsfieldsets[j].style.display = 'block';
 3375:                 } else {
 3376:                     crsfieldsets[j].style.display = 'none';
 3377:                 }
 3378:             }
 3379:         }
 3380:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3381:         var radioname = '';
 3382:         var divid = '';
 3383:         if (setting == 'user') {
 3384:             radioname = 'lti_mapuser_'+item;
 3385:             divid = 'lti_userfield_'+item;
 3386:         } else if (setting == 'crs') {
 3387:             radioname = 'lti_mapcrs_'+item;
 3388:             divid = 'lti_crsfield_'+item;
 3389:         } else if (setting == 'callback') {
 3390:             radioname = 'lti_callback_'+item;
 3391:             divid = 'lti_callbackfield_'+item;
 3392:         } else {
 3393:             radioname = 'lti_passback_'+item;
 3394:             divid =  'lti_passback_'+item;
 3395:         }
 3396:         var num = form.elements[radioname].length;
 3397:         if (num) {
 3398:             var setvis = '';
 3399:             for (var i=0; i<num; i++) {
 3400:                if (form.elements[radioname][i].checked) {
 3401:                    if ((setting == 'passback') || (setting == 'callback')) {
 3402:                        if (form.elements[radioname][i].value == '1') {
 3403:                            if (document.getElementById(divid)) {
 3404:                                document.getElementById(divid).style.display = 'inline-block';
 3405:                            }
 3406:                            setvis = 1;
 3407:                            break;
 3408:                        }
 3409:                    } else {
 3410:                        if (form.elements[radioname][i].value == 'other') {
 3411:                            if (document.getElementById(divid)) {
 3412:                                document.getElementById(divid).style.display = 'inline-block';
 3413:                            }
 3414:                            setvis = 1;
 3415:                            break;
 3416:                        }
 3417:                    }
 3418:                }
 3419:             }
 3420:             if (!setvis) {
 3421:                 if (document.getElementById(divid)) {
 3422:                     document.getElementById(divid).style.display = 'none';
 3423:                 }
 3424:             }
 3425:         }
 3426:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3427:         var numsec = form.elements['lti_crssec_'+item].length;
 3428:         if (numsec) {
 3429:             var setvis = '';
 3430:             for (var i=0; i<numsec; i++) {
 3431:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3432:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3433:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3434:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3435:                             setvis = 1;
 3436:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3437:                             if (numsrcsec) {
 3438:                                 var setsrcvis = '';
 3439:                                 for (var j=0; j<numsrcsec; j++) {
 3440:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3441:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3442:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3443:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3444:                                                 setsrcvis = 1;
 3445:                                             }
 3446:                                         }
 3447:                                     }
 3448:                                 }
 3449:                                 if (!setsrcvis) {
 3450:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3451:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3452:                                     }
 3453:                                 }
 3454:                             }
 3455:                         }
 3456:                     }
 3457:                 }
 3458:             }
 3459:             if (!setvis) {
 3460:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3461:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3462:                 }
 3463:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3464:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3465:                 }
 3466:             }
 3467:         }
 3468:     } else if (setting == 'lcauth') {
 3469:         var numauth = form.elements['lti_lcauth_'+item].length;
 3470:         if (numauth) {
 3471:             for (var i=0; i<numauth; i++) {
 3472:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3473:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3474:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3475:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3476:                         } else {
 3477:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3478:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3479:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3480:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3481:                                 } else {
 3482:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3483:                                 }
 3484:                             }
 3485:                         }
 3486:                     }
 3487:                 }
 3488:             }
 3489:         }
 3490:     } else if (setting == 'lcmenu') {
 3491:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3492:         var divid = 'lti_menufield_'+item;
 3493:         var setvis = '';
 3494:         for (var i=0; i<menus.length; i++) {
 3495:             var radioname = menus[i];
 3496:             var num = form.elements[radioname].length;
 3497:             if (num) {
 3498:                 for (var j=0; j<num; j++) {
 3499:                     if (form.elements[radioname][j].checked) {
 3500:                         if (form.elements[radioname][j].value == '1') {
 3501:                             if (document.getElementById(divid)) {
 3502:                                 document.getElementById(divid).style.display = 'inline-block';
 3503:                             }
 3504:                             setvis = 1;
 3505:                             break;
 3506:                         }
 3507:                     }
 3508:                 }
 3509:             }
 3510:             if (setvis == 1) {
 3511:                 break;
 3512:             }
 3513:         }
 3514:         if (!setvis) {
 3515:             if (document.getElementById(divid)) {
 3516:                 document.getElementById(divid).style.display = 'none';
 3517:             }
 3518:         }
 3519:     }
 3520:     return;
 3521: }
 3522: 
 3523: // ]]>
 3524: </script>
 3525: 
 3526: ENDSCRIPT
 3527: }
 3528: 
 3529: sub autoupdate_javascript {
 3530:     return <<"ENDSCRIPT";
 3531: <script type="text/javascript">
 3532: // <![CDATA[
 3533: function toggleLastActiveDays(form) {
 3534:     var radioname = 'lastactive';
 3535:     var divid = 'lastactive_div';
 3536:     var num = form.elements[radioname].length;
 3537:     if (num) {
 3538:         var setvis = '';
 3539:         for (var i=0; i<num; i++) {
 3540:             if (form.elements[radioname][i].checked) {
 3541:                 if (form.elements[radioname][i].value == '1') {
 3542:                     if (document.getElementById(divid)) {
 3543:                         document.getElementById(divid).style.display = 'inline-block';
 3544:                     }
 3545:                     setvis = 1;
 3546:                 }
 3547:                 break;
 3548:             }
 3549:         }
 3550:         if (!setvis) {
 3551:             if (document.getElementById(divid)) {
 3552:                 document.getElementById(divid).style.display = 'none';
 3553:             }
 3554:         }
 3555:     }
 3556:     return;
 3557: }
 3558: // ]]>
 3559: </script>
 3560: 
 3561: ENDSCRIPT
 3562: }
 3563: 
 3564: sub autoenroll_javascript {
 3565:     return <<"ENDSCRIPT";
 3566: <script type="text/javascript">
 3567: // <![CDATA[
 3568: function toggleFailsafe(form) {
 3569:     var radioname = 'autoenroll_failsafe';
 3570:     var divid = 'autoenroll_failsafe_div';
 3571:     var num = form.elements[radioname].length;
 3572:     if (num) {
 3573:         var setvis = '';
 3574:         for (var i=0; i<num; i++) {
 3575:             if (form.elements[radioname][i].checked) {
 3576:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3577:                     if (document.getElementById(divid)) {
 3578:                         document.getElementById(divid).style.display = 'inline-block';
 3579:                     }
 3580:                     setvis = 1;
 3581:                 }
 3582:                 break;
 3583:             }
 3584:         }
 3585:         if (!setvis) {
 3586:             if (document.getElementById(divid)) {
 3587:                 document.getElementById(divid).style.display = 'none';
 3588:             }
 3589:         }
 3590:     }
 3591:     return;
 3592: }
 3593: // ]]>
 3594: </script>
 3595: 
 3596: ENDSCRIPT
 3597: }
 3598: 
 3599: sub saml_javascript {
 3600:     return <<"ENDSCRIPT";
 3601: <script type="text/javascript">
 3602: // <![CDATA[
 3603: function toggleSamlOptions(form,hostid) {
 3604:     var radioname = 'saml_'+hostid;
 3605:     var tablecellon = 'samloptionson_'+hostid;
 3606:     var tablecelloff = 'samloptionsoff_'+hostid;
 3607:     var num = form.elements[radioname].length;
 3608:     if (num) {
 3609:         var setvis = '';
 3610:         for (var i=0; i<num; i++) {
 3611:             if (form.elements[radioname][i].checked) {
 3612:                 if (form.elements[radioname][i].value == '1') {
 3613:                     if (document.getElementById(tablecellon)) {
 3614:                         document.getElementById(tablecellon).style.display='';
 3615:                     }
 3616:                     if (document.getElementById(tablecelloff)) {
 3617:                         document.getElementById(tablecelloff).style.display='none';
 3618:                     }
 3619:                     setvis = 1;
 3620:                 }
 3621:                 break;
 3622:             }
 3623:         }
 3624:         if (!setvis) {
 3625:             if (document.getElementById(tablecellon)) {
 3626:                 document.getElementById(tablecellon).style.display='none';
 3627:             }
 3628:             if (document.getElementById(tablecelloff)) {
 3629:                 document.getElementById(tablecelloff).style.display='';
 3630:             }
 3631:         }
 3632:     }
 3633:     return;
 3634: }
 3635: // ]]>
 3636: </script>
 3637: 
 3638: ENDSCRIPT
 3639: }
 3640: 
 3641: sub ipaccess_javascript {
 3642:     my ($settings) = @_;
 3643:     my (%ordered,$total,%jstext);
 3644:     $total = 0;
 3645:     if (ref($settings) eq 'HASH') {
 3646:         foreach my $item (keys(%{$settings})) {
 3647:             if (ref($settings->{$item}) eq 'HASH') {
 3648:                 my $num = $settings->{$item}{'order'};
 3649:                 $ordered{$num} = $item;
 3650:             }
 3651:         }
 3652:         $total = scalar(keys(%{$settings}));
 3653:     }
 3654:     my @jsarray = ();
 3655:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3656:         push(@jsarray,$ordered{$item});
 3657:     }
 3658:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3659:     return <<"ENDSCRIPT";
 3660: <script type="text/javascript">
 3661: // <![CDATA[
 3662: function reorderIPaccess(form,item) {
 3663:     var changedVal;
 3664: $jstext
 3665:     var newpos = 'ipaccess_pos_add';
 3666:     var maxh = 1 + $total;
 3667:     var current = new Array;
 3668:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3669:     if (item == newpos) {
 3670:         changedVal = newitemVal;
 3671:     } else {
 3672:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3673:         current[newitemVal] = newpos;
 3674:     }
 3675:     for (var i=0; i<ipaccess.length; i++) {
 3676:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3677:         if (elementName != item) {
 3678:             if (form.elements[elementName]) {
 3679:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3680:                 current[currVal] = elementName;
 3681:             }
 3682:         }
 3683:     }
 3684:     var oldVal;
 3685:     for (var j=0; j<maxh; j++) {
 3686:         if (current[j] == undefined) {
 3687:             oldVal = j;
 3688:         }
 3689:     }
 3690:     if (oldVal < changedVal) {
 3691:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3692:            var elementName = current[k];
 3693:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3694:         }
 3695:     } else {
 3696:         for (var k=changedVal; k<oldVal; k++) {
 3697:             var elementName = current[k];
 3698:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3699:         }
 3700:     }
 3701:     return;
 3702: }
 3703: // ]]>
 3704: </script>
 3705: 
 3706: ENDSCRIPT
 3707: }
 3708: 
 3709: sub print_autoenroll {
 3710:     my ($dom,$settings,$rowtotal) = @_;
 3711:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3712:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 3713:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 3714:     $failsafesty = 'none';
 3715:     %failsafechecked = (
 3716:         off => ' checked="checked"',
 3717:     );
 3718:     if (ref($settings) eq 'HASH') {
 3719:         if (exists($settings->{'run'})) {
 3720:             if ($settings->{'run'} eq '0') {
 3721:                 $runoff = ' checked="checked" ';
 3722:                 $runon = ' ';
 3723:             } else {
 3724:                 $runon = ' checked="checked" ';
 3725:                 $runoff = ' ';
 3726:             }
 3727:         } else {
 3728:             if ($autorun) {
 3729:                 $runon = ' checked="checked" ';
 3730:                 $runoff = ' ';
 3731:             } else {
 3732:                 $runoff = ' checked="checked" ';
 3733:                 $runon = ' ';
 3734:             }
 3735:         }
 3736:         if (exists($settings->{'co-owners'})) {
 3737:             if ($settings->{'co-owners'} eq '0') {
 3738:                 $coownersoff = ' checked="checked" ';
 3739:                 $coownerson = ' ';
 3740:             } else {
 3741:                 $coownerson = ' checked="checked" ';
 3742:                 $coownersoff = ' ';
 3743:             }
 3744:         } else {
 3745:             $coownersoff = ' checked="checked" ';
 3746:             $coownerson = ' ';
 3747:         }
 3748:         if (exists($settings->{'sender_domain'})) {
 3749:             $defdom = $settings->{'sender_domain'};
 3750:         }
 3751:         if (exists($settings->{'failsafe'})) {
 3752:             $failsafe = $settings->{'failsafe'};
 3753:             if ($failsafe eq 'zero') {
 3754:                 $failsafechecked{'zero'} = ' checked="checked"';
 3755:                 $failsafechecked{'off'} = '';
 3756:                 $failsafesty = 'inline-block';
 3757:             } elsif ($failsafe eq 'any') {
 3758:                 $failsafechecked{'any'} = ' checked="checked"';
 3759:                 $failsafechecked{'off'} = '';
 3760:             }
 3761:             $autofailsafe = $settings->{'autofailsafe'};
 3762:         } elsif (exists($settings->{'autofailsafe'})) {
 3763:             $autofailsafe = $settings->{'autofailsafe'};
 3764:             if ($autofailsafe ne '') {
 3765:                 $failsafechecked{'zero'} = ' checked="checked"';
 3766:                 $failsafe = 'zero';
 3767:                 $failsafechecked{'off'} = '';
 3768:             }
 3769:         }
 3770:     } else {
 3771:         if ($autorun) {
 3772:             $runon = ' checked="checked" ';
 3773:             $runoff = ' ';
 3774:         } else {
 3775:             $runoff = ' checked="checked" ';
 3776:             $runon = ' ';
 3777:         }
 3778:     }
 3779:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3780:     my $notif_sender;
 3781:     if (ref($settings) eq 'HASH') {
 3782:         $notif_sender = $settings->{'sender_uname'};
 3783:     }
 3784:     my $datatable='<tr class="LC_odd_row">'.
 3785:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3786:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3787:                   '<input type="radio" name="autoenroll_run"'.
 3788:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3789:                   '<label><input type="radio" name="autoenroll_run"'.
 3790:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3791:                   '</tr><tr>'.
 3792:                   '<td>'.&mt('Notification messages - sender').
 3793:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3794:                   &mt('username').':&nbsp;'.
 3795:                   '<input type="text" name="sender_uname" value="'.
 3796:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3797:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3798:                   '<tr class="LC_odd_row">'.
 3799:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3800:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3801:                   '<input type="radio" name="autoassign_coowners"'.
 3802:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3803:                   '<label><input type="radio" name="autoassign_coowners"'.
 3804:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3805:                   '</tr><tr>'.
 3806:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3807:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 3808:                   '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="off" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'off'}.' />'.&mt('Not in use').'</label></span>&nbsp;&nbsp;&nbsp; '.
 3809:                   '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="zero" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'zero'}.' />'.&mt('Retrieved section enrollment is zero').'</label></span><br />'.
 3810:                   '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="any" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'any'}.' />'.&mt('Retrieved section enrollment is zero or greater').'</label></span>'.
 3811:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 3812:                   '<span class="LC_nobreak">'.
 3813:                   &mt('Threshold for number of students in section to drop: [_1]',
 3814:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 3815:                   '</span></div></td></tr>';
 3816:     $$rowtotal += 4;
 3817:     return $datatable;
 3818: }
 3819: 
 3820: sub print_autoupdate {
 3821:     my ($position,$dom,$settings,$rowtotal) = @_;
 3822:     my ($enable,$datatable);
 3823:     if ($position eq 'top') {
 3824:         my %choices = &Apache::lonlocal::texthash (
 3825:                           run        => 'Auto-update active?',
 3826:                           classlists => 'Update information in classlists?',
 3827:                           unexpired  => 'Skip updates for users without active or future roles?',
 3828:                           lastactive => 'Skip updates for inactive users?',
 3829:         );
 3830:         my $itemcount = 0;
 3831:         my $updateon = ' ';
 3832:         my $updateoff = ' checked="checked" ';
 3833:         if (ref($settings) eq 'HASH') {
 3834:             if ($settings->{'run'} eq '1') {
 3835:                 $updateon = $updateoff;
 3836:                 $updateoff = ' ';
 3837:             }
 3838:         }
 3839:         $enable = '<tr class="LC_odd_row">'.
 3840:                   '<td>'.$choices{'run'}.'</td>'.
 3841:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3842:                   '<input type="radio" name="autoupdate_run"'.
 3843:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 3844:                   '<label><input type="radio" name="autoupdate_run"'.
 3845:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 3846:                   '</tr>';
 3847:         my @toggles = ('classlists','unexpired');
 3848:         my %defaultchecked = ('classlists' => 'off',
 3849:                               'unexpired'  => 'off'
 3850:                               );
 3851:         $$rowtotal ++;
 3852:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3853:                                                      \%choices,$itemcount,'','','left','no');
 3854:         $datatable = $enable.$datatable;
 3855:         $$rowtotal += $itemcount;
 3856:         my $lastactiveon = ' ';
 3857:         my $lastactiveoff = ' checked="checked" ';
 3858:         my $lastactivestyle = 'none';
 3859:         my $lastactivedays;
 3860:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 3861:         if (ref($settings) eq 'HASH') {
 3862:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 3863:                 $lastactiveon = $lastactiveoff;
 3864:                 $lastactiveoff = ' ';
 3865:                 $lastactivestyle = 'inline-block';
 3866:                 $lastactivedays = $settings->{'lastactive'};
 3867:             }
 3868:         }
 3869:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3870:         $datatable .= '<tr'.$css_class.'>'.
 3871:                       '<td>'.$choices{'lastactive'}.'</td>'.
 3872:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3873:                       '<input type="radio" name="lastactive"'.
 3874:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3875:                       '&nbsp;<label>'.
 3876:                       '<input type="radio" name="lastactive"'.
 3877:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 3878:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 3879:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 3880:                           '<input type="text" size="5" name="lastactivedays" value="'.
 3881:                           $lastactivedays.'" />').
 3882:                       '</span></td>'.
 3883:                       '</tr>';
 3884:         $$rowtotal ++;
 3885:     } elsif ($position eq 'middle') {
 3886:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3887:         my $numinrow = 3;
 3888:         my $locknamesettings;
 3889:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3890:                                      $dom,$numinrow,$othertitle,
 3891:                                     'lockablenames',$rowtotal);
 3892:         $$rowtotal ++;
 3893:     } else {
 3894:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3895:         my @fields = ('lastname','firstname','middlename','generation',
 3896:                       'permanentemail','id');
 3897:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3898:         my $numrows = 0;
 3899:         if (ref($types) eq 'ARRAY') {
 3900:             if (@{$types} > 0) {
 3901:                 $datatable = 
 3902:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3903:                                          \@fields,$types,\$numrows);
 3904:                     $$rowtotal += @{$types}; 
 3905:             }
 3906:         }
 3907:         $datatable .= 
 3908:             &usertype_update_row($settings,{'default' => $othertitle},
 3909:                                  \%fieldtitles,\@fields,['default'],
 3910:                                  \$numrows);
 3911:         $$rowtotal ++;     
 3912:     }
 3913:     return $datatable;
 3914: }
 3915: 
 3916: sub print_autocreate {
 3917:     my ($dom,$settings,$rowtotal) = @_;
 3918:     my (%createon,%createoff,%currhash);
 3919:     my @types = ('xml','req');
 3920:     if (ref($settings) eq 'HASH') {
 3921:         foreach my $item (@types) {
 3922:             $createoff{$item} = ' checked="checked" ';
 3923:             $createon{$item} = ' ';
 3924:             if (exists($settings->{$item})) {
 3925:                 if ($settings->{$item}) {
 3926:                     $createon{$item} = ' checked="checked" ';
 3927:                     $createoff{$item} = ' ';
 3928:                 }
 3929:             }
 3930:         }
 3931:         if ($settings->{'xmldc'} ne '') {
 3932:             $currhash{$settings->{'xmldc'}} = 1;
 3933:         }
 3934:     } else {
 3935:         foreach my $item (@types) {
 3936:             $createoff{$item} = ' checked="checked" ';
 3937:             $createon{$item} = ' ';
 3938:         }
 3939:     }
 3940:     $$rowtotal += 2;
 3941:     my $numinrow = 2;
 3942:     my $datatable='<tr class="LC_odd_row">'.
 3943:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3944:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3945:                   '<input type="radio" name="autocreate_xml"'.
 3946:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3947:                   '<label><input type="radio" name="autocreate_xml"'.
 3948:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3949:                   '</td></tr><tr>'.
 3950:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3951:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3952:                   '<input type="radio" name="autocreate_req"'.
 3953:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3954:                   '<label><input type="radio" name="autocreate_req"'.
 3955:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3956:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3957:                                                    'autocreate_xmldc',%currhash);
 3958:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3959:     if ($numdc > 1) {
 3960:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3961:                       '</td><td class="LC_left_item">';
 3962:     } else {
 3963:         $datatable .= &mt('Course creation processed as:').
 3964:                       '</td><td class="LC_right_item">';
 3965:     }
 3966:     $datatable .= $dctable.'</td></tr>';
 3967:     $$rowtotal += $rows;
 3968:     return $datatable;
 3969: }
 3970: 
 3971: sub print_directorysrch {
 3972:     my ($position,$dom,$settings,$rowtotal) = @_;
 3973:     my $datatable;
 3974:     if ($position eq 'top') {
 3975:         my $instsrchon = ' ';
 3976:         my $instsrchoff = ' checked="checked" ';
 3977:         my ($exacton,$containson,$beginson);
 3978:         my $instlocalon = ' ';
 3979:         my $instlocaloff = ' checked="checked" ';
 3980:         if (ref($settings) eq 'HASH') {
 3981:             if ($settings->{'available'} eq '1') {
 3982:                 $instsrchon = $instsrchoff;
 3983:                 $instsrchoff = ' ';
 3984:             }
 3985:             if ($settings->{'localonly'} eq '1') {
 3986:                 $instlocalon = $instlocaloff;
 3987:                 $instlocaloff = ' ';
 3988:             }
 3989:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3990:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3991:                     if ($type eq 'exact') {
 3992:                         $exacton = ' checked="checked" ';
 3993:                     } elsif ($type eq 'contains') {
 3994:                         $containson = ' checked="checked" ';
 3995:                     } elsif ($type eq 'begins') {
 3996:                         $beginson = ' checked="checked" ';
 3997:                     }
 3998:                 }
 3999:             } else {
 4000:                 if ($settings->{'searchtypes'} eq 'exact') {
 4001:                     $exacton = ' checked="checked" ';
 4002:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 4003:                     $containson = ' checked="checked" ';
 4004:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 4005:                     $exacton = ' checked="checked" ';
 4006:                     $containson = ' checked="checked" ';
 4007:                 }
 4008:             }
 4009:         }
 4010:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 4011:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4012: 
 4013:         my $numinrow = 4;
 4014:         my $cansrchrow = 0;
 4015:         $datatable='<tr class="LC_odd_row">'.
 4016:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 4017:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4018:                    '<input type="radio" name="dirsrch_available"'.
 4019:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4020:                    '<label><input type="radio" name="dirsrch_available"'.
 4021:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4022:                    '</tr><tr>'.
 4023:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 4024:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4025:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 4026:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4027:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 4028:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4029:                    '</tr>';
 4030:         $$rowtotal += 2;
 4031:         if (ref($usertypes) eq 'HASH') {
 4032:             if (keys(%{$usertypes}) > 0) {
 4033:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4034:                                              $numinrow,$othertitle,'cansearch',
 4035:                                              $rowtotal);
 4036:                 $cansrchrow = 1;
 4037:             }
 4038:         }
 4039:         if ($cansrchrow) {
 4040:             $$rowtotal ++;
 4041:             $datatable .= '<tr>';
 4042:         } else {
 4043:             $datatable .= '<tr class="LC_odd_row">';
 4044:         }
 4045:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 4046:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 4047:         foreach my $title (@{$titleorder}) {
 4048:             if (defined($searchtitles->{$title})) {
 4049:                 my $check = ' ';
 4050:                 if (ref($settings) eq 'HASH') {
 4051:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 4052:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 4053:                             $check = ' checked="checked" ';
 4054:                         }
 4055:                     }
 4056:                 }
 4057:                 $datatable .= '<td class="LC_left_item">'.
 4058:                               '<span class="LC_nobreak"><label>'.
 4059:                               '<input type="checkbox" name="searchby" '.
 4060:                               'value="'.$title.'"'.$check.'/>'.
 4061:                               $searchtitles->{$title}.'</label></span></td>';
 4062:             }
 4063:         }
 4064:         $datatable .= '</tr></table></td></tr>';
 4065:         $$rowtotal ++;
 4066:         if ($cansrchrow) {
 4067:             $datatable .= '<tr class="LC_odd_row">';
 4068:         } else {
 4069:             $datatable .= '<tr>';
 4070:         }
 4071:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 4072:                       '<td class="LC_left_item" colspan="2">'.
 4073:                       '<span class="LC_nobreak"><label>'.
 4074:                       '<input type="checkbox" name="searchtypes" '.
 4075:                       $exacton.' value="exact" />'.&mt('Exact match').
 4076:                       '</label>&nbsp;'.
 4077:                       '<label><input type="checkbox" name="searchtypes" '.
 4078:                       $beginson.' value="begins" />'.&mt('Begins with').
 4079:                       '</label>&nbsp;'.
 4080:                       '<label><input type="checkbox" name="searchtypes" '.
 4081:                       $containson.' value="contains" />'.&mt('Contains').
 4082:                       '</label></span></td></tr>';
 4083:         $$rowtotal ++;
 4084:     } else {
 4085:         my $domsrchon = ' checked="checked" ';
 4086:         my $domsrchoff = ' ';
 4087:         my $domlocalon = ' ';
 4088:         my $domlocaloff = ' checked="checked" ';
 4089:         if (ref($settings) eq 'HASH') {
 4090:             if ($settings->{'lclocalonly'} eq '1') {
 4091:                 $domlocalon = $domlocaloff;
 4092:                 $domlocaloff = ' ';
 4093:             }
 4094:             if ($settings->{'lcavailable'} eq '0') {
 4095:                 $domsrchoff = $domsrchon;
 4096:                 $domsrchon = ' ';
 4097:             }
 4098:         }
 4099:         $datatable='<tr class="LC_odd_row">'.
 4100:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 4101:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4102:                       '<input type="radio" name="dirsrch_domavailable"'.
 4103:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4104:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 4105:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4106:                       '</tr><tr>'.
 4107:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 4108:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4109:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 4110:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4111:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 4112:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4113:                       '</tr>';
 4114:         $$rowtotal += 2;
 4115:     }
 4116:     return $datatable;
 4117: }
 4118: 
 4119: sub print_contacts {
 4120:     my ($position,$dom,$settings,$rowtotal) = @_;
 4121:     my $datatable;
 4122:     my @contacts = ('adminemail','supportemail');
 4123:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 4124:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 4125:     if ($position eq 'top') {
 4126:         if (ref($settings) eq 'HASH') {
 4127:             foreach my $item (@contacts) {
 4128:                 if (exists($settings->{$item})) {
 4129:                     $to{$item} = $settings->{$item};
 4130:                 }
 4131:             }
 4132:         }
 4133:     } elsif ($position eq 'middle') {
 4134:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 4135:                      'updatesmail','idconflictsmail','hostipmail');
 4136:         foreach my $type (@mailings) {
 4137:             $otheremails{$type} = '';
 4138:         }
 4139:     } elsif ($position eq 'lower') {
 4140:         if (ref($settings) eq 'HASH') {
 4141:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 4142:                 %lonstatus = %{$settings->{'lonstatus'}};
 4143:             }
 4144:         }
 4145:     } else {
 4146:         @mailings = ('helpdeskmail','otherdomsmail');
 4147:         foreach my $type (@mailings) {
 4148:             $otheremails{$type} = '';
 4149:         }
 4150:         $bccemails{'helpdeskmail'} = '';
 4151:         $bccemails{'otherdomsmail'} = '';
 4152:         $includestr{'helpdeskmail'} = '';
 4153:         $includestr{'otherdomsmail'} = '';
 4154:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 4155:     }
 4156:     if (ref($settings) eq 'HASH') {
 4157:         unless (($position eq 'top') || ($position eq 'lower')) {
 4158:             foreach my $type (@mailings) {
 4159:                 if (exists($settings->{$type})) {
 4160:                     if (ref($settings->{$type}) eq 'HASH') {
 4161:                         foreach my $item (@contacts) {
 4162:                             if ($settings->{$type}{$item}) {
 4163:                                 $checked{$type}{$item} = ' checked="checked" ';
 4164:                             }
 4165:                         }
 4166:                         $otheremails{$type} = $settings->{$type}{'others'};
 4167:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4168:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 4169:                             if ($settings->{$type}{'include'} ne '') {
 4170:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4171:                                 $includestr{$type} = &unescape($includestr{$type});
 4172:                             }
 4173:                         }
 4174:                     }
 4175:                 } elsif ($type eq 'lonstatusmail') {
 4176:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4177:                 }
 4178:             }
 4179:         }
 4180:         if ($position eq 'bottom') {
 4181:             foreach my $type (@mailings) {
 4182:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 4183:                 if ($settings->{$type}{'include'} ne '') {
 4184:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4185:                     $includestr{$type} = &unescape($includestr{$type});
 4186:                 }
 4187:             }
 4188:             if (ref($settings->{'helpform'}) eq 'HASH') {
 4189:                 if (ref($fields) eq 'ARRAY') {
 4190:                     foreach my $field (@{$fields}) {
 4191:                         $currfield{$field} = $settings->{'helpform'}{$field};
 4192:                     }
 4193:                 }
 4194:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 4195:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 4196:                 } else {
 4197:                     $maxsize = '1.0';
 4198:                 }
 4199:             } else {
 4200:                 if (ref($fields) eq 'ARRAY') {
 4201:                     foreach my $field (@{$fields}) {
 4202:                         $currfield{$field} = 'yes';
 4203:                     }
 4204:                 }
 4205:                 $maxsize = '1.0';
 4206:             }
 4207:         }
 4208:     } else {
 4209:         if ($position eq 'top') {
 4210:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 4211:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 4212:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 4213:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 4214:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4215:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 4216:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 4217:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 4218:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 4219:         } elsif ($position eq 'bottom') {
 4220:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 4221:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 4222:             if (ref($fields) eq 'ARRAY') {
 4223:                 foreach my $field (@{$fields}) {
 4224:                     $currfield{$field} = 'yes';
 4225:                 }
 4226:             }
 4227:             $maxsize = '1.0';
 4228:         }
 4229:     }
 4230:     my ($titles,$short_titles) = &contact_titles();
 4231:     my $rownum = 0;
 4232:     my $css_class;
 4233:     if ($position eq 'top') {
 4234:         foreach my $item (@contacts) {
 4235:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4236:             $datatable .= '<tr'.$css_class.'>'. 
 4237:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 4238:                           '</span></td><td class="LC_right_item">'.
 4239:                           '<input type="text" name="'.$item.'" value="'.
 4240:                           $to{$item}.'" /></td></tr>';
 4241:             $rownum ++;
 4242:         }
 4243:     } elsif ($position eq 'bottom') {
 4244:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4245:         $datatable .= '<tr'.$css_class.'>'.
 4246:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 4247:                       &mt('(e-mail, subject, and description always shown)').
 4248:                       '</td><td class="LC_left_item">';
 4249:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 4250:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 4251:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 4252:             foreach my $field (@{$fields}) {
 4253:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 4254:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 4255:                     $datatable .= ' '.&mt('(logged-in users)');
 4256:                 }
 4257:                 $datatable .='</td><td>';
 4258:                 my $clickaction;
 4259:                 if ($field eq 'screenshot') {
 4260:                     $clickaction = ' onclick="screenshotSize(this);"';
 4261:                 }
 4262:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4263:                     foreach my $option (@{$possoptions->{$field}}) {
 4264:                         my $checked;
 4265:                         if ($currfield{$field} eq $option) {
 4266:                             $checked = ' checked="checked"';
 4267:                         }
 4268:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4269:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4270:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4271:                                       '</label></span>'.('&nbsp;'x2);
 4272:                     }
 4273:                 }
 4274:                 if ($field eq 'screenshot') {
 4275:                     my $display;
 4276:                     if ($currfield{$field} eq 'no') {
 4277:                         $display = ' style="display:none"';
 4278:                     }
 4279:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4280:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4281:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4282:                 }
 4283:                 $datatable .= '</td></tr>';
 4284:             }
 4285:             $datatable .= '</table>';
 4286:         }
 4287:         $datatable .= '</td></tr>'."\n";
 4288:         $rownum ++;
 4289:     }
 4290:     unless (($position eq 'top') || ($position eq 'lower')) {
 4291:         foreach my $type (@mailings) {
 4292:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4293:             $datatable .= '<tr'.$css_class.'>'.
 4294:                           '<td><span class="LC_nobreak">'.
 4295:                           $titles->{$type}.': </span></td>'.
 4296:                           '<td class="LC_left_item">';
 4297:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4298:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4299:             }
 4300:             $datatable .= '<span class="LC_nobreak">';
 4301:             foreach my $item (@contacts) {
 4302:                 $datatable .= '<label>'.
 4303:                               '<input type="checkbox" name="'.$type.'"'.
 4304:                               $checked{$type}{$item}.
 4305:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4306:                               '</label>&nbsp;';
 4307:             }
 4308:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4309:                           '<input type="text" name="'.$type.'_others" '.
 4310:                           'value="'.$otheremails{$type}.'"  />';
 4311:             my %locchecked;
 4312:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4313:                 foreach my $loc ('s','b') {
 4314:                     if ($includeloc{$type} eq $loc) {
 4315:                         $locchecked{$loc} = ' checked="checked"';
 4316:                         last;
 4317:                     }
 4318:                 }
 4319:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4320:                               '<input type="text" name="'.$type.'_bcc" '.
 4321:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4322:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4323:                               &mt('Text automatically added to e-mail:').' '.
 4324:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4325:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4326:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4327:                               ('&nbsp;'x2).
 4328:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4329:                               '</span></fieldset>';
 4330:             }
 4331:             $datatable .= '</td></tr>'."\n";
 4332:             $rownum ++;
 4333:         }
 4334:     }
 4335:     if ($position eq 'middle') {
 4336:         my %choices;
 4337:         my $corelink = &core_link_msu();
 4338:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4339:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4340:                                         $corelink);
 4341:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4342:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4343:         my %defaultchecked = ('reporterrors'  => 'on',
 4344:                               'reportupdates' => 'on',
 4345:                               'reportstatus'  => 'on');
 4346:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4347:                                                    \%choices,$rownum);
 4348:         $datatable .= $reports;
 4349:     } elsif ($position eq 'lower') {
 4350:         my (%current,%excluded,%weights);
 4351:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4352:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4353:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4354:         } else {
 4355:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4356:         }
 4357:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4358:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4359:         } else {
 4360:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4361:         }
 4362:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4363:             foreach my $type ('E','W','N','U') {
 4364:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4365:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4366:                 } else {
 4367:                     $weights{$type} = $defaults->{$type};
 4368:                 }
 4369:             }
 4370:         } else {
 4371:             foreach my $type ('E','W','N','U') {
 4372:                 $weights{$type} = $defaults->{$type};
 4373:             }
 4374:         }
 4375:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4376:             if (@{$lonstatus{'excluded'}} > 0) {
 4377:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4378:             }
 4379:         }
 4380:         foreach my $item ('errorthreshold','errorsysmail') {
 4381:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4382:             $datatable .= '<tr'.$css_class.'>'.
 4383:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4384:                           $titles->{$item}.
 4385:                           '</span></td><td class="LC_left_item">'.
 4386:                           '<input type="text" name="'.$item.'" value="'.
 4387:                           $current{$item}.'" size="5" /></td></tr>';
 4388:             $rownum ++;
 4389:         }
 4390:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4391:         $datatable .= '<tr'.$css_class.'>'.
 4392:                       '<td class="LC_left_item">'.
 4393:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4394:                       '</span></td><td class="LC_left_item"><table><tr>';
 4395:         foreach my $type ('E','W','N','U') {
 4396:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4397:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4398:                           $weights{$type}.'" size="5" /></td>';
 4399:         }
 4400:         $datatable .= '</tr></table></tr>';
 4401:         $rownum ++;
 4402:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4403:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4404:                       $titles->{'errorexcluded'}.'</td>'.
 4405:                       '<td class="LC_left_item"><table>';
 4406:         my $numinrow = 4;
 4407:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4408:         for (my $i=0; $i<@ids; $i++) {
 4409:             my $rem = $i%($numinrow);
 4410:             if ($rem == 0) {
 4411:                 if ($i > 0) {
 4412:                     $datatable .= '</tr>';
 4413:                 }
 4414:                 $datatable .= '<tr>';
 4415:             }
 4416:             my $check;
 4417:             if ($excluded{$ids[$i]}) {
 4418:                 $check = ' checked="checked" ';
 4419:             }
 4420:             $datatable .= '<td class="LC_left_item">'.
 4421:                           '<span class="LC_nobreak"><label>'.
 4422:                           '<input type="checkbox" name="errorexcluded" '.
 4423:                           'value="'.$ids[$i].'"'.$check.' />'.
 4424:                           $ids[$i].'</label></span></td>';
 4425:         }
 4426:         my $colsleft = $numinrow - @ids%($numinrow);
 4427:         if ($colsleft > 1 ) {
 4428:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4429:                           '&nbsp;</td>';
 4430:         } elsif ($colsleft == 1) {
 4431:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4432:         }
 4433:         $datatable .= '</tr></table></td></tr>';
 4434:         $rownum ++;
 4435:     } elsif ($position eq 'bottom') {
 4436:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4437:         my (@posstypes,%usertypeshash);
 4438:         if (ref($types) eq 'ARRAY') {
 4439:             @posstypes = @{$types};
 4440:         }
 4441:         if (@posstypes) {
 4442:             if (ref($usertypes) eq 'HASH') {
 4443:                 %usertypeshash = %{$usertypes};
 4444:             }
 4445:             my @overridden;
 4446:             my $numinrow = 4;
 4447:             if (ref($settings) eq 'HASH') {
 4448:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4449:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4450:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4451:                             push(@overridden,$key);
 4452:                             foreach my $item (@contacts) {
 4453:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4454:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4455:                                 }
 4456:                             }
 4457:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4458:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4459:                             $includeloc{'override_'.$key} = '';
 4460:                             $includestr{'override_'.$key} = '';
 4461:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4462:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) =
 4463:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4464:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4465:                             }
 4466:                         }
 4467:                     }
 4468:                 }
 4469:             }
 4470:             my $customclass = 'LC_helpdesk_override';
 4471:             my $optionsprefix = 'LC_options_helpdesk_';
 4472: 
 4473:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4474:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4475:                                          $numinrow,$othertitle,'overrides',
 4476:                                          \$rownum,$onclicktypes,$customclass);
 4477:             $rownum ++;
 4478:             $usertypeshash{'default'} = $othertitle;
 4479:             foreach my $status (@posstypes) {
 4480:                 my $css_class;
 4481:                 if ($rownum%2) {
 4482:                     $css_class = 'LC_odd_row ';
 4483:                 }
 4484:                 $css_class .= $customclass;
 4485:                 my $rowid = $optionsprefix.$status;
 4486:                 my $hidden = 1;
 4487:                 my $currstyle = 'display:none';
 4488:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4489:                     $currstyle = 'display:table-row';
 4490:                     $hidden = 0;
 4491:                 }
 4492:                 my $key = 'override_'.$status;
 4493:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4494:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4495:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4496:                                                   \@contacts,$short_titles);
 4497:                 unless ($hidden) {
 4498:                     $rownum ++;
 4499:                 }
 4500:             }
 4501:         }
 4502:     }
 4503:     $$rowtotal += $rownum;
 4504:     return $datatable;
 4505: }
 4506: 
 4507: sub core_link_msu {
 4508:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4509:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4510: }
 4511: 
 4512: sub overridden_helpdesk {
 4513:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4514:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4515:     my $class = 'LC_left_item';
 4516:     if ($css_class) {
 4517:         $css_class = ' class="'.$css_class.'"';
 4518:     }
 4519:     if ($rowid) {
 4520:         $rowid = ' id="'.$rowid.'"';
 4521:     }
 4522:     if ($rowstyle) {
 4523:         $rowstyle = ' style="'.$rowstyle.'"';
 4524:     }
 4525:     my ($output,$description);
 4526:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4527:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4528:               "<td>$description</td>\n".
 4529:               '<td class="'.$class.'" colspan="2">'.
 4530:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4531:               '<span class="LC_nobreak">';
 4532:     if (ref($contacts) eq 'ARRAY') {
 4533:         foreach my $item (@{$contacts}) {
 4534:             my $check;
 4535:             if (ref($checked) eq 'HASH') {
 4536:                $check = $checked->{$item};
 4537:             }
 4538:             my $title;
 4539:             if (ref($short_titles) eq 'HASH') {
 4540:                 $title = $short_titles->{$item};
 4541:             }
 4542:             $output .= '<label>'.
 4543:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4544:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4545:         }
 4546:     }
 4547:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4548:                '<input type="text" name="override_'.$type.'_others" '.
 4549:                'value="'.$otheremails.'"  />';
 4550:     my %locchecked;
 4551:     foreach my $loc ('s','b') {
 4552:         if ($includeloc eq $loc) {
 4553:             $locchecked{$loc} = ' checked="checked"';
 4554:             last;
 4555:         }
 4556:     }
 4557:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4558:                '<input type="text" name="override_'.$type.'_bcc" '.
 4559:                'value="'.$bccemails.'"  /></fieldset>'.
 4560:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4561:                &mt('Text automatically added to e-mail:').' '.
 4562:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4563:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4564:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4565:                ('&nbsp;'x2).
 4566:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4567:                '</span></fieldset>'.
 4568:                '</td></tr>'."\n";
 4569:     return $output;
 4570: }
 4571: 
 4572: sub contacts_javascript {
 4573:     return <<"ENDSCRIPT";
 4574: 
 4575: <script type="text/javascript">
 4576: // <![CDATA[
 4577: 
 4578: function screenshotSize(field) {
 4579:     if (document.getElementById('help_screenshotsize')) {
 4580:         if (field.value == 'no') {
 4581:             document.getElementById('help_screenshotsize').style.display="none";
 4582:         } else {
 4583:             document.getElementById('help_screenshotsize').style.display="";
 4584:         }
 4585:     }
 4586:     return;
 4587: }
 4588: 
 4589: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4590:     if (form.elements[checkbox].length != undefined) {
 4591:         var count = 0;
 4592:         if (docount) {
 4593:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4594:                 if (form.elements[checkbox][i].checked) {
 4595:                     count ++;
 4596:                 }
 4597:             }
 4598:         }
 4599:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4600:             var type = form.elements[checkbox][i].value;
 4601:             if (document.getElementById(prefix+type)) {
 4602:                 if (form.elements[checkbox][i].checked) {
 4603:                     document.getElementById(prefix+type).style.display = 'table-row';
 4604:                     if (count % 2 == 1) {
 4605:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4606:                     } else {
 4607:                         document.getElementById(prefix+type).className = target;
 4608:                     }
 4609:                     count ++;
 4610:                 } else {
 4611:                     document.getElementById(prefix+type).style.display = 'none';
 4612:                 }
 4613:             }
 4614:         }
 4615:     }
 4616:     return;
 4617: }
 4618: 
 4619: // ]]>
 4620: </script>
 4621: 
 4622: ENDSCRIPT
 4623: }
 4624: 
 4625: sub print_helpsettings {
 4626:     my ($position,$dom,$settings,$rowtotal) = @_;
 4627:     my $confname = $dom.'-domainconfig';
 4628:     my $formname = 'display';
 4629:     my ($datatable,$itemcount);
 4630:     if ($position eq 'top') {
 4631:         $itemcount = 1;
 4632:         my (%choices,%defaultchecked,@toggles);
 4633:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4634:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4635:                                      &mt('LON-CAPA bug tracker'),600,500));
 4636:         %defaultchecked = ('submitbugs' => 'on');
 4637:         @toggles = ('submitbugs');
 4638:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4639:                                                      \%choices,$itemcount);
 4640:         $$rowtotal ++;
 4641:     } else {
 4642:         my $css_class;
 4643:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4644:         my (%customroles,%ordered,%current);
 4645:         if (ref($settings) eq 'HASH') {
 4646:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4647:                 %current = %{$settings->{'adhoc'}};
 4648:             }
 4649:         }
 4650:         my $count = 0;
 4651:         foreach my $key (sort(keys(%existing))) {
 4652:             if ($key=~/^rolesdef\_(\w+)$/) {
 4653:                 my $rolename = $1;
 4654:                 my (%privs,$order);
 4655:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4656:                 $customroles{$rolename} = \%privs;
 4657:                 if (ref($current{$rolename}) eq 'HASH') {
 4658:                     $order = $current{$rolename}{'order'};
 4659:                 }
 4660:                 if ($order eq '') {
 4661:                     $order = $count;
 4662:                 }
 4663:                 $ordered{$order} = $rolename;
 4664:                 $count++;
 4665:             }
 4666:         }
 4667:         my $maxnum = scalar(keys(%ordered));
 4668:         my @roles_by_num = ();
 4669:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4670:             push(@roles_by_num,$item);
 4671:         }
 4672:         my $context = 'domprefs';
 4673:         my $crstype = 'Course';
 4674:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4675:         my @accesstypes = ('all','dh','da','none');
 4676:         my ($numstatustypes,@jsarray);
 4677:         if (ref($types) eq 'ARRAY') {
 4678:             if (@{$types} > 0) {
 4679:                 $numstatustypes = scalar(@{$types});
 4680:                 push(@accesstypes,'status');
 4681:                 @jsarray = ('bystatus');
 4682:             }
 4683:         }
 4684:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4685:         if (keys(%domhelpdesk)) {
 4686:             push(@accesstypes,('inc','exc'));
 4687:             push(@jsarray,('notinc','notexc'));
 4688:         }
 4689:         my $hiddenstr = join("','",@jsarray);
 4690:         my $context = 'domprefs';
 4691:         my $crstype = 'Course';
 4692:         my $prefix = 'helproles_';
 4693:         my $add_class = 'LC_hidden';
 4694:         foreach my $num (@roles_by_num) {
 4695:             my $role = $ordered{$num};
 4696:             my ($desc,$access,@statuses);
 4697:             if (ref($current{$role}) eq 'HASH') {
 4698:                 $desc = $current{$role}{'desc'};
 4699:                 $access = $current{$role}{'access'};
 4700:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4701:                     @statuses = @{$current{$role}{'insttypes'}};
 4702:                 }
 4703:             }
 4704:             if ($desc eq '') {
 4705:                 $desc = $role;
 4706:             }
 4707:             my $identifier = 'custhelp'.$num;
 4708:             my %full=();
 4709:             my %levels= (
 4710:                          course => {},
 4711:                          domain => {},
 4712:                          system => {},
 4713:                         );
 4714:             my %levelscurrent=(
 4715:                                course => {},
 4716:                                domain => {},
 4717:                                system => {},
 4718:                               );
 4719:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4720:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4721:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4722:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4723:             $datatable .= '<tr '.$css_class.'><td valign="top"><b>'.$role.'</b><br />'.
 4724:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4725:             for (my $k=0; $k<=$maxnum; $k++) {
 4726:                 my $vpos = $k+1;
 4727:                 my $selstr;
 4728:                 if ($k == $num) {
 4729:                     $selstr = ' selected="selected" ';
 4730:                 }
 4731:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4732:             }
 4733:             $datatable .= '</select>'.('&nbsp;'x2).
 4734:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4735:                           '</td>'.
 4736:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4737:                           &mt('Name shown to users:').
 4738:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4739:                           '</fieldset>'.
 4740:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4741:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4742:                           '<fieldset>'.
 4743:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4744:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4745:                                                                    \%levelscurrent,$identifier,
 4746:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4747:                           '</fieldset></td>';
 4748:             $itemcount ++;
 4749:         }
 4750:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4751:         my $newcust = 'custhelp'.$count;
 4752:         my (%privs,%levelscurrent);
 4753:         my %full=();
 4754:         my %levels= (
 4755:                      course => {},
 4756:                      domain => {},
 4757:                      system => {},
 4758:                     );
 4759:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4760:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4761:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4762:         $datatable .= '<tr '.$css_class.'><td valign="top"><span class="LC_nobreak"><label>'.
 4763:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4764:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4765:         for (my $k=0; $k<$maxnum+1; $k++) {
 4766:             my $vpos = $k+1;
 4767:             my $selstr;
 4768:             if ($k == $maxnum) {
 4769:                 $selstr = ' selected="selected" ';
 4770:             }
 4771:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4772:         }
 4773:         $datatable .= '</select>&nbsp;'."\n".
 4774:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4775:                       '</label></span></td>'.
 4776:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4777:                       '<span class="LC_nobreak">'.
 4778:                       &mt('Internal name:').
 4779:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4780:                       '</span>'.('&nbsp;'x4).
 4781:                       '<span class="LC_nobreak">'.
 4782:                       &mt('Name shown to users:').
 4783:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4784:                       '</span></fieldset>'.
 4785:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4786:                                              $usertypes,$types,\%domhelpdesk).
 4787:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4788:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4789:                                                                 \@templateroles,$newcust).
 4790:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4791:                                                                \%levelscurrent,$newcust).
 4792:                       '</fieldset>'.
 4793:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4794:                       '</td></tr>';
 4795:         $count ++;
 4796:         $$rowtotal += $count;
 4797:     }
 4798:     return $datatable;
 4799: }
 4800: 
 4801: sub adhocbutton {
 4802:     my ($prefix,$num,$field,$visibility) = @_;
 4803:     my %lt = &Apache::lonlocal::texthash(
 4804:                                           show => 'Show details',
 4805:                                           hide => 'Hide details',
 4806:                                         );
 4807:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4808:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4809:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4810:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4811: }
 4812: 
 4813: sub helpsettings_javascript {
 4814:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4815:     return unless(ref($roles_by_num) eq 'ARRAY');
 4816:     my %html_js_lt = &Apache::lonlocal::texthash(
 4817:                                           show => 'Show details',
 4818:                                           hide => 'Hide details',
 4819:                                         );
 4820:     &html_escape(\%html_js_lt);
 4821:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4822:     return <<"ENDSCRIPT";
 4823: <script type="text/javascript">
 4824: // <![CDATA[
 4825: 
 4826: function reorderHelpRoles(form,item) {
 4827:     var changedVal;
 4828: $jstext
 4829:     var newpos = 'helproles_${total}_pos';
 4830:     var maxh = 1 + $total;
 4831:     var current = new Array();
 4832:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4833:     if (item == newpos) {
 4834:         changedVal = newitemVal;
 4835:     } else {
 4836:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4837:         current[newitemVal] = newpos;
 4838:     }
 4839:     for (var i=0; i<helproles.length; i++) {
 4840:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4841:         if (elementName != item) {
 4842:             if (form.elements[elementName]) {
 4843:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4844:                 current[currVal] = elementName;
 4845:             }
 4846:         }
 4847:     }
 4848:     var oldVal;
 4849:     for (var j=0; j<maxh; j++) {
 4850:         if (current[j] == undefined) {
 4851:             oldVal = j;
 4852:         }
 4853:     }
 4854:     if (oldVal < changedVal) {
 4855:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4856:            var elementName = current[k];
 4857:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4858:         }
 4859:     } else {
 4860:         for (var k=changedVal; k<oldVal; k++) {
 4861:             var elementName = current[k];
 4862:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4863:         }
 4864:     }
 4865:     return;
 4866: }
 4867: 
 4868: function helpdeskAccess(num) {
 4869:     var curraccess = null;
 4870:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4871:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4872:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4873:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4874:             }
 4875:         }
 4876:     }
 4877:     var shown = Array();
 4878:     var hidden = Array();
 4879:     if (curraccess == 'none') {
 4880:         hidden = Array('$hiddenstr');
 4881:     } else {
 4882:         if (curraccess == 'status') {
 4883:             shown = Array('bystatus');
 4884:             hidden = Array('notinc','notexc');
 4885:         } else {
 4886:             if (curraccess == 'exc') {
 4887:                 shown = Array('notexc');
 4888:                 hidden = Array('notinc','bystatus');
 4889:             }
 4890:             if (curraccess == 'inc') {
 4891:                 shown = Array('notinc');
 4892:                 hidden = Array('notexc','bystatus');
 4893:             }
 4894:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4895:                 hidden = Array('notinc','notexc','bystatus');
 4896:             }
 4897:         }
 4898:     }
 4899:     if (hidden.length > 0) {
 4900:         for (var i=0; i<hidden.length; i++) {
 4901:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4902:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4903:             }
 4904:         }
 4905:     }
 4906:     if (shown.length > 0) {
 4907:         for (var i=0; i<shown.length; i++) {
 4908:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4909:                 if (shown[i] == 'privs') {
 4910:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4911:                 } else {
 4912:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4913:                 }
 4914:             }
 4915:         }
 4916:     }
 4917:     return;
 4918: }
 4919: 
 4920: function toggleHelpdeskItem(num,field) {
 4921:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4922:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4923:             document.getElementById('helproles_'+num+'_'+field).className =
 4924:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4925:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4926:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4927:             }
 4928:         } else {
 4929:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4930:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4931:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4932:             }
 4933:         }
 4934:     }
 4935:     return;
 4936: }
 4937: 
 4938: // ]]>
 4939: </script>
 4940: 
 4941: ENDSCRIPT
 4942: }
 4943: 
 4944: sub helpdeskroles_access {
 4945:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4946:         $usertypes,$types,$domhelpdesk) = @_;
 4947:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4948:     my %lt = &Apache::lonlocal::texthash(
 4949:                     'rou'    => 'Role usage',
 4950:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4951:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4952:                     'dh'     => 'All with domain helpdesk role',
 4953:                     'da'     => 'All with domain helpdesk assistant role',
 4954:                     'none'   => 'None',
 4955:                     'status' => 'Determined based on institutional status',
 4956:                     'inc'    => 'Include all, but exclude specific personnel',
 4957:                     'exc'    => 'Exclude all, but include specific personnel',
 4958:                   );
 4959:     my %usecheck = (
 4960:                      all => ' checked="checked"',
 4961:                    );
 4962:     my %displaydiv = (
 4963:                       status => 'none',
 4964:                       inc    => 'none',
 4965:                       exc    => 'none',
 4966:                       priv   => 'block',
 4967:                      );
 4968:     my $output;
 4969:     if (ref($current) eq 'HASH') {
 4970:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4971:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4972:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4973:                 delete($usecheck{'all'});
 4974:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4975:                     my $access = $1;
 4976:                     $displaydiv{$access} = 'inline';
 4977:                 } elsif ($current->{access} eq 'none') {
 4978:                     $displaydiv{'priv'} = 'none';
 4979:                 }
 4980:             }
 4981:         }
 4982:     }
 4983:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4984:               '<p>'.$lt{'whi'}.'</p>';
 4985:     foreach my $access (@{$accesstypes}) {
 4986:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4987:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4988:                    $lt{$access}.'</label>';
 4989:         if ($access eq 'status') {
 4990:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4991:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4992:                                                                  $othertitle,$usertypes,$types).
 4993:                        '</div>';
 4994:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4995:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4996:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4997:                        '</div>';
 4998:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4999:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 5000:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5001:                        '</div>';
 5002:         }
 5003:         $output .= '</p>';
 5004:     }
 5005:     $output .= '</fieldset>';
 5006:     return $output;
 5007: }
 5008: 
 5009: sub radiobutton_prefs {
 5010:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 5011:         $additional,$align,$firstval) = @_;
 5012:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 5013:                    (ref($choices) eq 'HASH'));
 5014: 
 5015:     my (%checkedon,%checkedoff,$datatable,$css_class);
 5016: 
 5017:     foreach my $item (@{$toggles}) {
 5018:         if ($defaultchecked->{$item} eq 'on') {
 5019:             $checkedon{$item} = ' checked="checked" ';
 5020:             $checkedoff{$item} = ' ';
 5021:         } elsif ($defaultchecked->{$item} eq 'off') {
 5022:             $checkedoff{$item} = ' checked="checked" ';
 5023:             $checkedon{$item} = ' ';
 5024:         }
 5025:     }
 5026:     if (ref($settings) eq 'HASH') {
 5027:         foreach my $item (@{$toggles}) {
 5028:             if ($settings->{$item} eq '1') {
 5029:                 $checkedon{$item} =  ' checked="checked" ';
 5030:                 $checkedoff{$item} = ' ';
 5031:             } elsif ($settings->{$item} eq '0') {
 5032:                 $checkedoff{$item} =  ' checked="checked" ';
 5033:                 $checkedon{$item} = ' ';
 5034:             }
 5035:         }
 5036:     }
 5037:     if ($onclick) {
 5038:         $onclick = ' onclick="'.$onclick.'"';
 5039:     }
 5040:     foreach my $item (@{$toggles}) {
 5041:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5042:         $datatable .=
 5043:             '<tr'.$css_class.'><td valign="top">'.
 5044:             '<span class="LC_nobreak">'.$choices->{$item}.
 5045:             '</span></td>';
 5046:         if ($align eq 'left') {
 5047:             $datatable .= '<td class="LC_left_item">';
 5048:         } else {
 5049:             $datatable .= '<td class="LC_right_item">';
 5050:         }
 5051:         $datatable .= '<span class="LC_nobreak">';
 5052:         if ($firstval eq 'no') {
 5053:             $datatable .=
 5054:                 '<label><input type="radio" name="'.
 5055:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 5056:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5057:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 5058:         } else {
 5059:             $datatable .=
 5060:                 '<label><input type="radio" name="'.
 5061:                 $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 5062:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5063:                 $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 5064:         }
 5065:         $datatable .= '</span>'.$additional.'</td></tr>';
 5066:         $itemcount ++;
 5067:     }
 5068:     return ($datatable,$itemcount);
 5069: }
 5070: 
 5071: sub print_ltitools {
 5072:     my ($position,$dom,$settings,$rowtotal) = @_;
 5073:     my (%rules,%encrypt,%privkeys,%linkprot);
 5074:     if (ref($settings) eq 'HASH') {
 5075:         if ($position eq 'top') {
 5076:             if (exists($settings->{'encrypt'})) {
 5077:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 5078:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 5079:                         $encrypt{'toolsec_'.$key} = $settings->{'encrypt'}{$key};
 5080:                     }
 5081:                 }
 5082:             }
 5083:             if (exists($settings->{'private'})) {
 5084:                 if (ref($settings->{'private'}) eq 'HASH') {
 5085:                     if (ref($settings->{'private'}) eq 'HASH') {
 5086:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 5087:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 5088:                         }
 5089:                     }
 5090:                 }
 5091:             }
 5092:         } elsif ($position eq 'middle') {
 5093:             if (exists($settings->{'rules'})) {
 5094:                 if (ref($settings->{'rules'}) eq 'HASH') {
 5095:                     %rules = %{$settings->{'rules'}};
 5096:                 }
 5097:             }
 5098:         } else {
 5099:             foreach my $key ('encrypt','private','rules') {
 5100:                 if (exists($settings->{$key})) {
 5101:                     delete($settings->{$key});
 5102:                 }
 5103:             }
 5104:         }
 5105:     }
 5106:     my $datatable;
 5107:     my $itemcount = 1;
 5108:     if ($position eq 'top') {
 5109:         $datatable = &secrets_form($dom,'toolsec',\%encrypt,\%privkeys,$rowtotal);
 5110:     } elsif ($position eq 'middle') {
 5111:         $datatable = &password_rules('toolsecrets',\$itemcount,\%rules);
 5112:         $$rowtotal += $itemcount;
 5113:     } else {
 5114:         $datatable = &Apache::courseprefs::print_ltitools($dom,'',$settings,\$rowtotal,'','','domain');
 5115:     }
 5116:     return $datatable;
 5117: }
 5118: 
 5119: sub ltitools_names {
 5120:     my %lt = &Apache::lonlocal::texthash(
 5121:                                           'title'          => 'Title',
 5122:                                           'version'        => 'Version',
 5123:                                           'msgtype'        => 'Message Type',
 5124:                                           'sigmethod'      => 'Signature Method',
 5125:                                           'url'            => 'URL',
 5126:                                           'key'            => 'Key',
 5127:                                           'lifetime'       => 'Nonce lifetime (s)',
 5128:                                           'secret'         => 'Secret',
 5129:                                           'icon'           => 'Icon',
 5130:                                           'user'           => 'User',
 5131:                                           'fullname'       => 'Full Name',
 5132:                                           'firstname'      => 'First Name',
 5133:                                           'lastname'       => 'Last Name',
 5134:                                           'email'          => 'E-mail',
 5135:                                           'roles'          => 'Role',
 5136:                                           'window'         => 'Window',
 5137:                                           'tab'            => 'Tab',
 5138:                                           'iframe'         => 'iFrame',
 5139:                                           'height'         => 'Height',
 5140:                                           'width'          => 'Width',
 5141:                                           'linktext'       => 'Default Link Text',
 5142:                                           'explanation'    => 'Default Explanation',
 5143:                                           'passback'       => 'Tool can return grades:',
 5144:                                           'roster'         => 'Tool can retrieve roster:',
 5145:                                           'crstarget'      => 'Display target',
 5146:                                           'crslabel'       => 'Course label',
 5147:                                           'crstitle'       => 'Course title',
 5148:                                           'crslinktext'    => 'Link Text',
 5149:                                           'crsexplanation' => 'Explanation',
 5150:                                           'crsappend'      => 'Provider URL',
 5151:                                         );
 5152:     return %lt;
 5153: }
 5154: 
 5155: sub secrets_form {
 5156:     my ($dom,$context,$encrypt,$privkeys,$rowtotal) = @_;
 5157:     my @ids=&Apache::lonnet::current_machine_ids();
 5158:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 5159:     my $primary = &Apache::lonnet::domain($dom,'primary');
 5160:     my ($css_class,$extra,$numshown,$itemcount,$output);
 5161:     $itemcount = 0;
 5162:     foreach my $hostid (sort(keys(%servers))) {
 5163:         my ($showextra,$divsty,$switch);
 5164:         if ($hostid eq $primary) {
 5165:             if ($context eq 'ltisec') {
 5166:                 if (($encrypt->{'ltisec_consumers'}) || ($encrypt->{'ltisec_domlinkprot'})) {
 5167:                     $showextra = 1;
 5168:                 }
 5169:                 if ($encrypt->{'ltisec_crslinkprot'}) {
 5170:                     $showextra = 1;
 5171:                 }
 5172:             } else {
 5173:                 if (($encrypt->{'toolsec_crs'}) || ($encrypt->{'toolsec_dom'})) {
 5174:                     $showextra = 1;
 5175:                 }
 5176:             }
 5177:             unless (grep(/^\Q$hostid\E$/,@ids)) {
 5178:                 $switch = 1;
 5179:             }
 5180:             if ($showextra) {
 5181:                 $numshown ++;
 5182:                 $divsty = 'display:inline-block';
 5183:             } else {
 5184:                 $divsty = 'display:none';
 5185:             }
 5186:             $extra .= '<fieldset id="'.$context.'_info_'.$hostid.'" style="'.$divsty.'">'.
 5187:                       '<legend>'.$hostid.'</legend>';
 5188:             if ($switch) {
 5189:                 my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
 5190:                                    &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 5191:                                    '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 5192:                 if (exists($privkeys->{$hostid})) {
 5193:                     $extra .= '<div id="'.$context.'_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
 5194:                               '<span class="LC_nobreak">'.
 5195:                               &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 5196:                               '<span class="LC_nobreak">'.&mt('Change?').
 5197:                               '<label><input type="radio" value="0" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 5198:                               ('&nbsp;'x2).
 5199:                               '<label><input type="radio" value="1" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" />'.&mt('Yes').
 5200:                               '</label>&nbsp;&nbsp;</span><div id="'.$context.'_divchgprivkey_'.$hostid.'" style="display:none" />'.
 5201:                               '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 5202:                               '</span></div>';
 5203:                 } else {
 5204:                     $extra .= '<span class="LC_nobreak">'.
 5205:                               &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 5206:                               '</span>'."\n";
 5207:                 }
 5208:             } elsif (exists($privkeys->{$hostid})) {
 5209:                 $extra .= '<div id="'.$context.'_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
 5210:                           &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 5211:                           '<span class="LC_nobreak">'.&mt('Change?').
 5212:                           '<label><input type="radio" value="0" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 5213:                           ('&nbsp;'x2).
 5214:                           '<label><input type="radio" value="1" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" />'.&mt('Yes').
 5215:                           '</label>&nbsp;&nbsp;</span><div id="'.$context.'_divchgprivkey_'.$hostid.'" style="display:none" />'.
 5216:                           '<span class="LC_nobreak">'.&mt('New Key').':'.
 5217:                           '<input type="password" size="20" name="'.$context.'_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
 5218:                           '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.'.$context.'_privkey_'.$hostid.'.type='."'text'".' } else { this.form.'.$context.'_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 5219:                           '</span></div>';
 5220:             } else {
 5221:                 $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
 5222:                           '<input type="password" size="20" name="'.$context.'_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
 5223:                           '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.'.$context.'_privkey_'.$hostid.'.type='."'text'".' } else { this.form.'.$context.'_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>';
 5224:             }
 5225:             $extra .= '</fieldset>';
 5226:         }
 5227:     }
 5228:     my (%choices,@toggles,%defaultchecked);
 5229:     if ($context eq 'ltisec') {
 5230:         %choices = &Apache::lonlocal::texthash (
 5231:                                                   ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
 5232:                                                   ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
 5233:                                                   ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
 5234:                                                );
 5235:         @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
 5236:         %defaultchecked = (
 5237:                            'ltisec_crslinkprot' => 'off',
 5238:                            'ltisec_domlinkprot' => 'off',
 5239:                            'ltisec_consumers'   => 'off',
 5240:                           );
 5241:     } else {
 5242:         %choices = &Apache::lonlocal::texthash (
 5243:                                                   toolsec_crs => 'Encrypt stored external tool secrets defined in courses',
 5244:                                                   toolsec_dom => 'Encrypt stored external tool secrets defined in domain',
 5245:                                                );
 5246:         @toggles = qw(toolsec_crs toolsec_dom);
 5247:         %defaultchecked = (
 5248:                            'toolsec_crs' => 'off',
 5249:                            'toolsec_dom' => 'off',
 5250:                           );
 5251:     }
 5252:     my ($onclick,$itemcount);
 5253:     $onclick = 'javascript:toggleLTIEncKey(this.form,'."'$context'".');';
 5254:     ($output,$itemcount) = &radiobutton_prefs($encrypt,\@toggles,\%defaultchecked,
 5255:                                               \%choices,$itemcount,$onclick,'','left','no');
 5256: 
 5257:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5258:     my $noprivkeysty = 'display:inline-block';
 5259:     if ($numshown) {
 5260:         $noprivkeysty = 'display:none';
 5261:     }
 5262:     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
 5263:                '<td><div id="'.$context.'_noprivkey" style="'.$noprivkeysty.'" >'.
 5264:                '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
 5265:                $extra.
 5266:                '</td></tr>';
 5267:     $itemcount ++;
 5268:     $$rowtotal += $itemcount;
 5269:     return $output;
 5270: }
 5271: 
 5272: sub print_lti {
 5273:     my ($position,$dom,$settings,$rowtotal) = @_;
 5274:     my $itemcount = 1;
 5275:     my ($datatable,$css_class);
 5276:     my (%rules,%encrypt,%privkeys,%linkprot);
 5277:     if (ref($settings) eq 'HASH') {
 5278:         if ($position eq 'top') {
 5279:             if (exists($settings->{'encrypt'})) {
 5280:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 5281:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 5282:                         if ($key eq 'consumers') {
 5283:                             $encrypt{'ltisec_'.$key} = $settings->{'encrypt'}{$key};
 5284:                         } else {
 5285:                             $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
 5286:                         }
 5287:                     }
 5288:                 }
 5289:             }
 5290:             if (exists($settings->{'private'})) {
 5291:                 if (ref($settings->{'private'}) eq 'HASH') {
 5292:                     if (ref($settings->{'private'}) eq 'HASH') {
 5293:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 5294:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 5295:                         }
 5296:                     }
 5297:                 }
 5298:             }
 5299:         } elsif ($position eq 'middle') {
 5300:             if (exists($settings->{'rules'})) {
 5301:                 if (ref($settings->{'rules'}) eq 'HASH') {
 5302:                     %rules = %{$settings->{'rules'}};
 5303:                 }
 5304:             }
 5305:         } elsif ($position eq 'lower') {
 5306:             if (exists($settings->{'linkprot'})) {
 5307:                 if (ref($settings->{'linkprot'}) eq 'HASH') {
 5308:                     %linkprot = %{$settings->{'linkprot'}};
 5309:                     if ($linkprot{'lock'}) {
 5310:                         delete($linkprot{'lock'});
 5311:                     }
 5312:                 }
 5313:             }
 5314:         } else {
 5315:             foreach my $key ('encrypt','private','rules','linkprot') {
 5316:                 if (exists($settings->{$key})) {
 5317:                     delete($settings->{$key});
 5318:                 }
 5319:             }
 5320:         }
 5321:     }
 5322:     if ($position eq 'top') {
 5323:         $datatable = &secrets_form($dom,'ltisec',\%encrypt,\%privkeys,$rowtotal);
 5324:     } elsif ($position eq 'middle') {
 5325:         $datatable = &password_rules('ltisecrets',\$itemcount,\%rules);
 5326:         $$rowtotal += $itemcount;
 5327:     } elsif ($position eq 'lower') {
 5328:          $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
 5329:     } else {
 5330:         my ($switchserver,$switchmessage);
 5331:         $switchserver = &check_switchserver($dom);
 5332:         $switchmessage = &mt("submit from domain's primary library server: [_1].",$switchserver);
 5333:         my $maxnum = 0;
 5334:         my %ordered;
 5335:         if (ref($settings) eq 'HASH') {
 5336:             foreach my $item (keys(%{$settings})) {
 5337:                 if (ref($settings->{$item}) eq 'HASH') {
 5338:                     my $num = $settings->{$item}{'order'};
 5339:                     if ($num eq '') {
 5340:                         $num = scalar(keys(%{$settings}));
 5341:                     }
 5342:                     $ordered{$num} = $item;
 5343:                 }
 5344:             }
 5345:         }
 5346:         $maxnum = scalar(keys(%ordered));
 5347:         my %lt = &lti_names();
 5348:         if (keys(%ordered)) {
 5349:             my @items = sort { $a <=> $b } keys(%ordered);
 5350:             for (my $i=0; $i<@items; $i++) {
 5351:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5352:                 my $item = $ordered{$items[$i]};
 5353:                 my ($key,$secret,$usable,$lifetime,$consumer,$requser,$crsinc,$current);
 5354:                 if (ref($settings->{$item}) eq 'HASH') {
 5355:                     $key = $settings->{$item}->{'key'};
 5356:                     $usable = $settings->{$item}->{'usable'};
 5357:                     $lifetime = $settings->{$item}->{'lifetime'};
 5358:                     $consumer = $settings->{$item}->{'consumer'};
 5359:                     $requser = $settings->{$item}->{'requser'};
 5360:                     $crsinc = $settings->{$item}->{'crsinc'};
 5361:                     $current = $settings->{$item};
 5362:                 }
 5363:                 my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 5364:                 my %checkedrequser = (
 5365:                                        yes => ' checked="checked"',
 5366:                                        no  => '',
 5367:                                      );
 5368:                 if (!$requser) {
 5369:                     $checkedrequser{'no'} = $checkedrequser{'yes'};
 5370:                     $checkedrequser{'yes'} = '';
 5371:                 }
 5372:                 my $onclickcrsinc = ' onclick="toggleLTI(this.form,'."'crsinc','$i'".');"';
 5373:                 my %checkedcrsinc = (
 5374:                                       yes => ' checked="checked"',
 5375:                                       no  => '',
 5376:                                     );
 5377:                 if (!$crsinc) {
 5378:                     $checkedcrsinc{'no'} = $checkedcrsinc{'yes'};
 5379:                     $checkedcrsinc{'yes'} = '';
 5380:                 }
 5381:                 my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 5382:                 $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5383:                              .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 5384:                 for (my $k=0; $k<=$maxnum; $k++) {
 5385:                     my $vpos = $k+1;
 5386:                     my $selstr;
 5387:                     if ($k == $i) {
 5388:                         $selstr = ' selected="selected" ';
 5389:                     }
 5390:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5391:                 }
 5392:                 $datatable .= '</select>'.('&nbsp;'x2).
 5393:                     '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 5394:                     &mt('Delete?').'</label></span></td>'.
 5395:                     '<td colspan="2">'.
 5396:                     '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5397:                     '<span class="LC_nobreak">'.$lt{'consumer'}.
 5398:                     ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 5399:                     ('&nbsp;'x2).
 5400:                     '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 5401:                     '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 5402:                     ('&nbsp;'x2).
 5403:                     '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 5404:                     'value="'.$lifetime.'" size="3" /></span><br /><br />';
 5405:                 if ($key ne '') {
 5406:                     $datatable .= '<span class="LC_nobreak">'.$lt{'key'};
 5407:                     if ($switchserver) {
 5408:                         $datatable .= ': ['.&mt('[_1] to view/edit',$switchserver).']';
 5409:                     } else {
 5410:                         $datatable .= ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" autocomplete="off" />';
 5411:                     }
 5412:                     $datatable .= '</span> '.('&nbsp;'x2);
 5413:                 } elsif (!$switchserver) {
 5414:                     $datatable .= '<span class="LC_nobreak">'.$lt{'key'}.':'.
 5415:                                   '<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" autocomplete="off" />'.
 5416:                                   '</span> '.('&nbsp;'x2);
 5417:                 }
 5418:                 if ($switchserver) {
 5419:                     if ($usable ne '') {
 5420:                         $datatable .= '<div id="lti_divcurrsecret_'.$i.'" style="display:inline-block" /><span class="LC_nobreak">'.
 5421:                                       $lt{'secret'}.': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 5422:                                       '<span class="LC_nobreak">'.&mt('Change secret?').
 5423:                                       '<label><input type="radio" value="0" name="lti_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','lti'".');" checked="checked" />'.&mt('No').'</label>'.
 5424:                                       ('&nbsp;'x2).
 5425:                                      '<label><input type="radio" value="1" name="lti_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','lti'".');" />'.&mt('Yes').'</label>'.('&nbsp;'x2).
 5426:                                       '</span><div id="lti_divchgsecret_'.$i.'" style="display:none" />'.
 5427:                                       '<span class="LC_nobreak"> - '.$switchmessage.'</span>'.
 5428:                                       '</div>';
 5429:                     } elsif ($key eq '') {
 5430:                         $datatable .= '<span class="LC_nobreak">'.&mt('Key and Secret are required').' - '.$switchmessage.'</span>'."\n";
 5431:                     } else {
 5432:                         $datatable .= '<span class="LC_nobreak">'.&mt('Secret required').' - '.$switchmessage.'</span>'."\n";
 5433:                     }
 5434:                 } else {
 5435:                     if ($usable ne '') {
 5436:                         $datatable .= '<div id="lti_divcurrsecret_'.$i.'" style="display:inline-block" /><span class="LC_nobreak">'.
 5437:                                       $lt{'secret'}.': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 5438:                                       '<span class="LC_nobreak">'.&mt('Change?').
 5439:                                       '<label><input type="radio" value="0" name="lti_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','lti'".');" checked="checked" />'.&mt('No').'</label>'.
 5440:                                       ('&nbsp;'x2).
 5441:                                       '<label><input type="radio" value="1" name="lti_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','lti'".');" />'.&mt('Yes').
 5442:                                       '</label>&nbsp;&nbsp;</span><div id="lti_divchgsecret_'.$i.'" style="display:none" />'.
 5443:                                       '<span class="LC_nobreak">'.&mt('New Secret').':'.
 5444:                                       '<input type="password" size="20" name="lti_secret_'.$i.'" value="" autocomplete="new-password" />'.
 5445:                                       '<label><input type="checkbox" name="lti_visible_'.$i.'" id="lti_visible_'.$i.'" onclick="if (this.checked) { this.form.lti_secret_'.$i.'.type='."'text'".' } else { this.form.lti_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label></span></div>';
 5446:                     } else {
 5447:                         $datatable .=
 5448:                             '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 5449:                             '<input type="password" size="20" name="lti_secret_'.$i.'" value="" autocomplete="new-password" />'.
 5450:                             '<label><input type="checkbox" name="lti_visible_'.$i.'" id="lti_visible_'.$i.'" onclick="if (this.checked) { this.form.lti_secret_'.$i.'.type='."'text'".' } else { this.form.lti_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label>';
 5451:                     }
 5452:                 }
 5453:                 $datatable .= '<br /><br />'.
 5454:                     '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 5455:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5456:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 5457:                     '<br /><br />'.
 5458:                     '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 5459:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="1"'.$onclickcrsinc.$checkedcrsinc{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5460:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="0"'.$onclickcrsinc.$checkedcrsinc{no}.' />'.&mt('No').'</label></span>'."\n".
 5461:                     ('&nbsp;'x4).
 5462:                     '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 5463:                     '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 5464:                 $itemcount ++;
 5465:             }
 5466:         }
 5467:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5468:         my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 5469:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5470:                       '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 5471:                       '<select name="lti_pos_add"'.$chgstr.'>';
 5472:         for (my $k=0; $k<$maxnum+1; $k++) {
 5473:             my $vpos = $k+1;
 5474:             my $selstr;
 5475:             if ($k == $maxnum) {
 5476:                 $selstr = ' selected="selected" ';
 5477:             }
 5478:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5479:         }
 5480:         $datatable .= '</select>&nbsp;'."\n".
 5481:                       '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5482:                       '<td colspan="2">'.
 5483:                       '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5484:                       '<span class="LC_nobreak">'.$lt{'consumer'}.
 5485:                       ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 5486:                       ('&nbsp;'x2).
 5487:                       '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 5488:                       '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5489:                       ('&nbsp;'x2).
 5490:                       '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span><br /><br />'."\n";
 5491:         if ($switchserver) {
 5492:             $datatable .= '<span class="LC_nobreak">'.&mt('Key and Secret are required').' - '.$switchmessage.'</span>'."\n";
 5493:         } else {
 5494:             $datatable .= '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" autocomplete="off" /></span> '."\n".
 5495:                           ('&nbsp;'x2).
 5496:                           '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" autocomplete="new-password" />'.
 5497:                           '<label><input type="checkbox" name="lti_add_visible" id="lti_add_visible" onclick="if (this.checked) { this.form.lti_secret_add.type='."'text'".' } else { this.form.lti_secret_add.type='."'password'".' }" />'.&mt('Visible input').'</label></span> '."\n";
 5498:         }
 5499:         $datatable .= '<br /><br />'.
 5500:                       '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 5501:                       '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 5502:                       '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 5503:                       '<br /><br />'.
 5504:                       '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 5505:                       '<label><input type="radio" name="lti_crsinc_add" value="1" onclick="toggleLTI(this.form,'."'crsinc','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 5506:                       '<label><input type="radio" name="lti_crsinc_add" value="0" onclick="toggleLTI(this.form,'."'crsinc','add'".');" />'.&mt('No').'</label></span>'."\n".
 5507:                       '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 5508:                       '</td>'."\n".
 5509:                       '</tr>'."\n";
 5510:         $itemcount ++;
 5511:     }
 5512:     $$rowtotal += $itemcount;
 5513:     return $datatable;
 5514: }
 5515: 
 5516: sub lti_names {
 5517:     my %lt = &Apache::lonlocal::texthash(
 5518:                                           'version'   => 'LTI Version',
 5519:                                           'url'       => 'URL',
 5520:                                           'key'       => 'Key',
 5521:                                           'lifetime'  => 'Nonce lifetime (s)',
 5522:                                           'consumer'  => 'Consumer',
 5523:                                           'secret'    => 'Secret',
 5524:                                           'requser'   => "User's identity sent",
 5525:                                           'crsinc'    => "Course's identity sent",
 5526:                                           'email'     => 'Email address',
 5527:                                           'sourcedid' => 'User ID',
 5528:                                           'other'     => 'Other',
 5529:                                           'passback'  => 'Can return grades to Consumer:',
 5530:                                           'roster'    => 'Can retrieve roster from Consumer:',
 5531:                                           'topmenu'   => 'Display LON-CAPA page header',
 5532:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 5533:                                         );
 5534:     return %lt;
 5535: }
 5536: 
 5537: sub lti_options {
 5538:     my ($num,$current,$itemcount,%lt) = @_;
 5539:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 5540:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 5541:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 5542:     $checked{'storecrs'}{'Y'} = ' checked="checked"';
 5543:     $checked{'makecrs'}{'N'} = ' checked="checked"';
 5544:     $checked{'mapcrstype'} = {};
 5545:     $checked{'makeuser'} = {};
 5546:     $checked{'selfenroll'} = {};
 5547:     $checked{'crssec'} = {};
 5548:     $checked{'crssecsrc'} = {};
 5549:     $checked{'lcauth'} = {};
 5550:     $checked{'menuitem'} = {};
 5551:     if ($num eq 'add') {
 5552:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 5553:     }
 5554:     my $userfieldsty = 'none';
 5555:     my $crsfieldsty = 'none';
 5556:     my $crssecfieldsty = 'none';
 5557:     my $secsrcfieldsty = 'none';
 5558:     my $callbacksty = 'none';
 5559:     my $passbacksty = 'none';
 5560:     my $optionsty = 'block';
 5561:     my $crssty = 'block';
 5562:     my $lcauthparm;
 5563:     my $lcauthparmstyle = 'display:none';
 5564:     my $lcauthparmtext;
 5565:     my $menusty;
 5566:     my $numinrow = 4;
 5567:     my %menutitles = &ltimenu_titles();
 5568: 
 5569:     if (ref($current) eq 'HASH') {
 5570:         if (!$current->{'requser'}) {
 5571:             $optionsty = 'none';
 5572:             $crssty = 'none';
 5573:         } elsif (!$current->{'crsinc'}) {
 5574:             $crssty = 'none';
 5575:         }
 5576:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 5577:             $checked{'mapuser'}{'sourcedid'} = '';
 5578:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 5579:                 $checked{'mapuser'}{'email'} = ' checked="checked"';
 5580:             } else {
 5581:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 5582:                 $userfield = $current->{'mapuser'};
 5583:                 $userfieldsty = 'inline-block';
 5584:             }
 5585:         }
 5586:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 5587:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 5588:             if ($current->{'mapcrs'} eq 'context_id') {
 5589:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"';
 5590:             } else {
 5591:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 5592:                 $cidfield = $current->{'mapcrs'};
 5593:                 $crsfieldsty = 'inline-block';
 5594:             }
 5595:         }
 5596:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 5597:             foreach my $type (@{$current->{'mapcrstype'}}) {
 5598:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 5599:             }
 5600:         }
 5601:         if (!$current->{'storecrs'}) {
 5602:             $checked{'storecrs'}{'N'} = $checked{'storecrs'}{'Y'};
 5603:             $checked{'storecrs'}{'Y'} = '';
 5604:         }
 5605:         if ($current->{'makecrs'}) {
 5606:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 5607:         }
 5608:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 5609:             foreach my $role (@{$current->{'makeuser'}}) {
 5610:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 5611:             }
 5612:         }
 5613:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 5614:             $checked{'lcauth'}{$1} = ' checked="checked"';
 5615:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 5616:                 $lcauthparm = $current->{'lcauthparm'};
 5617:                 $lcauthparmstyle = 'display:table-row';
 5618:                 if ($current->{'lcauth'} eq 'localauth') {
 5619:                     $lcauthparmtext = &mt('Local auth argument');
 5620:                 } else {
 5621:                     $lcauthparmtext = &mt('Kerberos domain');
 5622:                 }
 5623:             }
 5624:         }
 5625:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 5626:             foreach my $role (@{$current->{'selfenroll'}}) {
 5627:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 5628:             }
 5629:         }
 5630:         if (ref($current->{'maproles'}) eq 'HASH') {
 5631:             %rolemaps = %{$current->{'maproles'}};
 5632:         }
 5633:         if ($current->{'section'} ne '') {
 5634:             $checked{'crssec'}{'Y'} = '  checked="checked"';
 5635:             $crssecfieldsty = 'inline-block';
 5636:             if ($current->{'section'} eq 'course_section_sourcedid') {
 5637:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 5638:             } else {
 5639:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 5640:                 $crssecsrc = $current->{'section'};
 5641:                 $secsrcfieldsty = 'inline-block';
 5642:             }
 5643:         } else {
 5644:             $checked{'crssec'}{'N'} = ' checked="checked"';
 5645:         }
 5646:         if ($current->{'callback'} ne '') {
 5647:             $callback = $current->{'callback'};
 5648:             $checked{'callback'}{'Y'} = ' checked="checked"';
 5649:             $callbacksty = 'inline-block';
 5650:         } else {
 5651:             $checked{'callback'}{'N'} = ' checked="checked"';
 5652:         }
 5653:         if ($current->{'topmenu'}) {
 5654:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 5655:         } else {
 5656:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 5657:         }
 5658:         if ($current->{'inlinemenu'}) {
 5659:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 5660:         } else {
 5661:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 5662:         }
 5663:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 5664:             $menusty = 'inline-block';
 5665:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 5666:                 foreach my $item (@{$current->{'lcmenu'}}) {
 5667:                     if (exists($menutitles{$item})) {
 5668:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 5669:                     }
 5670:                 }
 5671:             }
 5672:         } else {
 5673:             $menusty = 'none';
 5674:         }
 5675:     } else {
 5676:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 5677:         $checked{'crssec'}{'N'} = ' checked="checked"';
 5678:         $checked{'callback'}{'N'} = ' checked="checked"';
 5679:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 5680:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 5681:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 5682:         $menusty = 'inline-block';
 5683:     }
 5684:     my @coursetypes = ('official','unofficial','community','textbook','lti');
 5685:     my %coursetypetitles = &Apache::lonlocal::texthash (
 5686:                                official   => 'Official',
 5687:                                unofficial => 'Unofficial',
 5688:                                community  => 'Community',
 5689:                                textbook   => 'Textbook',
 5690:                                lti        => 'LTI Provider',
 5691:     );
 5692:     my @authtypes = ('internal','krb4','krb5','localauth');
 5693:     my %shortauth = (
 5694:                      internal => 'int',
 5695:                      krb4 => 'krb4',
 5696:                      krb5 => 'krb5',
 5697:                      localauth  => 'loc'
 5698:                     );
 5699:     my %authnames = &authtype_names();
 5700:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 5701:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 5702:     my @courseroles = ('cc','in','ta','ep','st');
 5703:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 5704:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 5705:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 5706:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 5707:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 5708:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 5709:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 5710:     my $output = '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Logout options').'</legend>'.
 5711:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback to logout LON-CAPA on log out from Consumer').':&nbsp;'.
 5712:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 5713:                  $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5714:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 5715:                  $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 5716:                  '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 5717:                  '<span class="LC_nobreak">'.&mt('Parameter').': '.
 5718:                  '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 5719:                  '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 5720:                  '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 5721:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 5722:     foreach my $option ('sourcedid','email','other') {
 5723:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 5724:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 5725:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 5726:     }
 5727:     $output .= '</span></div>'.
 5728:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 5729:                '<input type="text" name="lti_customuser_'.$num.'" '.
 5730:                'value="'.$userfield.'" /></div></fieldset>'.
 5731:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 5732:     foreach my $ltirole (@ltiroles) {
 5733:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 5734:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';
 5735:     }
 5736:     $output .= '</fieldset>'.
 5737:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 5738:                '<table>'.
 5739:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 5740:                '</table>'.
 5741:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 5742:                '<td class="LC_left_item">';
 5743:     foreach my $auth ('lti',@authtypes) {
 5744:         my $authtext;
 5745:         if ($auth eq 'lti') {
 5746:             $authtext = &mt('None');
 5747:         } else {
 5748:             $authtext = $authnames{$shortauth{$auth}};
 5749:         }
 5750:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 5751:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 5752:                    $authtext.'</label></span> &nbsp;';
 5753:     }
 5754:     $output .= '</td></tr>'.
 5755:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 5756:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 5757:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 5758:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 5759:                '</table></fieldset>'.
 5760:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.
 5761:                &mt('LON-CAPA menu items (Course Coordinator can override)').'</legend>'.
 5762:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 5763:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 5764:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5765:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 5766:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 5767:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5768:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 5769:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 5770:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5771:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 5772:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 5773:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5774:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 5775:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 5776:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 5777:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 5778:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 5779:                    ('&nbsp;'x2);
 5780:     }
 5781:     $output .= '</span></div></fieldset>'.
 5782:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 5783:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 5784:                &mt('Unique course identifier').':&nbsp;';
 5785:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 5786:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 5787:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 5788:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 5789:     }
 5790:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 5791:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 5792:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5793:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 5794:     foreach my $type (@coursetypes) {
 5795:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 5796:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 5797:                    ('&nbsp;'x2);
 5798:     }
 5799:     $output .= '</span><br /><br />'.
 5800:                '<span class="LC_nobreak">'.&mt('Store mapping of course identifier to LON-CAPA CourseID').':&nbsp;'.
 5801:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="0"'.
 5802:                $checked{'storecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5803:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="1"'.
 5804:                $checked{'storecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 5805:                '</fieldset>'.
 5806:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 5807:     foreach my $ltirole (@lticourseroles) {
 5808:         my ($selected,$selectnone);
 5809:         if ($rolemaps{$ltirole} eq '') {
 5810:             $selectnone = ' selected="selected"';
 5811:         }
 5812:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 5813:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 5814:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5815:         foreach my $role (@courseroles) {
 5816:             unless ($selectnone) {
 5817:                 if ($rolemaps{$ltirole} eq $role) {
 5818:                     $selected = ' selected="selected"';
 5819:                 } else {
 5820:                     $selected = '';
 5821:                 }
 5822:             }
 5823:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 5824:                        &Apache::lonnet::plaintext($role,'Course').
 5825:                        '</option>';
 5826:         }
 5827:         $output .= '</select></td>';
 5828:     }
 5829:     $output .= '</tr></table></fieldset>'.
 5830:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Creating courses').'</legend>'.
 5831:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 5832:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 5833:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5834:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 5835:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 5836:                '</fieldset>'.
 5837:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 5838:     foreach my $lticrsrole (@lticourseroles) {
 5839:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 5840:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 5841:     }
 5842:     $output .= '</fieldset>'.
 5843:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Course options').'</legend>'.
 5844:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 5845:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 5846:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5847:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 5848:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 5849:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 5850:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 5851:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 5852:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 5853:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 5854:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 5855:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 5856:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 5857:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 5858:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5859:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 5860:     foreach my $extra ('roster','passback') {
 5861:         my $checkedon = '';
 5862:         my $checkedoff = ' checked="checked"';
 5863:         if ($extra eq 'passback') {
 5864:             $pb1p1chk = ' checked="checked"';
 5865:             $pb1p0chk = '';
 5866:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"';
 5867:         } else {
 5868:             $onclickpb = '';
 5869:         }
 5870:         if (ref($current) eq 'HASH') {
 5871:             if (($current->{$extra})) {
 5872:                 $checkedon = $checkedoff;
 5873:                 $checkedoff = '';
 5874:                 if ($extra eq 'passback') {
 5875:                     $passbacksty = 'inline-block';
 5876:                 }
 5877:                 if ($current->{'passbackformat'} eq '1.0') {
 5878:                     $pb1p0chk =  ' checked="checked"';
 5879:                     $pb1p1chk = '';
 5880:                 }
 5881:             }
 5882:         }
 5883:         $output .= $lt{$extra}.'&nbsp;'.
 5884:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 5885:                    &mt('No').'</label>'.('&nbsp;'x2).
 5886:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 5887:                    &mt('Yes').'</label><br />';
 5888:     }
 5889:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 5890:                '<span class="LC_nobreak">'.&mt('Grade format').
 5891:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 5892:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 5893:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 5894:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 5895:                '<div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>';
 5896:     $output .= '</span></div></fieldset>';
 5897: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 5898: #
 5899: #    $output .= '</fieldset>'.
 5900: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 5901:     return $output;
 5902: }
 5903: 
 5904: sub ltimenu_titles {
 5905:     return &Apache::lonlocal::texthash(
 5906:                                         fullname    => 'Full name',
 5907:                                         coursetitle => 'Course title',
 5908:                                         role        => 'Role',
 5909:                                         logout      => 'Logout',
 5910:                                         grades      => 'Grades',
 5911:     );
 5912: }
 5913: 
 5914: 
 5915: 
 5916: sub print_coursedefaults {
 5917:     my ($position,$dom,$settings,$rowtotal) = @_;
 5918:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 5919:     my $itemcount = 1;
 5920:     my %choices =  &Apache::lonlocal::texthash (
 5921:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 5922:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 5923:         coursecredits        => 'Credits can be specified for courses',
 5924:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 5925:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 5926:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 5927:         texengine            => 'Default method to display mathematics',
 5928:         postsubmit           => 'Disable submit button/keypress following student submission',
 5929:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 5930:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 5931:         ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
 5932:         domexttool           => 'External Tools defined in the domain may be used in courses/communities (by type)',
 5933:         exttool              => 'External Tools can be defined and configured in courses/communities (by type)',
 5934:     );
 5935:     my %staticdefaults = (
 5936:                            anonsurvey_threshold => 10,
 5937:                            uploadquota          => 500,
 5938:                            postsubmit           => 60,
 5939:                            mysqltables          => 172800,
 5940:                            domexttool           => 1,
 5941:                            exttool              => 0,
 5942:                          );
 5943:     if ($position eq 'top') {
 5944:         %defaultchecked = (
 5945:                             'uselcmath'       => 'on',
 5946:                             'usejsme'         => 'on',
 5947:                             'inline_chem'     => 'on',
 5948:                             'canclone'        => 'none',
 5949:                           );
 5950:         @toggles = ('uselcmath','usejsme','inline_chem');
 5951:         my $deftex = $Apache::lonnet::deftex;
 5952:         if (ref($settings) eq 'HASH') {
 5953:             if ($settings->{'texengine'}) {
 5954:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 5955:                     $deftex = $settings->{'texengine'};
 5956:                 }
 5957:             }
 5958:         }
 5959:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5960:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 5961:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 5962:                        '</span></td><td class="LC_right_item">'.
 5963:                        '<select name="texengine">'."\n";
 5964:         my %texoptions = (
 5965:                             MathJax  => 'MathJax',
 5966:                             mimetex  => &mt('Convert to Images'),
 5967:                             tth      => &mt('TeX to HTML'),
 5968:                          );
 5969:         foreach my $renderer ('MathJax','mimetex','tth') {
 5970:             my $selected = '';
 5971:             if ($renderer eq $deftex) {
 5972:                 $selected = ' selected="selected"';
 5973:             }
 5974:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 5975:         }
 5976:         $mathdisp .= '</select></td></tr>'."\n";
 5977:         $itemcount ++;
 5978:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 5979:                                                      \%choices,$itemcount);
 5980:         $datatable = $mathdisp.$datatable;
 5981:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5982:         $datatable .=
 5983:             '<tr'.$css_class.'><td valign="top">'.
 5984:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 5985:             '</span></td><td class="LC_left_item">';
 5986:         my $currcanclone = 'none';
 5987:         my $onclick;
 5988:         my @cloneoptions = ('none','domain');
 5989:         my %clonetitles = &Apache::lonlocal::texthash (
 5990:                              none     => 'No additional course requesters',
 5991:                              domain   => "Any course requester in course's domain",
 5992:                              instcode => 'Course requests for official courses ...',
 5993:                           );
 5994:         my (%codedefaults,@code_order,@posscodes);
 5995:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 5996:                                                     \@code_order) eq 'ok') {
 5997:             if (@code_order > 0) {
 5998:                 push(@cloneoptions,'instcode');
 5999:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 6000:             }
 6001:         }
 6002:         if (ref($settings) eq 'HASH') {
 6003:             if ($settings->{'canclone'}) {
 6004:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 6005:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 6006:                         if (@code_order > 0) {
 6007:                             $currcanclone = 'instcode';
 6008:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 6009:                         }
 6010:                     }
 6011:                 } elsif ($settings->{'canclone'} eq 'domain') {
 6012:                     $currcanclone = $settings->{'canclone'};
 6013:                 }
 6014:             }
 6015:         }
 6016:         foreach my $option (@cloneoptions) {
 6017:             my ($checked,$additional);
 6018:             if ($currcanclone eq $option) {
 6019:                 $checked = ' checked="checked"';
 6020:             }
 6021:             if ($option eq 'instcode') {
 6022:                 if (@code_order) {
 6023:                     my $show = 'none';
 6024:                     if ($checked) {
 6025:                         $show = 'block';
 6026:                     }
 6027:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 6028:                                   &mt('Institutional codes for new and cloned course have identical:').
 6029:                                   '<br />';
 6030:                     foreach my $item (@code_order) {
 6031:                         my $codechk;
 6032:                         if ($checked) {
 6033:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 6034:                                 $codechk = ' checked="checked"';
 6035:                             }
 6036:                         }
 6037:                         $additional .= '<label>'.
 6038:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 6039:                                        $item.'</label>';
 6040:                     }
 6041:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 6042:                 }
 6043:             }
 6044:             $datatable .=
 6045:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 6046:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 6047:                 '</label>&nbsp;'.$additional.'</span><br />';
 6048:         }
 6049:         $datatable .= '</td>'.
 6050:                       '</tr>';
 6051:         $itemcount ++;
 6052:     } else {
 6053:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6054:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 6055:         my $currusecredits = 0;
 6056:         my $postsubmitclient = 1;
 6057:         my $ltiauth = 0;
 6058:         my %domexttool;
 6059:         my %exttool;
 6060:         my @types = ('official','unofficial','community','textbook');
 6061:         if (ref($settings) eq 'HASH') {
 6062:             if ($settings->{'ltiauth'}) {
 6063:                 $ltiauth = 1;
 6064:             }
 6065:             if (ref($settings->{'domexttool'}) eq 'HASH') {
 6066:                 foreach my $type (@types) {
 6067:                     if ($settings->{'domexttool'}->{$type}) {
 6068:                         $domexttool{$type} = ' checked="checked"';
 6069:                     }
 6070:                 }
 6071:             } else {
 6072:                 foreach my $type (@types) {
 6073:                     if ($staticdefaults{'domexttool'}) {
 6074:                         $domexttool{$type} = ' checked="checked"';
 6075:                     }
 6076:                 }
 6077:             }
 6078:             if (ref($settings->{'exttool'}) eq 'HASH') {
 6079:                 foreach my $type (@types) {
 6080:                     if ($settings->{'exttool'}->{$type}) {
 6081:                         $exttool{$type} = ' checked="checked"';
 6082:                     }
 6083:                 }
 6084:             }
 6085:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 6086:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 6087:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 6088:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 6089:                 }
 6090:             }
 6091:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 6092:                 foreach my $type (@types) {
 6093:                     next if ($type eq 'community');
 6094:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 6095:                     if ($defcredits{$type} ne '') {
 6096:                         $currusecredits = 1;
 6097:                     }
 6098:                 }
 6099:             }
 6100:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 6101:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 6102:                     $postsubmitclient = 0;
 6103:                     foreach my $type (@types) {
 6104:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6105:                     }
 6106:                 } else {
 6107:                     foreach my $type (@types) {
 6108:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 6109:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 6110:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 6111:                             } else {
 6112:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6113:                             }
 6114:                         } else {
 6115:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6116:                         }
 6117:                     }
 6118:                 }
 6119:             } else {
 6120:                 foreach my $type (@types) {
 6121:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6122:                 }
 6123:             }
 6124:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 6125:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 6126:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 6127:                 }
 6128:             } else {
 6129:                 foreach my $type (@types) {
 6130:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 6131:                 }
 6132:             }
 6133:         } else {
 6134:             foreach my $type (@types) {
 6135:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6136:                 if ($staticdefaults{'domexttool'}) {
 6137:                     $domexttool{$type} = ' checked="checked"';
 6138:                 }
 6139:             }
 6140:         }
 6141:         if (!$currdefresponder) {
 6142:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 6143:         } elsif ($currdefresponder < 1) {
 6144:             $currdefresponder = 1;
 6145:         }
 6146:         foreach my $type (@types) {
 6147:             if ($curruploadquota{$type} eq '') {
 6148:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 6149:             }
 6150:         }
 6151:         $datatable .=
 6152:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6153:                 $choices{'anonsurvey_threshold'}.
 6154:                 '</span></td>'.
 6155:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 6156:                 '<input type="text" name="anonsurvey_threshold"'.
 6157:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 6158:                 '</td></tr>'."\n";
 6159:         $itemcount ++;
 6160:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6161:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6162:                       $choices{'uploadquota'}.
 6163:                       '</span></td>'.
 6164:                       '<td align="right" class="LC_right_item">'.
 6165:                       '<table><tr>';
 6166:         foreach my $type (@types) {
 6167:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 6168:                            '<input type="text" name="uploadquota_'.$type.'"'.
 6169:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 6170:         }
 6171:         $datatable .= '</tr></table></td></tr>'."\n";
 6172:         $itemcount ++;
 6173:         my $onclick = "toggleDisplay(this.form,'credits');";
 6174:         my $display = 'none';
 6175:         if ($currusecredits) {
 6176:             $display = 'block';
 6177:         }
 6178:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 6179:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 6180:         foreach my $type (@types) {
 6181:             next if ($type eq 'community');
 6182:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 6183:                            '<input type="text" name="'.$type.'_credits"'.
 6184:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 6185:         }
 6186:         $additional .= '</tr></table></div>'."\n";
 6187:         %defaultchecked = ('coursecredits' => 'off');
 6188:         @toggles = ('coursecredits');
 6189:         my $current = {
 6190:                         'coursecredits' => $currusecredits,
 6191:                       };
 6192:         (my $table,$itemcount) =
 6193:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 6194:                                \%choices,$itemcount,$onclick,$additional,'left');
 6195:         $datatable .= $table;
 6196:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 6197:         my $display = 'none';
 6198:         if ($postsubmitclient) {
 6199:             $display = 'block';
 6200:         }
 6201:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 6202:                       &mt('Number of seconds submit is disabled').'<br />'.
 6203:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 6204:                       '<table><tr>';
 6205:         foreach my $type (@types) {
 6206:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 6207:                            '<input type="text" name="'.$type.'_timeout" value="'.
 6208:                            $deftimeout{$type}.'" size="5" /></td>';
 6209:         }
 6210:         $additional .= '</tr></table></div>'."\n";
 6211:         %defaultchecked = ('postsubmit' => 'on');
 6212:         @toggles = ('postsubmit');
 6213:         $current = {
 6214:                        'postsubmit' => $postsubmitclient,
 6215:                    };
 6216:         ($table,$itemcount) =
 6217:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 6218:                                \%choices,$itemcount,$onclick,$additional,'left');
 6219:         $datatable .= $table;
 6220:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6221:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6222:                       $choices{'mysqltables'}.
 6223:                       '</span></td>'.
 6224:                       '<td align="right" class="LC_right_item">'.
 6225:                       '<table><tr>';
 6226:         foreach my $type (@types) {
 6227:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 6228:                            '<input type="text" name="mysqltables_'.$type.'"'.
 6229:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 6230:         }
 6231:         $datatable .= '</tr></table></td></tr>'."\n";
 6232:         $itemcount ++;
 6233:         %defaultchecked = ('ltiauth' => 'off');
 6234:         @toggles = ('ltiauth');
 6235:         $current = {
 6236:                        'ltiauth' => $ltiauth,
 6237:                    };
 6238:         ($table,$itemcount) =
 6239:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 6240:                                \%choices,$itemcount,undef,undef,'left');
 6241:         $datatable .= $table;
 6242:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6243:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6244:                       $choices{'domexttool'}.
 6245:                       '</span></td>'.
 6246:                       '<td style="text-align: right" class="LC_right_item">'.
 6247:                       '<table><tr>';
 6248:         foreach my $type (@types) {
 6249:             $datatable .= '<td style="text-align: left">'.
 6250:                           '<span class="LC_nobreak">'.
 6251:                           '<input type="checkbox" name="domexttool"'.
 6252:                           ' value="'.$type.'"'.$domexttool{$type}.' />'.
 6253:                           &mt($type).'</span></td>'."\n";
 6254:         }
 6255:         $datatable .= '</tr></table></td></tr>'."\n";
 6256:         $itemcount ++;
 6257:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6258:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6259:                       $choices{'exttool'}.
 6260:                       '</span></td>'.
 6261:                       '<td style="text-align: right" class="LC_right_item">'.
 6262:                       '<table><tr>';
 6263:         foreach my $type (@types) {
 6264:             $datatable .= '<td style="text-align: left">'.
 6265:                           '<span class="LC_nobreak">'.
 6266:                           '<input type="checkbox" name="exttool"'.
 6267:                           ' value="'.$type.'"'.$exttool{$type}.' />'.
 6268:                           &mt($type).'</span></td>'."\n";
 6269:         }
 6270:         $datatable .= '</tr></table></td></tr>'."\n";
 6271:     }
 6272:     $$rowtotal += $itemcount;
 6273:     return $datatable;
 6274: }
 6275: 
 6276: sub print_selfenrollment {
 6277:     my ($position,$dom,$settings,$rowtotal) = @_;
 6278:     my ($css_class,$datatable);
 6279:     my $itemcount = 1;
 6280:     my @types = ('official','unofficial','community','textbook');
 6281:     if (($position eq 'top') || ($position eq 'middle')) {
 6282:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 6283:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 6284:         my @rows;
 6285:         my $key;
 6286:         if ($position eq 'top') {
 6287:             $key = 'admin'; 
 6288:             if (ref($rowsref) eq 'ARRAY') {
 6289:                 @rows = @{$rowsref};
 6290:             }
 6291:         } elsif ($position eq 'middle') {
 6292:             $key = 'default';
 6293:             @rows = ('types','registered','approval','limit');
 6294:         }
 6295:         foreach my $row (@rows) {
 6296:             if (defined($titlesref->{$row})) {
 6297:                 $itemcount ++;
 6298:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6299:                 $datatable .= '<tr'.$css_class.'>'.
 6300:                               '<td>'.$titlesref->{$row}.'</td>'.
 6301:                               '<td class="LC_left_item">'.
 6302:                               '<table><tr>';
 6303:                 my (%current,%currentcap);
 6304:                 if (ref($settings) eq 'HASH') {
 6305:                     if (ref($settings->{$key}) eq 'HASH') {
 6306:                         foreach my $type (@types) {
 6307:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 6308:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 6309:                             }
 6310:                             if (($row eq 'limit') && ($key eq 'default')) {
 6311:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 6312:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 6313:                                 }
 6314:                             }
 6315:                         }
 6316:                     }
 6317:                 }
 6318:                 my %roles = (
 6319:                              '0' => &Apache::lonnet::plaintext('dc'),
 6320:                             ); 
 6321:             
 6322:                 foreach my $type (@types) {
 6323:                     unless (($row eq 'registered') && ($key eq 'default')) {
 6324:                         $datatable .= '<th>'.&mt($type).'</th>';
 6325:                     }
 6326:                 }
 6327:                 unless (($row eq 'registered') && ($key eq 'default')) {
 6328:                     $datatable .= '</tr><tr>';
 6329:                 }
 6330:                 foreach my $type (@types) {
 6331:                     if ($type eq 'community') {
 6332:                         $roles{'1'} = &mt('Community personnel');
 6333:                     } else {
 6334:                         $roles{'1'} = &mt('Course personnel');
 6335:                     }
 6336:                     $datatable .= '<td style="vertical-align: top">';
 6337:                     if ($position eq 'top') {
 6338:                         my %checked;
 6339:                         if ($current{$type} eq '0') {
 6340:                             $checked{'0'} = ' checked="checked"';
 6341:                         } else {
 6342:                             $checked{'1'} = ' checked="checked"';
 6343:                         }
 6344:                         foreach my $role ('1','0') {
 6345:                             $datatable .= '<span class="LC_nobreak"><label>'.
 6346:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 6347:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 6348:                                           $roles{$role}.'</label></span> ';
 6349:                         }
 6350:                     } else {
 6351:                         if ($row eq 'types') {
 6352:                             my %checked;
 6353:                             if ($current{$type} =~ /^(all|dom)$/) {
 6354:                                 $checked{$1} = ' checked="checked"';
 6355:                             } else {
 6356:                                 $checked{''} = ' checked="checked"';
 6357:                             }
 6358:                             foreach my $val ('','dom','all') {
 6359:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6360:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6361:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6362:                             }
 6363:                         } elsif ($row eq 'registered') {
 6364:                             my %checked;
 6365:                             if ($current{$type} eq '1') {
 6366:                                 $checked{'1'} = ' checked="checked"';
 6367:                             } else {
 6368:                                 $checked{'0'} = ' checked="checked"';
 6369:                             }
 6370:                             foreach my $val ('0','1') {
 6371:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6372:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6373:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6374:                             }
 6375:                         } elsif ($row eq 'approval') {
 6376:                             my %checked;
 6377:                             if ($current{$type} =~ /^([12])$/) {
 6378:                                 $checked{$1} = ' checked="checked"';
 6379:                             } else {
 6380:                                 $checked{'0'} = ' checked="checked"';
 6381:                             }
 6382:                             for my $val (0..2) {
 6383:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6384:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6385:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6386:                             }
 6387:                         } elsif ($row eq 'limit') {
 6388:                             my %checked;
 6389:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 6390:                                 $checked{$1} = ' checked="checked"';
 6391:                             } else {
 6392:                                 $checked{'none'} = ' checked="checked"';
 6393:                             }
 6394:                             my $cap;
 6395:                             if ($currentcap{$type} =~ /^\d+$/) {
 6396:                                 $cap = $currentcap{$type};
 6397:                             }
 6398:                             foreach my $val ('none','allstudents','selfenrolled') {
 6399:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6400:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6401:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6402:                             }
 6403:                             $datatable .= '<br />'.
 6404:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 6405:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 6406:                                           '</span>'; 
 6407:                         }
 6408:                     }
 6409:                     $datatable .= '</td>';
 6410:                 }
 6411:                 $datatable .= '</tr>';
 6412:             }
 6413:             $datatable .= '</table></td></tr>';
 6414:         }
 6415:     } elsif ($position eq 'bottom') {
 6416:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 6417:     }
 6418:     $$rowtotal += $itemcount;
 6419:     return $datatable;
 6420: }
 6421: 
 6422: sub print_validation_rows {
 6423:     my ($caller,$dom,$settings,$rowtotal) = @_;
 6424:     my ($itemsref,$namesref,$fieldsref);
 6425:     if ($caller eq 'selfenroll') { 
 6426:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 6427:     } elsif ($caller eq 'requestcourses') {
 6428:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 6429:     }
 6430:     my %currvalidation;
 6431:     if (ref($settings) eq 'HASH') {
 6432:         if (ref($settings->{'validation'}) eq 'HASH') {
 6433:             %currvalidation = %{$settings->{'validation'}};
 6434:         }
 6435:     }
 6436:     my $datatable;
 6437:     my $itemcount = 0;
 6438:     foreach my $item (@{$itemsref}) {
 6439:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6440:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6441:                       $namesref->{$item}.
 6442:                       '</span></td>'.
 6443:                       '<td class="LC_left_item">';
 6444:         if (($item eq 'url') || ($item eq 'button')) {
 6445:             $datatable .= '<span class="LC_nobreak">'.
 6446:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 6447:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 6448:         } elsif ($item eq 'fields') {
 6449:             my @currfields;
 6450:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 6451:                 @currfields = @{$currvalidation{$item}};
 6452:             }
 6453:             foreach my $field (@{$fieldsref}) {
 6454:                 my $check = '';
 6455:                 if (grep(/^\Q$field\E$/,@currfields)) {
 6456:                     $check = ' checked="checked"';
 6457:                 }
 6458:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6459:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 6460:                               ' value="'.$field.'"'.$check.' />'.$field.
 6461:                               '</label></span> ';
 6462:             }
 6463:         } elsif ($item eq 'markup') {
 6464:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 6465:                            $currvalidation{$item}.
 6466:                               '</textarea>';
 6467:         }
 6468:         $datatable .= '</td></tr>'."\n";
 6469:         if (ref($rowtotal)) {
 6470:             $itemcount ++;
 6471:         }
 6472:     }
 6473:     if ($caller eq 'requestcourses') {
 6474:         my %currhash;
 6475:         if (ref($settings) eq 'HASH') {
 6476:             if (ref($settings->{'validation'}) eq 'HASH') {
 6477:                 if ($settings->{'validation'}{'dc'} ne '') {
 6478:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 6479:                 }
 6480:             }
 6481:         }
 6482:         my $numinrow = 2;
 6483:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 6484:                                                        'validationdc',%currhash);
 6485:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6486:         $datatable .= '<tr'.$css_class.'><td>';
 6487:         if ($numdc > 1) {
 6488:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 6489:         } else {
 6490:             $datatable .=  &mt('Course creation processed as: ');
 6491:         }
 6492:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 6493:         $itemcount ++;
 6494:     }
 6495:     if (ref($rowtotal)) {
 6496:         $$rowtotal += $itemcount;
 6497:     }
 6498:     return $datatable;
 6499: }
 6500: 
 6501: sub print_passwords {
 6502:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 6503:     my ($datatable,$css_class);
 6504:     my $itemcount = 0;
 6505:     my %titles = &Apache::lonlocal::texthash (
 6506:         captcha        => '"Forgot Password" CAPTCHA validation',
 6507:         link           => 'Reset link expiration (hours)',
 6508:         case           => 'Case-sensitive usernames/e-mail',
 6509:         prelink        => 'Information required (form 1)',
 6510:         postlink       => 'Information required (form 2)',
 6511:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 6512:         customtext     => 'Domain specific text (HTML)',
 6513:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 6514:         intauth_check  => 'Check bcrypt cost if authenticated',
 6515:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 6516:         permanent      => 'Permanent e-mail address',
 6517:         critical       => 'Critical notification address',
 6518:         notify         => 'Notification address',
 6519:         min            => 'Minimum password length',
 6520:         max            => 'Maximum password length',
 6521:         chars          => 'Required characters',
 6522:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 6523:     );
 6524:     if ($position eq 'top') {
 6525:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6526:         my $shownlinklife = 2;
 6527:         my $prelink = 'both';
 6528:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 6529:         if (ref($settings) eq 'HASH') {
 6530:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 6531:                 $shownlinklife = $settings->{resetlink};
 6532:             }
 6533:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 6534:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 6535:             }
 6536:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 6537:                 $prelink = $settings->{resetprelink};
 6538:             }
 6539:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 6540:                 %postlink = %{$settings->{resetpostlink}};
 6541:             }
 6542:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 6543:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 6544:             }
 6545:             if ($settings->{resetremove}) {
 6546:                 $nostdtext = 1;
 6547:             }
 6548:             if ($settings->{resetcustom}) {
 6549:                 $customurl = $settings->{resetcustom};
 6550:             }
 6551:         } else {
 6552:             if (ref($types) eq 'ARRAY') {
 6553:                 foreach my $item (@{$types}) {
 6554:                     $casesens{$item} = 1;
 6555:                     $postlink{$item} = ['username','email'];
 6556:                 }
 6557:             }
 6558:             $casesens{'default'} = 1;
 6559:             $postlink{'default'} = ['username','email'];
 6560:             $prelink = 'both';
 6561:             %emailsrc = (
 6562:                           permanent => 1,
 6563:                           critical  => 1,
 6564:                           notify    => 1,
 6565:             );
 6566:         }
 6567:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 6568:         $itemcount ++;
 6569:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6570:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 6571:                       '<td class="LC_left_item">'.
 6572:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 6573:                       'name="passwords_link" size="3" /></td></tr>';
 6574:         $itemcount ++;
 6575:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6576:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 6577:                       '<td class="LC_left_item">';
 6578:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6579:             foreach my $item (@{$types}) {
 6580:                 my $checkedcase;
 6581:                 if ($casesens{$item}) {
 6582:                     $checkedcase = ' checked="checked"';
 6583:                 }
 6584:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6585:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 6586:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 6587:                               '</span>&nbsp;&nbsp; ';
 6588:             }
 6589:         }
 6590:         my $checkedcase;
 6591:         if ($casesens{'default'}) {
 6592:             $checkedcase = ' checked="checked"';
 6593:         }
 6594:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 6595:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 6596:                       $othertitle.'</label></span></td>';
 6597:         $itemcount ++;
 6598:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6599:         my %checkedpre = (
 6600:                              both => ' checked="checked"',
 6601:                              either => '',
 6602:                          );
 6603:         if ($prelink eq 'either') {
 6604:             $checkedpre{either} = ' checked="checked"';
 6605:             $checkedpre{both} = '';
 6606:         }
 6607:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 6608:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6609:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 6610:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 6611:                       '<span class="LC_nobreak"><label>'.
 6612:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 6613:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 6614:         $itemcount ++;
 6615:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6616:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 6617:                       '<td class="LC_left_item">';
 6618:         my %postlinked;
 6619:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6620:             foreach my $item (@{$types}) {
 6621:                 undef(%postlinked);
 6622:                 $datatable .= '<fieldset style="display: inline-block;">'.
 6623:                               '<legend>'.$usertypes->{$item}.'</legend>';
 6624:                 if (ref($postlink{$item}) eq 'ARRAY') {
 6625:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 6626:                 }
 6627:                 foreach my $field ('email','username') {
 6628:                     my $checked;
 6629:                     if ($postlinked{$field}) {
 6630:                         $checked = ' checked="checked"';
 6631:                     }
 6632:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6633:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 6634:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 6635:                                   '<span>&nbsp;&nbsp; ';
 6636:                 }
 6637:                 $datatable .= '</fieldset>';
 6638:             }
 6639:         }
 6640:         if (ref($postlink{'default'}) eq 'ARRAY') {
 6641:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 6642:         }
 6643:         $datatable .= '<fieldset style="display: inline-block;">'.
 6644:                       '<legend>'.$othertitle.'</legend>';
 6645:         foreach my $field ('email','username') {
 6646:             my $checked;
 6647:             if ($postlinked{$field}) {
 6648:                 $checked = ' checked="checked"';
 6649:             }
 6650:             $datatable .= '<span class="LC_nobreak"><label>'.
 6651:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 6652:                           $field.'"'.$checked.' />'.$field.'</label>'.
 6653:                           '<span>&nbsp;&nbsp; ';
 6654:         }
 6655:         $datatable .= '</fieldset></td></tr>';
 6656:         $itemcount ++;
 6657:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6658:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 6659:                       '<td class="LC_left_item">';
 6660:         foreach my $type ('permanent','critical','notify') {
 6661:             my $checkedemail;
 6662:             if ($emailsrc{$type}) {
 6663:                 $checkedemail = ' checked="checked"';
 6664:             }
 6665:             $datatable .= '<span class="LC_nobreak"><label>'.
 6666:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 6667:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 6668:                           '<span>&nbsp;&nbsp; ';
 6669:         }
 6670:         $datatable .= '</td></tr>';
 6671:         $itemcount ++;
 6672:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6673:         my $switchserver = &check_switchserver($dom,$confname);
 6674:         my ($showstd,$noshowstd);
 6675:         if ($nostdtext) {
 6676:             $noshowstd = ' checked="checked"';
 6677:         } else {
 6678:             $showstd = ' checked="checked"';
 6679:         }
 6680:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 6681:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6682:                       &mt('Retain standard text:').
 6683:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 6684:                       &mt('Yes').'</label>'.'&nbsp;'.
 6685:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 6686:                       &mt('No').'</label></span><br />'.
 6687:                       '<span class="LC_fontsize_small">'.
 6688:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 6689:                       &mt('Include custom text:');
 6690:         if ($customurl) {
 6691:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 6692:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 6693:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 6694:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 6695:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 6696:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 6697:         }
 6698:         if ($switchserver) {
 6699:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 6700:         } else {
 6701:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 6702:                          '<input type="file" name="passwords_customfile" /></span>';
 6703:         }
 6704:         $datatable .= '</td></tr>';
 6705:     } elsif ($position eq 'middle') {
 6706:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 6707:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 6708:         my %defaults;
 6709:         if (ref($domconf{'defaults'}) eq 'HASH') {
 6710:             %defaults = %{$domconf{'defaults'}};
 6711:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 6712:                 $defaults{'intauth_cost'} = 10;
 6713:             }
 6714:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 6715:                 $defaults{'intauth_check'} = 0;
 6716:             }
 6717:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 6718:                 $defaults{'intauth_switch'} = 0;
 6719:             }
 6720:         } else {
 6721:             %defaults = (
 6722:                           'intauth_cost'   => 10,
 6723:                           'intauth_check'  => 0,
 6724:                           'intauth_switch' => 0,
 6725:                         );
 6726:         }
 6727:         foreach my $item (@items) {
 6728:             if ($itemcount%2) {
 6729:                 $css_class = '';
 6730:             } else {
 6731:                 $css_class = ' class="LC_odd_row" ';
 6732:             }
 6733:             $datatable .= '<tr'.$css_class.'>'.
 6734:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 6735:                           '</span></td><td class="LC_left_item" colspan="3">';
 6736:             if ($item eq 'intauth_switch') {
 6737:                 my @options = (0,1,2);
 6738:                 my %optiondesc = &Apache::lonlocal::texthash (
 6739:                                    0 => 'No',
 6740:                                    1 => 'Yes',
 6741:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 6742:                                  );
 6743:                 $datatable .= '<table width="100%">';
 6744:                 foreach my $option (@options) {
 6745:                     my $checked = ' ';
 6746:                     if ($defaults{$item} eq $option) {
 6747:                         $checked = ' checked="checked"';
 6748:                     }
 6749:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 6750:                                   '<label><input type="radio" name="'.$item.
 6751:                                   '" value="'.$option.'"'.$checked.' />'.
 6752:                                   $optiondesc{$option}.'</label></span></td></tr>';
 6753:                 }
 6754:                 $datatable .= '</table>';
 6755:             } elsif ($item eq 'intauth_check') {
 6756:                 my @options = (0,1,2);
 6757:                 my %optiondesc = &Apache::lonlocal::texthash (
 6758:                                    0 => 'No',
 6759:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 6760:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 6761:                                  );
 6762:                 $datatable .= '<table width="100%">';
 6763:                 foreach my $option (@options) {
 6764:                     my $checked = ' ';
 6765:                     my $onclick;
 6766:                     if ($defaults{$item} eq $option) {
 6767:                         $checked = ' checked="checked"';
 6768:                     }
 6769:                     if ($option == 2) {
 6770:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 6771:                     }
 6772:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 6773:                                   '<label><input type="radio" name="'.$item.
 6774:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 6775:                                   $optiondesc{$option}.'</label></span></td></tr>';
 6776:                 }
 6777:                 $datatable .= '</table>';
 6778:             } else {
 6779:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 6780:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 6781:             }
 6782:             $datatable .= '</td></tr>';
 6783:             $itemcount ++;
 6784:         }
 6785:     } elsif ($position eq 'lower') {
 6786:         $datatable .= &password_rules('passwords',\$itemcount,$settings);
 6787:     } else {
 6788:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6789:         my %ownerchg = (
 6790:                           by  => {},
 6791:                           for => {},
 6792:                        );
 6793:         my %ownertitles = &Apache::lonlocal::texthash (
 6794:                             by  => 'Course owner status(es) allowed',
 6795:                             for => 'Student status(es) allowed',
 6796:                           );
 6797:         if (ref($settings) eq 'HASH') {
 6798:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 6799:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 6800:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 6801:                 }
 6802:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 6803:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 6804:                 }
 6805:             }
 6806:         }
 6807:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6808:         $datatable .= '<tr '.$css_class.'>'.
 6809:                       '<td>'.
 6810:                       &mt('Requirements').'<ul>'.
 6811:                       '<li>'.&mt("Course 'type' is not a Community").'</li>'.
 6812:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 6813:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 6814:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 6815:                       '</ul>'.
 6816:                       '</td>'.
 6817:                       '<td class="LC_left_item">';
 6818:         foreach my $item ('by','for') {
 6819:             $datatable .= '<fieldset style="display: inline-block;">'.
 6820:                           '<legend>'.$ownertitles{$item}.'</legend>';
 6821:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6822:                 foreach my $type (@{$types}) {
 6823:                     my $checked;
 6824:                     if ($ownerchg{$item}{$type}) {
 6825:                         $checked = ' checked="checked"';
 6826:                     }
 6827:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6828:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 6829:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 6830:                                   '</span>&nbsp;&nbsp; ';
 6831:                 }
 6832:             }
 6833:             my $checked;
 6834:             if ($ownerchg{$item}{'default'}) {
 6835:                 $checked = ' checked="checked"';
 6836:             }
 6837:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 6838:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 6839:                           $othertitle.'</label></span></fieldset>';
 6840:         }
 6841:         $datatable .= '</td></tr>';
 6842:     }
 6843:     return $datatable;
 6844: }
 6845: 
 6846: sub password_rules {
 6847:     my ($prefix,$itemcountref,$settings) = @_;
 6848:     my ($min,$max,%chars,$numsaved,$numinrow);
 6849:     my %titles;
 6850:     if ($prefix eq 'passwords') {
 6851:         %titles = &Apache::lonlocal::texthash (
 6852:             min            => 'Minimum password length',
 6853:             max            => 'Maximum password length',
 6854:             chars          => 'Required characters',
 6855:         );
 6856:     } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
 6857:         %titles = &Apache::lonlocal::texthash (
 6858:             min            => 'Minimum secret length',
 6859:             max            => 'Maximum secret length',
 6860:             chars          => 'Required characters',
 6861:         );
 6862:     }
 6863:     $min = $Apache::lonnet::passwdmin;
 6864:     my $datatable;
 6865:     my $itemcount;
 6866:     if (ref($itemcountref)) {
 6867:         $itemcount = $$itemcountref;
 6868:     }
 6869:     if (ref($settings) eq 'HASH') {
 6870:         if ($settings->{min}) {
 6871:             $min = $settings->{min};
 6872:         }
 6873:         if ($settings->{max}) {
 6874:             $max = $settings->{max};
 6875:         }
 6876:         if (ref($settings->{chars}) eq 'ARRAY') {
 6877:             map { $chars{$_} = 1; } (@{$settings->{chars}});
 6878:         }
 6879:         if ($prefix eq 'passwords') {
 6880:             if ($settings->{numsaved}) {
 6881:                 $numsaved = $settings->{numsaved};
 6882:             }
 6883:         }
 6884:     }
 6885:     my %rulenames = &Apache::lonlocal::texthash(
 6886:                                                  uc => 'At least one upper case letter',
 6887:                                                  lc => 'At least one lower case letter',
 6888:                                                  num => 'At least one number',
 6889:                                                  spec => 'At least one non-alphanumeric',
 6890:                                                );
 6891:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6892:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 6893:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 6894:                   '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
 6895:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 6896:                   '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 6897:                   '</span></td></tr>';
 6898:     $itemcount ++;
 6899:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6900:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 6901:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 6902:                   '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
 6903:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 6904:                   '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 6905:                   '</span></td></tr>';
 6906:     $itemcount ++;
 6907:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6908:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 6909:                   '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 6910:                   '</span></td>';
 6911:     my $numinrow = 2;
 6912:     my @possrules = ('uc','lc','num','spec');
 6913:     $datatable .= '<td class="LC_left_item"><table>';
 6914:     for (my $i=0; $i<@possrules; $i++) {
 6915:         my ($rem,$checked);
 6916:         if ($chars{$possrules[$i]}) {
 6917:             $checked = ' checked="checked"';
 6918:         }
 6919:         $rem = $i%($numinrow);
 6920:         if ($rem == 0) {
 6921:             if ($i > 0) {
 6922:                 $datatable .= '</tr>';
 6923:             }
 6924:             $datatable .= '<tr>';
 6925:         }
 6926:         $datatable .= '<td><span class="LC_nobreak"><label>'.
 6927:                       '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 6928:                       $rulenames{$possrules[$i]}.'</label></span></td>';
 6929:     }
 6930:     my $rem = @possrules%($numinrow);
 6931:     my $colsleft = $numinrow - $rem;
 6932:     if ($colsleft > 1 ) {
 6933:         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6934:                       '&nbsp;</td>';
 6935:     } elsif ($colsleft == 1) {
 6936:         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6937:     }
 6938:     $datatable .='</table></td></tr>';
 6939:     $itemcount ++;
 6940:     if ($prefix eq 'passwords') {
 6941:         $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
 6942:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6943:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 6944:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6945:                       '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
 6946:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 6947:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 6948:                       '</span></td></tr>';
 6949:         $itemcount ++;
 6950:     }
 6951:     if (ref($itemcountref)) {
 6952:         $$itemcountref += $itemcount;
 6953:     }
 6954:     return $datatable;
 6955: }
 6956: 
 6957: sub print_wafproxy {
 6958:     my ($position,$dom,$settings,$rowtotal) = @_;
 6959:     my $css_class;
 6960:     my $itemcount = 0;
 6961:     my $datatable;
 6962:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6963:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 6964:     my %lt = &wafproxy_titles();
 6965:     foreach my $server (sort(keys(%servers))) {
 6966:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 6967:         next if ($serverhome eq '');
 6968:         my $serverdom;
 6969:         if ($serverhome ne $server) {
 6970:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 6971:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 6972:                 $othercontrol{$server} = $serverdom;
 6973:             }
 6974:         } else {
 6975:             $serverdom = &Apache::lonnet::host_domain($server);
 6976:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 6977:             if ($serverdom ne $dom) {
 6978:                 $othercontrol{$server} = $serverdom;
 6979:             } else {
 6980:                 $setdom = 1;
 6981:                 if (ref($settings) eq 'HASH') {
 6982:                     if (ref($settings->{'alias'}) eq 'HASH') {
 6983:                         $aliases{$dom} = $settings->{'alias'};
 6984:                         if ($aliases{$dom} ne '') {
 6985:                             $showdom = 1;
 6986:                         }
 6987:                     }
 6988:                     if (ref($settings->{'saml'}) eq 'HASH') {
 6989:                         $saml{$dom} = $settings->{'saml'};
 6990:                     }
 6991:                 }
 6992:             }
 6993:         }
 6994:     }
 6995:     if ($setdom) {
 6996:         %{$values{$dom}} = ();
 6997:         if (ref($settings) eq 'HASH') {
 6998:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 6999:                 $values{$dom}{$item} = $settings->{$item};
 7000:             }
 7001:         }
 7002:     }
 7003:     if (keys(%othercontrol)) {
 7004:         %otherdoms = reverse(%othercontrol);
 7005:         foreach my $domain (keys(%otherdoms)) {
 7006:             %{$values{$domain}} = ();
 7007:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 7008:             if (ref($config{'wafproxy'}) eq 'HASH') {
 7009:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 7010:                 if (exists($config{'wafproxy'}{'saml'})) {
 7011:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 7012:                 }
 7013:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7014:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 7015:                 }
 7016:             }
 7017:         }
 7018:     }
 7019:     if ($position eq 'top') {
 7020:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7021:         my %aliasinfo;
 7022:         foreach my $server (sort(keys(%servers))) {
 7023:             $itemcount ++;
 7024:             my $dom_in_effect;
 7025:             my $aliasrows = '<tr>'.
 7026:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7027:                             &mt('Hostname').':&nbsp;'.
 7028:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 7029:             if ($othercontrol{$server}) {
 7030:                 $dom_in_effect = $othercontrol{$server};
 7031:                 my ($current,$forsaml);
 7032:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 7033:                     $current = $aliases{$dom_in_effect}{$server};
 7034:                 }
 7035:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 7036:                     if ($saml{$dom_in_effect}{$server}) {
 7037:                         $forsaml = 1;
 7038:                     }
 7039:                 }
 7040:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7041:                               &mt('Alias').':&nbsp';
 7042:                 if ($current) {
 7043:                     $aliasrows .= $current;
 7044:                     if ($forsaml) {
 7045:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 7046:                     }
 7047:                 } else {
 7048:                     $aliasrows .= &mt('None');
 7049:                 }
 7050:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 7051:                               &mt('controlled by domain: [_1]',
 7052:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 7053:             } else {
 7054:                 $dom_in_effect = $dom;
 7055:                 my ($current,$samlon,$samloff);
 7056:                 $samloff = ' checked="checked"';
 7057:                 if (ref($aliases{$dom}) eq 'HASH') {
 7058:                     if ($aliases{$dom}{$server}) {
 7059:                         $current = $aliases{$dom}{$server};
 7060:                     }
 7061:                 }
 7062:                 if (ref($saml{$dom}) eq 'HASH') {
 7063:                     if ($saml{$dom}{$server}) {
 7064:                         $samlon = $samloff;
 7065:                         undef($samloff);
 7066:                     }
 7067:                 }
 7068:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7069:                               &mt('Alias').':&nbsp;'.
 7070:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 7071:                               'value="'.$current.'" size="30" />'.
 7072:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 7073:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 7074:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 7075:                               &mt('No').'</label>&nbsp;<label>'.
 7076:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 7077:                               &mt('Yes').'</label></span>'.
 7078:                               '</td>';
 7079:             }
 7080:             $aliasrows .= '</tr>';
 7081:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 7082:         }
 7083:         if ($aliasinfo{$dom}) {
 7084:             my ($onclick,$wafon,$wafoff,$showtable);
 7085:             $onclick = ' onclick="javascript:toggleWAF();"';
 7086:             $wafoff = ' checked="checked"';
 7087:             $showtable = ' style="display:none";';
 7088:             if ($showdom) {
 7089:                 $wafon = $wafoff;
 7090:                 $wafoff = '';
 7091:                 $showtable = ' style="display:inline;"';
 7092:             }
 7093:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7094:             $datatable = '<tr'.$css_class.'>'.
 7095:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 7096:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 7097:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 7098:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 7099:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 7100:                          &mt('No').'</label></span></td>'.
 7101:                          '<td class="LC_left_item">'.
 7102:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 7103:                          '</table></td></tr>';
 7104:             $itemcount++;
 7105:         }
 7106:         if (keys(%otherdoms)) {
 7107:             foreach my $key (sort(keys(%otherdoms))) {
 7108:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7109:                 $datatable .= '<tr'.$css_class.'>'.
 7110:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 7111:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 7112:                               '</table></td></tr>';
 7113:                 $itemcount++;
 7114:             }
 7115:         }
 7116:     } else {
 7117:         my %ip_methods = &remoteip_methods();
 7118:         if ($setdom) {
 7119:             $itemcount ++;
 7120:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7121:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 7122:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 7123:             $wafstyle = ' style="display:none;"';
 7124:             $nowafstyle = ' style="display:table-row;"';
 7125:             $currwafdisplay = ' style="display: none"';
 7126:             $wafrangestyle = ' style="display: none"';
 7127:             $curr_remotip = 'n';
 7128:             $ssltossl = ' checked="checked"';
 7129:             if ($showdom) {
 7130:                 $wafstyle = ' style="display:table-row;"';
 7131:                 $nowafstyle =  ' style="display:none;"';
 7132:                 if (keys(%{$values{$dom}})) {
 7133:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 7134:                         $curr_remotip = $values{$dom}{remoteip};
 7135:                     }
 7136:                     if ($curr_remotip eq 'h') {
 7137:                         $currwafdisplay = ' style="display:table-row"';
 7138:                         $wafrangestyle = ' style="display:inline-block;"';
 7139:                     }
 7140:                     if ($values{$dom}{'sslopt'}) {
 7141:                         $alltossl = ' checked="checked"';
 7142:                         $ssltossl = '';
 7143:                     }
 7144:                 }
 7145:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 7146:                     $vpndircheck = ' checked="checked"';
 7147:                     $currwafvpn = ' style="display:table-row;"';
 7148:                     $wafrangestyle = ' style="display:inline-block;"';
 7149:                 } else {
 7150:                     $vpnaliascheck = ' checked="checked"';
 7151:                     $currwafvpn = ' style="display:none;"';
 7152:                 }
 7153:             }
 7154:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7155:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 7156:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 7157:                           '</tr>'.
 7158:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7159:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 7160:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 7161:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 7162:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 7163:                           '<td class="LC_left_item"><table>'.
 7164:                           '<tr>'.
 7165:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 7166:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 7167:             foreach my $option ('m','h','n') {
 7168:                 my $sel;
 7169:                 if ($option eq $curr_remotip) {
 7170:                    $sel = ' selected="selected"';
 7171:                 }
 7172:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 7173:                               $ip_methods{$option}.'</option>';
 7174:             }
 7175:             $datatable .= '</select></td></tr>'."\n".
 7176:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 7177:                           $lt{'ipheader'}.':&nbsp;'.
 7178:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 7179:                           'name="wafproxy_ipheader" />'.
 7180:                           '</td></tr>'."\n".
 7181:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 7182:                           $lt{'trusted'}.':<br />'.
 7183:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 7184:                           $values{$dom}{'trusted'}.'</textarea>'.
 7185:                           '</td></tr>'."\n".
 7186:                           '<tr><td><hr /></td></tr>'."\n".
 7187:                           '<tr>'.
 7188:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 7189:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 7190:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 7191:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 7192:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 7193:             foreach my $item ('vpnint','vpnext') {
 7194:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 7195:                               '<td valign="top">'.$lt{$item}.':<br />'.
 7196:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 7197:                               $values{$dom}{$item}.'</textarea>'.
 7198:                               '</td></tr>'."\n";
 7199:             }
 7200:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 7201:                           '<tr>'.
 7202:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 7203:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 7204:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 7205:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 7206:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 7207:                           '</table></td></tr>';
 7208:         }
 7209:         if (keys(%otherdoms)) {
 7210:             foreach my $domain (sort(keys(%otherdoms))) {
 7211:                 $itemcount ++;
 7212:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7213:                 $datatable .= '<tr'.$css_class.'>'.
 7214:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 7215:                               '<td class="LC_left_item"><table>';
 7216:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 7217:                     my $showval = &mt('None');
 7218:                     if ($item eq 'ssl') {
 7219:                         $showval = $lt{'ssltossl'};
 7220:                     }
 7221:                     if ($values{$domain}{$item}) {
 7222:                         $showval = $values{$domain}{$item};
 7223:                         if ($item eq 'ssl') {
 7224:                             $showval = $lt{'alltossl'};
 7225:                         } elsif ($item eq 'remoteip') {
 7226:                             $showval = $ip_methods{$values{$domain}{$item}};
 7227:                         }
 7228:                     }
 7229:                     $datatable .= '<tr>'.
 7230:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 7231:                 }
 7232:                 $datatable .= '</table></td></tr>';
 7233:             }
 7234:         }
 7235:     }
 7236:     $$rowtotal += $itemcount;
 7237:     return $datatable;
 7238: }
 7239: 
 7240: sub wafproxy_titles {
 7241:     return &Apache::lonlocal::texthash(
 7242:                remoteip   => "Method for determining user's IP",
 7243:                ipheader   => 'Request header containing remote IP',
 7244:                trusted    => 'Trusted IP range(s)',
 7245:                vpnaccess  => 'Access from institutional VPN',
 7246:                vpndirect  => 'via regular hostname (no WAF)',
 7247:                vpnaliased => 'via aliased hostname (WAF)',
 7248:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 7249:                vpnext     => 'IP Range(s) for backend WAF connections',
 7250:                sslopt     => 'Forwarding http/https',
 7251:                alltossl   => 'WAF forwards both http and https requests to https',
 7252:                ssltossl   => 'WAF forwards http requests to http and https to https',
 7253:            );
 7254: }
 7255: 
 7256: sub remoteip_methods {
 7257:     return &Apache::lonlocal::texthash(
 7258:               m => 'Use Apache mod_remoteip',
 7259:               h => 'Use headers parsed by LON-CAPA',
 7260:               n => 'Not in use',
 7261:            );
 7262: }
 7263: 
 7264: sub print_usersessions {
 7265:     my ($position,$dom,$settings,$rowtotal) = @_;
 7266:     my ($css_class,$datatable,%checked,%choices);
 7267:     my (%by_ip,%by_location,@intdoms);
 7268:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 7269: 
 7270:     my @alldoms = &Apache::lonnet::all_domains();
 7271:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 7272:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7273:     my %altids = &id_for_thisdom(%servers);
 7274:     my $itemcount = 1;
 7275:     if ($position eq 'top') {
 7276:         if (keys(%serverhomes) > 1) {
 7277:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 7278:             my ($curroffloadnow,$curroffloadoth);
 7279:             if (ref($settings) eq 'HASH') {
 7280:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 7281:                     $curroffloadnow = $settings->{'offloadnow'};
 7282:                 }
 7283:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 7284:                     $curroffloadoth = $settings->{'offloadoth'};
 7285:                 }
 7286:             }
 7287:             my $other_insts = scalar(keys(%by_location));
 7288:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 7289:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 7290:         } else {
 7291:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 7292:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 7293:                           '</td></tr>';
 7294:         }
 7295:     } else {
 7296:         if (keys(%by_location) == 0) {
 7297:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 7298:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 7299:                           '</td></tr>';
 7300:         } else {
 7301:             my %lt = &usersession_titles();
 7302:             my $numinrow = 5;
 7303:             my $prefix;
 7304:             my @types;
 7305:             if ($position eq 'bottom') {
 7306:                 $prefix = 'remote';
 7307:                 @types = ('version','excludedomain','includedomain');
 7308:             } else {
 7309:                 $prefix = 'hosted';
 7310:                 @types = ('excludedomain','includedomain');
 7311:             }
 7312:             my (%current,%checkedon,%checkedoff);
 7313:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 7314:             my @locations = sort(keys(%by_location));
 7315:             foreach my $type (@types) {
 7316:                 $checkedon{$type} = '';
 7317:                 $checkedoff{$type} = ' checked="checked"';
 7318:             }
 7319:             if (ref($settings) eq 'HASH') {
 7320:                 if (ref($settings->{$prefix}) eq 'HASH') {
 7321:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 7322:                         $current{$key} = $settings->{$prefix}{$key};
 7323:                         if ($key eq 'version') {
 7324:                             if ($current{$key} ne '') {
 7325:                                 $checkedon{$key} = ' checked="checked"';
 7326:                                 $checkedoff{$key} = '';
 7327:                             }
 7328:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 7329:                             $checkedon{$key} = ' checked="checked"';
 7330:                             $checkedoff{$key} = '';
 7331:                         }
 7332:                     }
 7333:                 }
 7334:             }
 7335:             foreach my $type (@types) {
 7336:                 next if ($type ne 'version' && !@locations);
 7337:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7338:                 $datatable .= '<tr'.$css_class.'>
 7339:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 7340:                                <span class="LC_nobreak">&nbsp;
 7341:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 7342:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 7343:                 if ($type eq 'version') {
 7344:                     my $selector = '<select name="'.$prefix.'_version">';
 7345:                     foreach my $version (@lcversions) {
 7346:                         my $selected = '';
 7347:                         if ($current{'version'} eq $version) {
 7348:                             $selected = ' selected="selected"';
 7349:                         }
 7350:                         $selector .= ' <option value="'.$version.'"'.
 7351:                                      $selected.'>'.$version.'</option>';
 7352:                     }
 7353:                     $selector .= '</select> ';
 7354:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 7355:                 } else {
 7356:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 7357:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 7358:                                  ' />'.('&nbsp;'x2).
 7359:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 7360:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 7361:                                  "\n".
 7362:                                  '</div><div><table>';
 7363:                     my $rem;
 7364:                     for (my $i=0; $i<@locations; $i++) {
 7365:                         my ($showloc,$value,$checkedtype);
 7366:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 7367:                             my $ip = $by_location{$locations[$i]}->[0];
 7368:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 7369:                                  $value = join(':',@{$by_ip{$ip}});
 7370:                                 $showloc = join(', ',@{$by_ip{$ip}});
 7371:                                 if (ref($current{$type}) eq 'ARRAY') {
 7372:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 7373:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 7374:                                             $checkedtype = ' checked="checked"';
 7375:                                             last;
 7376:                                         }
 7377:                                     }
 7378:                                 }
 7379:                             }
 7380:                         }
 7381:                         $rem = $i%($numinrow);
 7382:                         if ($rem == 0) {
 7383:                             if ($i > 0) {
 7384:                                 $datatable .= '</tr>';
 7385:                             }
 7386:                             $datatable .= '<tr>';
 7387:                         }
 7388:                         $datatable .= '<td class="LC_left_item">'.
 7389:                                       '<span class="LC_nobreak"><label>'.
 7390:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 7391:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 7392:                                       '</label></span></td>';
 7393:                     }
 7394:                     $rem = @locations%($numinrow);
 7395:                     my $colsleft = $numinrow - $rem;
 7396:                     if ($colsleft > 1 ) {
 7397:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7398:                                       '&nbsp;</td>';
 7399:                     } elsif ($colsleft == 1) {
 7400:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7401:                     }
 7402:                     $datatable .= '</tr></table>';
 7403:                 }
 7404:                 $datatable .= '</td></tr>';
 7405:                 $itemcount ++;
 7406:             }
 7407:         }
 7408:     }
 7409:     $$rowtotal += $itemcount;
 7410:     return $datatable;
 7411: }
 7412: 
 7413: sub build_location_hashes {
 7414:     my ($intdoms,$by_ip,$by_location) = @_;
 7415:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 7416:                   (ref($by_location) eq 'HASH')); 
 7417:     my %iphost = &Apache::lonnet::get_iphost();
 7418:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 7419:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 7420:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 7421:         foreach my $id (@{$iphost{$primary_ip}}) {
 7422:             my $intdom = &Apache::lonnet::internet_dom($id);
 7423:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 7424:                 push(@{$intdoms},$intdom);
 7425:             }
 7426:         }
 7427:     }
 7428:     foreach my $ip (keys(%iphost)) {
 7429:         if (ref($iphost{$ip}) eq 'ARRAY') {
 7430:             foreach my $id (@{$iphost{$ip}}) {
 7431:                 my $location = &Apache::lonnet::internet_dom($id);
 7432:                 if ($location) {
 7433:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 7434:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7435:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 7436:                             push(@{$by_ip->{$ip}},$location);
 7437:                         }
 7438:                     } else {
 7439:                         $by_ip->{$ip} = [$location];
 7440:                     }
 7441:                 }
 7442:             }
 7443:         }
 7444:     }
 7445:     foreach my $ip (sort(keys(%{$by_ip}))) {
 7446:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7447:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 7448:             my $first = $by_ip->{$ip}->[0];
 7449:             if (ref($by_location->{$first}) eq 'ARRAY') {
 7450:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 7451:                     push(@{$by_location->{$first}},$ip);
 7452:                 }
 7453:             } else {
 7454:                 $by_location->{$first} = [$ip];
 7455:             }
 7456:         }
 7457:     }
 7458:     return;
 7459: }
 7460: 
 7461: sub current_offloads_to {
 7462:     my ($dom,$settings,$servers) = @_;
 7463:     my (%spareid,%otherdomconfigs);
 7464:     if (ref($servers) eq 'HASH') {
 7465:         foreach my $lonhost (sort(keys(%{$servers}))) {
 7466:             my $gotspares;
 7467:             if (ref($settings) eq 'HASH') {
 7468:                 if (ref($settings->{'spares'}) eq 'HASH') {
 7469:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 7470:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 7471:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 7472:                         $gotspares = 1;
 7473:                     }
 7474:                 }
 7475:             }
 7476:             unless ($gotspares) {
 7477:                 my $gotspares;
 7478:                 my $serverhomeID =
 7479:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 7480:                 my $serverhomedom =
 7481:                     &Apache::lonnet::host_domain($serverhomeID);
 7482:                 if ($serverhomedom ne $dom) {
 7483:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 7484:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 7485:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 7486:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 7487:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 7488:                                 $gotspares = 1;
 7489:                             }
 7490:                         }
 7491:                     } else {
 7492:                         $otherdomconfigs{$serverhomedom} =
 7493:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 7494:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 7495:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 7496:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 7497:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 7498:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 7499:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 7500:                                         $gotspares = 1;
 7501:                                     }
 7502:                                 }
 7503:                             }
 7504:                         }
 7505:                     }
 7506:                 }
 7507:             }
 7508:             unless ($gotspares) {
 7509:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 7510:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 7511:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 7512:                } else {
 7513:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 7514:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 7515:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 7516:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 7517:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 7518:                     } else {
 7519:                         my %what = (
 7520:                              spareid => 1,
 7521:                         );
 7522:                         my ($result,$returnhash) = 
 7523:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 7524:                         if ($result eq 'ok') { 
 7525:                             if (ref($returnhash) eq 'HASH') {
 7526:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 7527:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 7528:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 7529:                                 }
 7530:                             }
 7531:                         }
 7532:                     }
 7533:                 }
 7534:             }
 7535:         }
 7536:     }
 7537:     return %spareid;
 7538: }
 7539: 
 7540: sub spares_row {
 7541:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 7542:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 7543:     my $css_class;
 7544:     my $numinrow = 4;
 7545:     my $itemcount = 1;
 7546:     my $datatable;
 7547:     my %typetitles = &sparestype_titles();
 7548:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 7549:         foreach my $server (sort(keys(%{$servers}))) {
 7550:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 7551:             my ($othercontrol,$serverdom);
 7552:             if ($serverhome ne $server) {
 7553:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 7554:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 7555:             } else {
 7556:                 $serverdom = &Apache::lonnet::host_domain($server);
 7557:                 if ($serverdom ne $dom) {
 7558:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 7559:                 }
 7560:             }
 7561:             next unless (ref($spareid->{$server}) eq 'HASH');
 7562:             my ($checkednow,$checkedoth);
 7563:             if (ref($curroffloadnow) eq 'HASH') {
 7564:                 if ($curroffloadnow->{$server}) {
 7565:                     $checkednow = ' checked="checked"';
 7566:                 }
 7567:             }
 7568:             if (ref($curroffloadoth) eq 'HASH') {
 7569:                 if ($curroffloadoth->{$server}) {
 7570:                     $checkedoth = ' checked="checked"';
 7571:                 }
 7572:             }
 7573:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7574:             $datatable .= '<tr'.$css_class.'>
 7575:                            <td rowspan="2">
 7576:                             <span class="LC_nobreak">'.
 7577:                           &mt('[_1] when busy, offloads to:'
 7578:                               ,'<b>'.$server.'</b>').'</span><br />'.
 7579:                           '<span class="LC_nobreak">'."\n".
 7580:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 7581:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 7582:                           "\n";
 7583:             if ($other_insts) {
 7584:                 $datatable .= '<br />'.
 7585:                               '<span class="LC_nobreak">'."\n".
 7586:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 7587:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 7588:                           "\n";
 7589:             }
 7590:             my (%current,%canselect);
 7591:             my @choices = 
 7592:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 7593:             foreach my $type ('primary','default') {
 7594:                 if (ref($spareid->{$server}) eq 'HASH') {
 7595:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 7596:                         my @spares = @{$spareid->{$server}{$type}};
 7597:                         if (@spares > 0) {
 7598:                             if ($othercontrol) {
 7599:                                 $current{$type} = join(', ',@spares);
 7600:                             } else {
 7601:                                 $current{$type} .= '<table>';
 7602:                                 my $numspares = scalar(@spares);
 7603:                                 for (my $i=0;  $i<@spares; $i++) {
 7604:                                     my $rem = $i%($numinrow);
 7605:                                     if ($rem == 0) {
 7606:                                         if ($i > 0) {
 7607:                                             $current{$type} .= '</tr>';
 7608:                                         }
 7609:                                         $current{$type} .= '<tr>';
 7610:                                     }
 7611:                                     $current{$type} .= '<td><label><input type="checkbox" name="spare_'.$type.'_'.$server.'" id="spare_'.$type.'_'.$server.'_'.$i.'" checked="checked" value="'.$spareid->{$server}{$type}[$i].'" onclick="updateNewSpares(this.form,'."'$server'".');" />&nbsp;'.
 7612:                                                        $spareid->{$server}{$type}[$i].
 7613:                                                        '</label></td>'."\n";
 7614:                                 }
 7615:                                 my $rem = @spares%($numinrow);
 7616:                                 my $colsleft = $numinrow - $rem;
 7617:                                 if ($colsleft > 1 ) {
 7618:                                     $current{$type} .= '<td colspan="'.$colsleft.
 7619:                                                        '" class="LC_left_item">'.
 7620:                                                        '&nbsp;</td>';
 7621:                                 } elsif ($colsleft == 1) {
 7622:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 7623:                                 }
 7624:                                 $current{$type} .= '</tr></table>';
 7625:                             }
 7626:                         }
 7627:                     }
 7628:                     if ($current{$type} eq '') {
 7629:                         $current{$type} = &mt('None specified');
 7630:                     }
 7631:                     if ($othercontrol) {
 7632:                         if ($type eq 'primary') {
 7633:                             $canselect{$type} = $othercontrol;
 7634:                         }
 7635:                     } else {
 7636:                         $canselect{$type} = 
 7637:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 7638:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 7639:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 7640:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 7641:                         if (@choices > 0) {
 7642:                             foreach my $lonhost (@choices) {
 7643:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 7644:                             }
 7645:                         }
 7646:                         $canselect{$type} .= '</select>'."\n";
 7647:                     }
 7648:                 } else {
 7649:                     $current{$type} = &mt('Could not be determined');
 7650:                     if ($type eq 'primary') {
 7651:                         $canselect{$type} =  $othercontrol;
 7652:                     }
 7653:                 }
 7654:                 if ($type eq 'default') {
 7655:                     $datatable .= '<tr'.$css_class.'>';
 7656:                 }
 7657:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 7658:                               '<td>'.$current{$type}.'</td>'."\n".
 7659:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 7660:             }
 7661:             $itemcount ++;
 7662:         }
 7663:     }
 7664:     $$rowtotal += $itemcount;
 7665:     return $datatable;
 7666: }
 7667: 
 7668: sub possible_newspares {
 7669:     my ($server,$currspares,$serverhomes,$altids) = @_;
 7670:     my $serverhostname = &Apache::lonnet::hostname($server);
 7671:     my %excluded;
 7672:     if ($serverhostname ne '') {
 7673:         %excluded = (
 7674:                        $serverhostname => 1,
 7675:                     );
 7676:     }
 7677:     if (ref($currspares) eq 'HASH') {
 7678:         foreach my $type (keys(%{$currspares})) {
 7679:             if (ref($currspares->{$type}) eq 'ARRAY') {
 7680:                 if (@{$currspares->{$type}} > 0) {
 7681:                     foreach my $curr (@{$currspares->{$type}}) {
 7682:                         my $hostname = &Apache::lonnet::hostname($curr);
 7683:                         $excluded{$hostname} = 1;
 7684:                     }
 7685:                 }
 7686:             }
 7687:         }
 7688:     }
 7689:     my @choices;
 7690:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 7691:         if (keys(%{$serverhomes}) > 1) {
 7692:             foreach my $name (sort(keys(%{$serverhomes}))) {
 7693:                 unless ($excluded{$name}) {
 7694:                     if (exists($altids->{$serverhomes->{$name}})) {
 7695:                         push(@choices,$altids->{$serverhomes->{$name}});
 7696:                     } else {
 7697:                         push(@choices,$serverhomes->{$name});
 7698:                     }
 7699:                 }
 7700:             }
 7701:         }
 7702:     }
 7703:     return sort(@choices);
 7704: }
 7705: 
 7706: sub print_loadbalancing {
 7707:     my ($dom,$settings,$rowtotal) = @_;
 7708:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7709:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7710:     my $numinrow = 1;
 7711:     my $datatable;
 7712:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7713:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 7714:     if (ref($settings) eq 'HASH') {
 7715:         %existing = %{$settings};
 7716:     }
 7717:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 7718:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 7719:                                   \%currtargets,\%currrules,\%currcookies);
 7720:     } else {
 7721:         return;
 7722:     }
 7723:     my ($othertitle,$usertypes,$types) =
 7724:         &Apache::loncommon::sorted_inst_types($dom);
 7725:     my $rownum = 8;
 7726:     if (ref($types) eq 'ARRAY') {
 7727:         $rownum += scalar(@{$types});
 7728:     }
 7729:     my @css_class = ('LC_odd_row','LC_even_row');
 7730:     my $balnum = 0;
 7731:     my $islast;
 7732:     my (@toshow,$disabledtext);
 7733:     if (keys(%currbalancer) > 0) {
 7734:         @toshow = sort(keys(%currbalancer));
 7735:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 7736:             push(@toshow,'');
 7737:         }
 7738:     } else {
 7739:         @toshow = ('');
 7740:         $disabledtext = &mt('No existing load balancer');
 7741:     }
 7742:     foreach my $lonhost (@toshow) {
 7743:         if ($balnum == scalar(@toshow)-1) {
 7744:             $islast = 1;
 7745:         } else {
 7746:             $islast = 0;
 7747:         }
 7748:         my $cssidx = $balnum%2;
 7749:         my $targets_div_style = 'display: none';
 7750:         my $disabled_div_style = 'display: block';
 7751:         my $homedom_div_style = 'display: none';
 7752:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 7753:                       '<td rowspan="'.$rownum.'" valign="top">'.
 7754:                       '<p>';
 7755:         if ($lonhost eq '') {
 7756:             $datatable .= '<span class="LC_nobreak">';
 7757:             if (keys(%currbalancer) > 0) {
 7758:                 $datatable .= &mt('Add balancer:');
 7759:             } else {
 7760:                 $datatable .= &mt('Enable balancer:');
 7761:             }
 7762:             $datatable .= '&nbsp;'.
 7763:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 7764:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 7765:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 7766:                           '<option value="" selected="selected">'.&mt('None').
 7767:                           '</option>'."\n";
 7768:             foreach my $server (sort(keys(%servers))) {
 7769:                 next if ($currbalancer{$server});
 7770:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 7771:             }
 7772:             $datatable .=
 7773:                 '</select>'."\n".
 7774:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 7775:         } else {
 7776:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 7777:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 7778:                            &mt('Stop balancing').'</label>'.
 7779:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 7780:             $targets_div_style = 'display: block';
 7781:             $disabled_div_style = 'display: none';
 7782:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 7783:                 $homedom_div_style = 'display: block';
 7784:             }
 7785:         }
 7786:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 7787:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 7788:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 7789:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 7790:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 7791:         my @sparestypes = ('primary','default');
 7792:         my %typetitles = &sparestype_titles();
 7793:         my %hostherechecked = (
 7794:                                   no => ' checked="checked"',
 7795:                               );
 7796:         my %balcookiechecked = (
 7797:                                   no => ' checked="checked"',
 7798:                                );
 7799:         foreach my $sparetype (@sparestypes) {
 7800:             my $targettable;
 7801:             for (my $i=0; $i<$numspares; $i++) {
 7802:                 my $checked;
 7803:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 7804:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 7805:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 7806:                             $checked = ' checked="checked"';
 7807:                         }
 7808:                     }
 7809:                 }
 7810:                 my ($chkboxval,$disabled);
 7811:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 7812:                     $chkboxval = $spares[$i];
 7813:                 }
 7814:                 if (exists($currbalancer{$spares[$i]})) {
 7815:                     $disabled = ' disabled="disabled"';
 7816:                 }
 7817:                 $targettable .=
 7818:                     '<td><span class="LC_nobreak"><label>'.
 7819:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 7820:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 7821:                     '</span></label></span></td>';
 7822:                 my $rem = $i%($numinrow);
 7823:                 if ($rem == 0) {
 7824:                     if (($i > 0) && ($i < $numspares-1)) {
 7825:                         $targettable .= '</tr>';
 7826:                     }
 7827:                     if ($i < $numspares-1) {
 7828:                         $targettable .= '<tr>';
 7829:                     }
 7830:                 }
 7831:             }
 7832:             if ($targettable ne '') {
 7833:                 my $rem = $numspares%($numinrow);
 7834:                 my $colsleft = $numinrow - $rem;
 7835:                 if ($colsleft > 1 ) {
 7836:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7837:                                     '&nbsp;</td>';
 7838:                 } elsif ($colsleft == 1) {
 7839:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 7840:                 }
 7841:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 7842:                                '<table><tr>'.$targettable.'</tr></table><br />';
 7843:             }
 7844:             $hostherechecked{$sparetype} = '';
 7845:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 7846:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 7847:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 7848:                         $hostherechecked{$sparetype} = ' checked="checked"';
 7849:                         $hostherechecked{'no'} = '';
 7850:                     }
 7851:                 }
 7852:             }
 7853:         }
 7854:         if ($currcookies{$lonhost}) {
 7855:             %balcookiechecked = (
 7856:                                     yes => ' checked="checked"',
 7857:                                 );
 7858:         }
 7859:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 7860:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 7861:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 7862:         foreach my $sparetype (@sparestypes) {
 7863:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 7864:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 7865:                           '</i></label><br />';
 7866:         }
 7867:         $datatable .= &mt('Use balancer cookie').'<br />'.
 7868:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 7869:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 7870:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 7871:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 7872:                       '</div></td></tr>'.
 7873:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 7874:                                            $othertitle,$usertypes,$types,\%servers,
 7875:                                            \%currbalancer,$lonhost,
 7876:                                            $targets_div_style,$homedom_div_style,
 7877:                                            $css_class[$cssidx],$balnum,$islast);
 7878:         $$rowtotal += $rownum;
 7879:         $balnum ++;
 7880:     }
 7881:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 7882:     return $datatable;
 7883: }
 7884: 
 7885: sub get_loadbalancers_config {
 7886:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 7887:     return unless ((ref($servers) eq 'HASH') &&
 7888:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 7889:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 7890:                    (ref($currcookies) eq 'HASH'));
 7891:     if (keys(%{$existing}) > 0) {
 7892:         my $oldlonhost;
 7893:         foreach my $key (sort(keys(%{$existing}))) {
 7894:             if ($key eq 'lonhost') {
 7895:                 $oldlonhost = $existing->{'lonhost'};
 7896:                 $currbalancer->{$oldlonhost} = 1;
 7897:             } elsif ($key eq 'targets') {
 7898:                 if ($oldlonhost) {
 7899:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 7900:                 }
 7901:             } elsif ($key eq 'rules') {
 7902:                 if ($oldlonhost) {
 7903:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 7904:                 }
 7905:             } elsif (ref($existing->{$key}) eq 'HASH') {
 7906:                 $currbalancer->{$key} = 1;
 7907:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 7908:                 $currrules->{$key} = $existing->{$key}{'rules'};
 7909:                 if ($existing->{$key}{'cookie'}) {
 7910:                     $currcookies->{$key} = 1;
 7911:                 }
 7912:             }
 7913:         }
 7914:     } else {
 7915:         my ($balancerref,$targetsref) =
 7916:                 &Apache::lonnet::get_lonbalancer_config($servers);
 7917:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 7918:             foreach my $server (sort(keys(%{$balancerref}))) {
 7919:                 $currbalancer->{$server} = 1;
 7920:                 $currtargets->{$server} = $targetsref->{$server};
 7921:             }
 7922:         }
 7923:     }
 7924:     return;
 7925: }
 7926: 
 7927: sub loadbalancing_rules {
 7928:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 7929:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 7930:         $css_class,$balnum,$islast) = @_;
 7931:     my $output;
 7932:     my $num = 0;
 7933:     my ($alltypes,$othertypes,$titles) =
 7934:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 7935:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 7936:         foreach my $type (@{$alltypes}) {
 7937:             $num ++;
 7938:             my $current;
 7939:             if (ref($currrules) eq 'HASH') {
 7940:                 $current = $currrules->{$type};
 7941:             }
 7942:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 7943:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 7944:                     $current = '';
 7945:                 }
 7946:             }
 7947:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 7948:                                              $servers,$currbalancer,$lonhost,$dom,
 7949:                                              $targets_div_style,$homedom_div_style,
 7950:                                              $css_class,$balnum,$num,$islast);
 7951:         }
 7952:     }
 7953:     return $output;
 7954: }
 7955: 
 7956: sub loadbalancing_titles {
 7957:     my ($dom,$intdom,$usertypes,$types) = @_;
 7958:     my %othertypes = (
 7959:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 7960:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 7961:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 7962:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 7963:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 7964:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 7965:                      );
 7966:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 7967:     my @available;
 7968:     if (ref($types) eq 'ARRAY') {
 7969:         @available = @{$types};
 7970:     }
 7971:     unless (grep(/^default$/,@available)) {
 7972:         push(@available,'default');
 7973:     }
 7974:     unshift(@alltypes,@available);
 7975:     my %titles;
 7976:     foreach my $type (@alltypes) {
 7977:         if ($type =~ /^_LC_/) {
 7978:             $titles{$type} = $othertypes{$type};
 7979:         } elsif ($type eq 'default') {
 7980:             $titles{$type} = &mt('All users from [_1]',$dom);
 7981:             if (ref($types) eq 'ARRAY') {
 7982:                 if (@{$types} > 0) {
 7983:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 7984:                 }
 7985:             }
 7986:         } elsif (ref($usertypes) eq 'HASH') {
 7987:             $titles{$type} = $usertypes->{$type};
 7988:         }
 7989:     }
 7990:     return (\@alltypes,\%othertypes,\%titles);
 7991: }
 7992: 
 7993: sub loadbalance_rule_row {
 7994:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 7995:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 7996:     my @rulenames;
 7997:     my %ruletitles = &offloadtype_text();
 7998:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 7999:         @rulenames = ('balancer','offloadedto','specific');
 8000:     } else {
 8001:         @rulenames = ('default','homeserver');
 8002:         if ($type eq '_LC_external') {
 8003:             push(@rulenames,'externalbalancer');
 8004:         } else {
 8005:             push(@rulenames,'specific');
 8006:         }
 8007:         push(@rulenames,'none');
 8008:     }
 8009:     my $style = $targets_div_style;
 8010:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8011:         $style = $homedom_div_style;
 8012:     }
 8013:     my $space;
 8014:     if ($islast && $num == 1) {
 8015:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 8016:     }
 8017:     my $output =
 8018:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 8019:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 8020:         '<td valaign="top">'.$space.
 8021:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 8022:     for (my $i=0; $i<@rulenames; $i++) {
 8023:         my $rule = $rulenames[$i];
 8024:         my ($checked,$extra);
 8025:         if ($rulenames[$i] eq 'default') {
 8026:             $rule = '';
 8027:         }
 8028:         if ($rulenames[$i] eq 'specific') {
 8029:             if (ref($servers) eq 'HASH') {
 8030:                 my $default;
 8031:                 if (($current ne '') && (exists($servers->{$current}))) {
 8032:                     $checked = ' checked="checked"';
 8033:                 }
 8034:                 unless ($checked) {
 8035:                     $default = ' selected="selected"';
 8036:                 }
 8037:                 $extra =
 8038:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8039:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8040:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 8041:                     '<option value=""'.$default.'></option>'."\n";
 8042:                 foreach my $server (sort(keys(%{$servers}))) {
 8043:                     if (ref($currbalancer) eq 'HASH') {
 8044:                         next if (exists($currbalancer->{$server}));
 8045:                     }
 8046:                     my $selected;
 8047:                     if ($server eq $current) {
 8048:                         $selected = ' selected="selected"';
 8049:                     }
 8050:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 8051:                 }
 8052:                 $extra .= '</select>';
 8053:             }
 8054:         } elsif ($rule eq $current) {
 8055:             $checked = ' checked="checked"';
 8056:         }
 8057:         $output .= '<span class="LC_nobreak"><label>'.
 8058:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 8059:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 8060:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 8061:                    ')"'.$checked.' />&nbsp;';
 8062:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 8063:             $output .= $ruletitles{'particular'};
 8064:         } else {
 8065:             $output .= $ruletitles{$rulenames[$i]};
 8066:         }
 8067:         $output .= '</label>'.$extra.'</span><br />'."\n";
 8068:     }
 8069:     $output .= '</div></td></tr>'."\n";
 8070:     return $output;
 8071: }
 8072: 
 8073: sub offloadtype_text {
 8074:     my %ruletitles = &Apache::lonlocal::texthash (
 8075:            'default'          => 'Offloads to default destinations',
 8076:            'homeserver'       => "Offloads to user's home server",
 8077:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 8078:            'specific'         => 'Offloads to specific server',
 8079:            'none'             => 'No offload',
 8080:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 8081:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 8082:            'particular'       => 'Session hosted (after re-auth) on server:',
 8083:     );
 8084:     return %ruletitles;
 8085: }
 8086: 
 8087: sub sparestype_titles {
 8088:     my %typestitles = &Apache::lonlocal::texthash (
 8089:                           'primary' => 'primary',
 8090:                           'default' => 'default',
 8091:                       );
 8092:     return %typestitles;
 8093: }
 8094: 
 8095: sub contact_titles {
 8096:     my %titles = &Apache::lonlocal::texthash (
 8097:                    'supportemail'    => 'Support E-mail address',
 8098:                    'adminemail'      => 'Default Server Admin E-mail address',
 8099:                    'errormail'       => 'Error reports to be e-mailed to',
 8100:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 8101:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 8102:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 8103:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 8104:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 8105:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 8106:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 8107:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 8108:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 8109:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 8110:                    'errorweights'    => 'Weights used to compute error count',
 8111:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 8112:                  );
 8113:     my %short_titles = &Apache::lonlocal::texthash (
 8114:                            adminemail   => 'Admin E-mail address',
 8115:                            supportemail => 'Support E-mail',
 8116:                        );   
 8117:     return (\%titles,\%short_titles);
 8118: }
 8119: 
 8120: sub helpform_fields {
 8121:     my %titles =  &Apache::lonlocal::texthash (
 8122:                        'username'   => 'Name',
 8123:                        'user'       => 'Username/domain',
 8124:                        'phone'      => 'Phone',
 8125:                        'cc'         => 'Cc e-mail',
 8126:                        'course'     => 'Course Details',
 8127:                        'section'    => 'Sections',
 8128:                        'screenshot' => 'File upload',
 8129:     );
 8130:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 8131:     my %possoptions = (
 8132:                         username     => ['yes','no','req'],
 8133:                         phone        => ['yes','no','req'],
 8134:                         user         => ['yes','no'],
 8135:                         cc           => ['yes','no'],
 8136:                         course       => ['yes','no'],
 8137:                         section      => ['yes','no'],
 8138:                         screenshot   => ['yes','no'],
 8139:                       );
 8140:     my %fieldoptions = &Apache::lonlocal::texthash (
 8141:                          'yes'  => 'Optional',
 8142:                          'req'  => 'Required',
 8143:                          'no'   => "Not shown",
 8144:     );
 8145:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 8146: }
 8147: 
 8148: sub tool_titles {
 8149:     my %titles = &Apache::lonlocal::texthash (
 8150:                      aboutme    => 'Personal web page',
 8151:                      blog       => 'Blog',
 8152:                      webdav     => 'WebDAV',
 8153:                      portfolio  => 'Portfolio',
 8154:                      timezone   => 'Can set time zone',
 8155:                      official   => 'Official courses (with institutional codes)',
 8156:                      unofficial => 'Unofficial courses',
 8157:                      community  => 'Communities',
 8158:                      textbook   => 'Textbook courses',
 8159:                  );
 8160:     return %titles;
 8161: }
 8162: 
 8163: sub courserequest_titles {
 8164:     my %titles = &Apache::lonlocal::texthash (
 8165:                                    official   => 'Official',
 8166:                                    unofficial => 'Unofficial',
 8167:                                    community  => 'Communities',
 8168:                                    textbook   => 'Textbook',
 8169:                                    lti        => 'LTI Provider',
 8170:                                    norequest  => 'Not allowed',
 8171:                                    approval   => 'Approval by Dom. Coord.',
 8172:                                    validate   => 'With validation',
 8173:                                    autolimit  => 'Numerical limit',
 8174:                                    unlimited  => '(blank for unlimited)',
 8175:                  );
 8176:     return %titles;
 8177: }
 8178: 
 8179: sub authorrequest_titles {
 8180:     my %titles = &Apache::lonlocal::texthash (
 8181:                                    norequest  => 'Not allowed',
 8182:                                    approval   => 'Approval by Dom. Coord.',
 8183:                                    automatic  => 'Automatic approval',
 8184:                  );
 8185:     return %titles;
 8186: }
 8187: 
 8188: sub courserequest_conditions {
 8189:     my %conditions = &Apache::lonlocal::texthash (
 8190:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 8191:        validate   => '(Processing of request subject to institutional validation).',
 8192:                  );
 8193:     return %conditions;
 8194: }
 8195: 
 8196: 
 8197: sub print_usercreation {
 8198:     my ($position,$dom,$settings,$rowtotal) = @_;
 8199:     my $numinrow = 4;
 8200:     my $datatable;
 8201:     if ($position eq 'top') {
 8202:         $$rowtotal ++;
 8203:         my $rowcount = 0;
 8204:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 8205:         if (ref($rules) eq 'HASH') {
 8206:             if (keys(%{$rules}) > 0) {
 8207:                 $datatable .= &user_formats_row('username',$settings,$rules,
 8208:                                                 $ruleorder,$numinrow,$rowcount);
 8209:                 $$rowtotal ++;
 8210:                 $rowcount ++;
 8211:             }
 8212:         }
 8213:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 8214:         if (ref($idrules) eq 'HASH') {
 8215:             if (keys(%{$idrules}) > 0) {
 8216:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 8217:                                                 $idruleorder,$numinrow,$rowcount);
 8218:                 $$rowtotal ++;
 8219:                 $rowcount ++;
 8220:             }
 8221:         }
 8222:         if ($rowcount == 0) {
 8223:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 8224:             $$rowtotal ++;
 8225:             $rowcount ++;
 8226:         }
 8227:     } elsif ($position eq 'middle') {
 8228:         my @creators = ('author','course','requestcrs');
 8229:         my ($rules,$ruleorder) =
 8230:             &Apache::lonnet::inst_userrules($dom,'username');
 8231:         my %lt = &usercreation_types();
 8232:         my %checked;
 8233:         if (ref($settings) eq 'HASH') {
 8234:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 8235:                 foreach my $item (@creators) {
 8236:                     $checked{$item} = $settings->{'cancreate'}{$item};
 8237:                 }
 8238:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 8239:                 foreach my $item (@creators) {
 8240:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 8241:                         $checked{$item} = 'none';
 8242:                     }
 8243:                 }
 8244:             }
 8245:         }
 8246:         my $rownum = 0;
 8247:         foreach my $item (@creators) {
 8248:             $rownum ++;
 8249:             if ($checked{$item} eq '') {
 8250:                 $checked{$item} = 'any';
 8251:             }
 8252:             my $css_class;
 8253:             if ($rownum%2) {
 8254:                 $css_class = '';
 8255:             } else {
 8256:                 $css_class = ' class="LC_odd_row" ';
 8257:             }
 8258:             $datatable .= '<tr'.$css_class.'>'.
 8259:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 8260:                          '</span></td><td align="right">';
 8261:             my @options = ('any');
 8262:             if (ref($rules) eq 'HASH') {
 8263:                 if (keys(%{$rules}) > 0) {
 8264:                     push(@options,('official','unofficial'));
 8265:                 }
 8266:             }
 8267:             push(@options,'none');
 8268:             foreach my $option (@options) {
 8269:                 my $type = 'radio';
 8270:                 my $check = ' ';
 8271:                 if ($checked{$item} eq $option) {
 8272:                     $check = ' checked="checked" ';
 8273:                 } 
 8274:                 $datatable .= '<span class="LC_nobreak"><label>'.
 8275:                               '<input type="'.$type.'" name="can_createuser_'.
 8276:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 8277:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 8278:             }
 8279:             $datatable .= '</td></tr>';
 8280:         }
 8281:     } else {
 8282:         my @contexts = ('author','course','domain');
 8283:         my @authtypes = ('int','krb4','krb5','loc','lti');
 8284:         my %checked;
 8285:         if (ref($settings) eq 'HASH') {
 8286:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 8287:                 foreach my $item (@contexts) {
 8288:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 8289:                         foreach my $auth (@authtypes) {
 8290:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 8291:                                 $checked{$item}{$auth} = ' checked="checked" ';
 8292:                             }
 8293:                         }
 8294:                     }
 8295:                 }
 8296:             }
 8297:         } else {
 8298:             foreach my $item (@contexts) {
 8299:                 foreach my $auth (@authtypes) {
 8300:                     $checked{$item}{$auth} = ' checked="checked" ';
 8301:                 }
 8302:             }
 8303:         }
 8304:         my %title = &context_names();
 8305:         my %authname = &authtype_names();
 8306:         my $rownum = 0;
 8307:         my $css_class; 
 8308:         foreach my $item (@contexts) {
 8309:             if ($rownum%2) {
 8310:                 $css_class = '';
 8311:             } else {
 8312:                 $css_class = ' class="LC_odd_row" ';
 8313:             }
 8314:             $datatable .=   '<tr'.$css_class.'>'.
 8315:                             '<td>'.$title{$item}.
 8316:                             '</td><td class="LC_left_item">'.
 8317:                             '<span class="LC_nobreak">';
 8318:             foreach my $auth (@authtypes) {
 8319:                 $datatable .= '<label>'. 
 8320:                               '<input type="checkbox" name="'.$item.'_auth" '.
 8321:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 8322:                               $authname{$auth}.'</label>&nbsp;';
 8323:             }
 8324:             $datatable .= '</span></td></tr>';
 8325:             $rownum ++;
 8326:         }
 8327:         $$rowtotal += $rownum;
 8328:     }
 8329:     return $datatable;
 8330: }
 8331: 
 8332: sub print_selfcreation {
 8333:     my ($position,$dom,$settings,$rowtotal) = @_;
 8334:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 8335:         $emaildomain,$datatable);
 8336:     if (ref($settings) eq 'HASH') {
 8337:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 8338:             $createsettings = $settings->{'cancreate'};
 8339:             if (ref($createsettings) eq 'HASH') {
 8340:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 8341:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 8342:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 8343:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 8344:                         @selfcreate = ('email','login','sso');
 8345:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 8346:                         @selfcreate = ($createsettings->{'selfcreate'});
 8347:                     }
 8348:                 }
 8349:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 8350:                     $processing = $createsettings->{'selfcreateprocessing'};
 8351:                 }
 8352:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 8353:                     $emailoptions = $createsettings->{'emailoptions'};
 8354:                 }
 8355:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 8356:                     $emailverified = $createsettings->{'emailverified'};
 8357:                 }
 8358:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 8359:                     $emaildomain = $createsettings->{'emaildomain'};
 8360:                 }
 8361:             }
 8362:         }
 8363:     }
 8364:     my %radiohash;
 8365:     my $numinrow = 4;
 8366:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 8367:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8368:     if ($position eq 'top') {
 8369:         my %choices = &Apache::lonlocal::texthash (
 8370:                                                       cancreate_login      => 'Institutional Login',
 8371:                                                       cancreate_sso        => 'Institutional Single Sign On',
 8372:                                                   );
 8373:         my @toggles = sort(keys(%choices));
 8374:         my %defaultchecked = (
 8375:                                'cancreate_login' => 'off',
 8376:                                'cancreate_sso'   => 'off',
 8377:                              );
 8378:         my ($onclick,$itemcount);
 8379:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 8380:                                                      \%choices,$itemcount,$onclick);
 8381:         $$rowtotal += $itemcount;
 8382: 
 8383:         if (ref($usertypes) eq 'HASH') {
 8384:             if (keys(%{$usertypes}) > 0) {
 8385:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 8386:                                              $dom,$numinrow,$othertitle,
 8387:                                              'statustocreate',$rowtotal);
 8388:                 $$rowtotal ++;
 8389:             }
 8390:         }
 8391:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 8392:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 8393:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 8394:         my $rem;
 8395:         my $numperrow = 2;
 8396:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 8397:         $datatable .= '<tr'.$css_class.'>'.
 8398:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 8399:                      '<td class="LC_left_item">'."\n".
 8400:                      '<table>'."\n";
 8401:         for (my $i=0; $i<@fields; $i++) {
 8402:             $rem = $i%($numperrow);
 8403:             if ($rem == 0) {
 8404:                 if ($i > 0) {
 8405:                     $datatable .= '</tr>';
 8406:                 }
 8407:                 $datatable .= '<tr>';
 8408:             }
 8409:             my $currval;
 8410:             if (ref($createsettings) eq 'HASH') {
 8411:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 8412:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 8413:                 }
 8414:             }
 8415:             $datatable .= '<td class="LC_left_item">'.
 8416:                           '<span class="LC_nobreak">'.
 8417:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 8418:                           'value="'.$currval.'" size="10" />&nbsp;'.
 8419:                           $fieldtitles{$fields[$i]}.'</span></td>';
 8420:         }
 8421:         my $colsleft = $numperrow - $rem;
 8422:         if ($colsleft > 1 ) {
 8423:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8424:                          '&nbsp;</td>';
 8425:         } elsif ($colsleft == 1) {
 8426:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8427:         }
 8428:         $datatable .= '</tr></table></td></tr>';
 8429:         $$rowtotal ++;
 8430:     } elsif ($position eq 'middle') {
 8431:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 8432:         my @posstypes;
 8433:         if (ref($types) eq 'ARRAY') {
 8434:             @posstypes = @{$types};
 8435:         }
 8436:         unless (grep(/^default$/,@posstypes)) {
 8437:             push(@posstypes,'default');
 8438:         }
 8439:         my %usertypeshash;
 8440:         if (ref($usertypes) eq 'HASH') {
 8441:             %usertypeshash = %{$usertypes};
 8442:         }
 8443:         $usertypeshash{'default'} = $othertitle;
 8444:         foreach my $status (@posstypes) {
 8445:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 8446:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 8447:             $$rowtotal ++;
 8448:         }
 8449:     } else {
 8450:         my %choices = &Apache::lonlocal::texthash (
 8451:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 8452:                                                   );
 8453:         my @toggles = sort(keys(%choices));
 8454:         my %defaultchecked = (
 8455:                                'cancreate_email' => 'off',
 8456:                              );
 8457:         my $customclass = 'LC_selfcreate_email';
 8458:         my $classprefix = 'LC_canmodify_emailusername_';
 8459:         my $optionsprefix = 'LC_options_emailusername_';
 8460:         my $display = 'none';
 8461:         my $rowstyle = 'display:none';
 8462:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 8463:             $display = 'block';
 8464:             $rowstyle = 'display:table-row';
 8465:         }
 8466:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 8467:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 8468:                                                      \%choices,$$rowtotal,$onclick);
 8469:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 8470:                                          $rowstyle);
 8471:         $$rowtotal ++;
 8472:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 8473:                                       $rowstyle);
 8474:         $$rowtotal ++;
 8475:         my (@ordered,@posstypes,%usertypeshash);
 8476:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 8477:         my ($emailrules,$emailruleorder) =
 8478:             &Apache::lonnet::inst_userrules($dom,'email');
 8479:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8480:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8481:         if (ref($types) eq 'ARRAY') {
 8482:             @posstypes = @{$types};
 8483:         }
 8484:         if (@posstypes) {
 8485:             unless (grep(/^default$/,@posstypes)) {
 8486:                 push(@posstypes,'default');
 8487:             }
 8488:             if (ref($usertypes) eq 'HASH') {
 8489:                 %usertypeshash = %{$usertypes};
 8490:             }
 8491:             my $currassign;
 8492:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 8493:                 $currassign = {
 8494:                                   selfassign => $domdefaults{'inststatusguest'},
 8495:                               };
 8496:                 @ordered = @{$domdefaults{'inststatusguest'}};
 8497:             } else {
 8498:                 $currassign = { selfassign => [] };
 8499:             }
 8500:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 8501:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 8502:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 8503:                                          $numinrow,$othertitle,'selfassign',
 8504:                                          $rowtotal,$onclicktypes,$customclass,
 8505:                                          $rowstyle);
 8506:             $$rowtotal ++;
 8507:             $usertypeshash{'default'} = $othertitle;
 8508:             foreach my $status (@posstypes) {
 8509:                 my $css_class;
 8510:                 if ($$rowtotal%2) {
 8511:                     $css_class = 'LC_odd_row ';
 8512:                 }
 8513:                 $css_class .= $customclass;
 8514:                 my $rowid = $optionsprefix.$status;
 8515:                 my $hidden = 1;
 8516:                 my $currstyle = 'display:none';
 8517:                 if (grep(/^\Q$status\E$/,@ordered)) {
 8518:                     $currstyle = $rowstyle;
 8519:                     $hidden = 0;
 8520:                 }
 8521:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 8522:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 8523:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 8524:                 unless ($hidden) {
 8525:                     $$rowtotal ++;
 8526:                 }
 8527:             }
 8528:         } else {
 8529:             my $css_class;
 8530:             if ($$rowtotal%2) {
 8531:                 $css_class = 'LC_odd_row ';
 8532:             }
 8533:             $css_class .= $customclass;
 8534:             $usertypeshash{'default'} = $othertitle;
 8535:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 8536:                                          $emailrules,$emailruleorder,$settings,'default','',
 8537:                                          $othertitle,$css_class,$rowstyle,$intdom);
 8538:             $$rowtotal ++;
 8539:         }
 8540:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 8541:         $numinrow = 1;
 8542:         if (@posstypes) {
 8543:             foreach my $status (@posstypes) {
 8544:                 my $rowid = $classprefix.$status;
 8545:                 my $datarowstyle = 'display:none';
 8546:                 if (grep(/^\Q$status\E$/,@ordered)) {
 8547:                     $datarowstyle = $rowstyle;
 8548:                 }
 8549:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 8550:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 8551:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 8552:                 unless ($datarowstyle eq 'display:none') {
 8553:                     $$rowtotal ++;
 8554:                 }
 8555:             }
 8556:         } else {
 8557:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 8558:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 8559:                                                    $infotitles,'',$customclass,$rowstyle);
 8560:         }
 8561:     }
 8562:     return $datatable;
 8563: }
 8564: 
 8565: sub selfcreate_javascript {
 8566:     return <<"ENDSCRIPT";
 8567: 
 8568: <script type="text/javascript">
 8569: // <![CDATA[
 8570: 
 8571: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 8572:     var x = document.getElementsByClassName(target);
 8573:     var insttypes = 0;
 8574:     var insttypeRegExp = new RegExp(prefix);
 8575:     if ((x.length != undefined) && (x.length > 0)) {
 8576:         if (form.elements[radio].length != undefined) {
 8577:             for (var i=0; i<form.elements[radio].length; i++) {
 8578:                 if (form.elements[radio][i].checked) {
 8579:                     if (form.elements[radio][i].value == 1) {
 8580:                         for (var j=0; j<x.length; j++) {
 8581:                             if (x[j].id == 'undefined') {
 8582:                                 x[j].style.display = 'table-row';
 8583:                             } else if (insttypeRegExp.test(x[j].id)) {
 8584:                                 insttypes ++;
 8585:                             } else {
 8586:                                 x[j].style.display = 'table-row';
 8587:                             }
 8588:                         }
 8589:                     } else {
 8590:                         for (var j=0; j<x.length; j++) {
 8591:                             x[j].style.display = 'none';
 8592:                         }
 8593:                     }
 8594:                     break;
 8595:                 }
 8596:             }
 8597:             if (insttypes > 0) {
 8598:                 toggleDataRow(form,checkbox,target,altprefix);
 8599:                 toggleDataRow(form,checkbox,target,prefix,1);
 8600:             }
 8601:         }
 8602:     }
 8603:     return;
 8604: }
 8605: 
 8606: function toggleDataRow(form,checkbox,target,prefix,docount) {
 8607:     if (form.elements[checkbox].length != undefined) {
 8608:         var count = 0;
 8609:         if (docount) {
 8610:             for (var i=0; i<form.elements[checkbox].length; i++) {
 8611:                 if (form.elements[checkbox][i].checked) {
 8612:                     count ++;
 8613:                 }
 8614:             }
 8615:         }
 8616:         for (var i=0; i<form.elements[checkbox].length; i++) {
 8617:             var type = form.elements[checkbox][i].value;
 8618:             if (document.getElementById(prefix+type)) {
 8619:                 if (form.elements[checkbox][i].checked) {
 8620:                     document.getElementById(prefix+type).style.display = 'table-row';
 8621:                     if (count % 2 == 1) {
 8622:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 8623:                     } else {
 8624:                         document.getElementById(prefix+type).className = target;
 8625:                     }
 8626:                     count ++;
 8627:                 } else {
 8628:                     document.getElementById(prefix+type).style.display = 'none';
 8629:                 }
 8630:             }
 8631:         }
 8632:     }
 8633:     return;
 8634: }
 8635: 
 8636: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 8637:     var caller = radio+'_'+status;
 8638:     if (form.elements[caller].length != undefined) {
 8639:         for (var i=0; i<form.elements[caller].length; i++) {
 8640:             if (form.elements[caller][i].checked) {
 8641:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 8642:                     var curr = form.elements[caller][i].value;
 8643:                     if (prefix) {
 8644:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 8645:                     }
 8646:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 8647:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 8648:                     if (curr == 'custom') {
 8649:                         if (prefix) {
 8650:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 8651:                         }
 8652:                     } else if (curr == 'inst') {
 8653:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 8654:                     } else if (curr == 'noninst') {
 8655:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 8656:                     }
 8657:                     break;
 8658:                 }
 8659:             }
 8660:         }
 8661:     }
 8662: }
 8663: 
 8664: // ]]>
 8665: </script>
 8666: 
 8667: ENDSCRIPT
 8668: }
 8669: 
 8670: sub noninst_users {
 8671:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 8672:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_;
 8673:     my $class = 'LC_left_item';
 8674:     if ($css_class) {
 8675:         $css_class = ' class="'.$css_class.'"';
 8676:     }
 8677:     if ($rowid) {
 8678:         $rowid = ' id="'.$rowid.'"';
 8679:     }
 8680:     if ($rowstyle) {
 8681:         $rowstyle = ' style="'.$rowstyle.'"';
 8682:     }
 8683:     my ($output,$description);
 8684:     if ($type eq 'default') {
 8685:         $description = &mt('Requests for: [_1]',$typetitle);
 8686:     } else {
 8687:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 8688:     }
 8689:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 8690:               "<td>$description</td>\n".
 8691:               '<td class="'.$class.'" colspan="2">'.
 8692:               '<table><tr>';
 8693:     my %headers = &Apache::lonlocal::texthash(
 8694:               approve  => 'Processing',
 8695:               email    => 'E-mail',
 8696:               username => 'Username',
 8697:     );
 8698:     foreach my $item ('approve','email','username') {
 8699:         $output .= '<th>'.$headers{$item}.'</th>';
 8700:     }
 8701:     $output .= '</tr><tr>';
 8702:     foreach my $item ('approve','email','username') {
 8703:         $output .= '<td valign="top">';
 8704:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 8705:         if ($item eq 'approve') {
 8706:             %choices = &Apache::lonlocal::texthash (
 8707:                                                      automatic => 'Automatically approved',
 8708:                                                      approval  => 'Queued for approval',
 8709:                                                    );
 8710:             @options = ('automatic','approval');
 8711:             $hashref = $processing;
 8712:             $defoption = 'automatic';
 8713:             $name = 'cancreate_emailprocess_'.$type;
 8714:         } elsif ($item eq 'email') {
 8715:             %choices = &Apache::lonlocal::texthash (
 8716:                                                      any     => 'Any e-mail',
 8717:                                                      inst    => 'Institutional only',
 8718:                                                      noninst => 'Non-institutional only',
 8719:                                                      custom  => 'Custom restrictions',
 8720:                                                    );
 8721:             @options = ('any','inst','noninst');
 8722:             my $showcustom;
 8723:             if (ref($emailrules) eq 'HASH') {
 8724:                 if (keys(%{$emailrules}) > 0) {
 8725:                     push(@options,'custom');
 8726:                     $showcustom = 'cancreate_emailrule';
 8727:                     if (ref($settings) eq 'HASH') {
 8728:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 8729:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 8730:                                 if (exists($emailrules->{$rule})) {
 8731:                                     $hascustom ++;
 8732:                                 }
 8733:                             }
 8734:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 8735:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 8736:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 8737:                                     if (exists($emailrules->{$rule})) {
 8738:                                         $hascustom ++;
 8739:                                     }
 8740:                                 }
 8741:                             }
 8742:                         }
 8743:                     }
 8744:                 }
 8745:             }
 8746:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 8747:                                                      "'cancreate_emaildomain','$type'".');"';
 8748:             $hashref = $emailoptions;
 8749:             $defoption = 'any';
 8750:             $name = 'cancreate_emailoptions_'.$type;
 8751:         } elsif ($item eq 'username') {
 8752:             %choices = &Apache::lonlocal::texthash (
 8753:                                                      all    => 'Same as e-mail',
 8754:                                                      first  => 'Omit @domain',
 8755:                                                      free   => 'Free to choose',
 8756:                                                    );
 8757:             @options = ('all','first','free');
 8758:             $hashref = $emailverified;
 8759:             $defoption = 'all';
 8760:             $name = 'cancreate_usernameoptions_'.$type;
 8761:         }
 8762:         foreach my $option (@options) {
 8763:             my $checked;
 8764:             if (ref($hashref) eq 'HASH') {
 8765:                 if ($type eq '') {
 8766:                     if (!exists($hashref->{'default'})) {
 8767:                         if ($option eq $defoption) {
 8768:                             $checked = ' checked="checked"';
 8769:                         }
 8770:                     } else {
 8771:                         if ($hashref->{'default'} eq $option) {
 8772:                             $checked = ' checked="checked"';
 8773:                         }
 8774:                     }
 8775:                 } else {
 8776:                     if (!exists($hashref->{$type})) {
 8777:                         if ($option eq $defoption) {
 8778:                             $checked = ' checked="checked"';
 8779:                         }
 8780:                     } else {
 8781:                         if ($hashref->{$type} eq $option) {
 8782:                             $checked = ' checked="checked"';
 8783:                         }
 8784:                     }
 8785:                 }
 8786:             } elsif (($item eq 'email') && ($hascustom)) {
 8787:                 if ($option eq 'custom') {
 8788:                     $checked = ' checked="checked"';
 8789:                 }
 8790:             } elsif ($option eq $defoption) {
 8791:                 $checked = ' checked="checked"';
 8792:             }
 8793:             $output .= '<span class="LC_nobreak"><label>'.
 8794:                        '<input type="radio" name="'.$name.'"'.
 8795:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 8796:                        $choices{$option}.'</label></span><br />';
 8797:             if ($item eq 'email') {
 8798:                 if ($option eq 'custom') {
 8799:                     my $id = 'cancreate_emailrule_'.$type;
 8800:                     my $display = 'none';
 8801:                     if ($checked) {
 8802:                         $display = 'inline';
 8803:                     }
 8804:                     my $numinrow = 2;
 8805:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 8806:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 8807:                                &user_formats_row('email',$settings,$emailrules,
 8808:                                                  $emailruleorder,$numinrow,'',$type);
 8809:                               '</table></fieldset>';
 8810:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 8811:                     my %text = &Apache::lonlocal::texthash (
 8812:                                                              inst    => 'must end:',
 8813:                                                              noninst => 'cannot end:',
 8814:                                                            );
 8815:                     my $value;
 8816:                     if (ref($emaildomain) eq 'HASH') {
 8817:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 8818:                             $value = $emaildomain->{$type}->{$option};
 8819:                         }
 8820:                     }
 8821:                     if ($value eq '') {
 8822:                         $value = '@'.$intdom;
 8823:                     }
 8824:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 8825:                     my $display = 'none';
 8826:                     if ($checked) {
 8827:                         $display = 'inline';
 8828:                     }
 8829:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 8830:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 8831:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 8832:                                '</div>';
 8833:                 }
 8834:             }
 8835:         }
 8836:         $output .= '</td>'."\n";
 8837:     }
 8838:     $output .= "</tr></table></td></tr>\n";
 8839:     return $output;
 8840: }
 8841: 
 8842: sub captcha_choice {
 8843:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 8844:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 8845:         $vertext,$currver);
 8846:     my %lt = &captcha_phrases();
 8847:     $keyentry = 'hidden';
 8848:     my $colspan=2;
 8849:     if ($context eq 'cancreate') {
 8850:         $rowname = &mt('CAPTCHA validation');
 8851:     } elsif ($context eq 'login') {
 8852:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 8853:     } elsif ($context eq 'passwords') {
 8854:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 8855:         $colspan=1;
 8856:     }
 8857:     if (ref($settings) eq 'HASH') {
 8858:         if ($settings->{'captcha'}) {
 8859:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 8860:         } else {
 8861:             $checked{'original'} = ' checked="checked"';
 8862:         }
 8863:         if ($settings->{'captcha'} eq 'recaptcha') {
 8864:             $pubtext = $lt{'pub'};
 8865:             $privtext = $lt{'priv'};
 8866:             $keyentry = 'text';
 8867:             $vertext = $lt{'ver'};
 8868:             $currver = $settings->{'recaptchaversion'};
 8869:             if ($currver ne '2') {
 8870:                 $currver = 1;
 8871:             }
 8872:         }
 8873:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 8874:             $currpub = $settings->{'recaptchakeys'}{'public'};
 8875:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 8876:         }
 8877:     } else {
 8878:         $checked{'original'} = ' checked="checked"';
 8879:     }
 8880:     my $css_class;
 8881:     if ($itemcount%2) {
 8882:         $css_class = 'LC_odd_row';
 8883:     }
 8884:     if ($customcss) {
 8885:         $css_class .= " $customcss";
 8886:     }
 8887:     $css_class =~ s/^\s+//;
 8888:     if ($css_class) {
 8889:         $css_class = ' class="'.$css_class.'"';
 8890:     }
 8891:     if ($rowstyle) {
 8892:         $css_class .= ' style="'.$rowstyle.'"';
 8893:     }
 8894:     my $output = '<tr'.$css_class.'>'.
 8895:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 8896:                  '<table><tr><td>'."\n";
 8897:     foreach my $option ('original','recaptcha','notused') {
 8898:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 8899:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 8900:                    $lt{$option}.'</label></span>';
 8901:         unless ($option eq 'notused') {
 8902:             $output .= ('&nbsp;'x2)."\n";
 8903:         }
 8904:     }
 8905: #
 8906: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 8907: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 8908: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 8909: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 8910: #
 8911:     $output .= '</td></tr>'."\n".
 8912:                '<tr><td class="LC_zero_height">'."\n".
 8913:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 8914:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 8915:                $currpub.'" size="40" /></span><br />'."\n".
 8916:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 8917:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 8918:                $currpriv.'" size="40" /></span><br />'.
 8919:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 8920:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 8921:                $currver.'" size="3" /></span><br />'.
 8922:                '</td></tr></table>'."\n".
 8923:                '</td></tr>';
 8924:     return $output;
 8925: }
 8926: 
 8927: sub user_formats_row {
 8928:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 8929:     my $output;
 8930:     my %text = (
 8931:                    'username' => 'new usernames',
 8932:                    'id'       => 'IDs',
 8933:                );
 8934:     unless (($type eq 'email') || ($type eq 'unamemap')) {
 8935:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 8936:         $output = '<tr '.$css_class.'>'.
 8937:                   '<td><span class="LC_nobreak">'.
 8938:                   &mt("Format rules to check for $text{$type}: ").
 8939:                   '</td><td class="LC_left_item" colspan="2"><table>';
 8940:     }
 8941:     my $rem;
 8942:     if (ref($ruleorder) eq 'ARRAY') {
 8943:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 8944:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 8945:                 my $rem = $i%($numinrow);
 8946:                 if ($rem == 0) {
 8947:                     if ($i > 0) {
 8948:                         $output .= '</tr>';
 8949:                     }
 8950:                     $output .= '<tr>';
 8951:                 }
 8952:                 my $check = ' ';
 8953:                 if (ref($settings) eq 'HASH') {
 8954:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 8955:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 8956:                             $check = ' checked="checked" ';
 8957:                         }
 8958:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 8959:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 8960:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 8961:                                 $check = ' checked="checked" ';
 8962:                             }
 8963:                         }
 8964:                     }
 8965:                 }
 8966:                 my $name = $type.'_rule';
 8967:                 if ($type eq 'email') {
 8968:                     $name .= '_'.$status;
 8969:                 }
 8970:                 $output .= '<td class="LC_left_item">'.
 8971:                            '<span class="LC_nobreak"><label>'.
 8972:                            '<input type="checkbox" name="'.$name.'" '.
 8973:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 8974:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 8975:             }
 8976:         }
 8977:         $rem = @{$ruleorder}%($numinrow);
 8978:     }
 8979:     my $colsleft;
 8980:     if ($rem) {
 8981:         $colsleft = $numinrow - $rem;
 8982:     }
 8983:     if ($colsleft > 1 ) {
 8984:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8985:                    '&nbsp;</td>';
 8986:     } elsif ($colsleft == 1) {
 8987:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 8988:     }
 8989:     $output .= '</tr>';
 8990:     unless (($type eq 'email') || ($type eq 'unamemap')) {
 8991:         $output .= '</table></td></tr>';
 8992:     }
 8993:     return $output;
 8994: }
 8995: 
 8996: sub usercreation_types {
 8997:     my %lt = &Apache::lonlocal::texthash (
 8998:                     author     => 'When adding a co-author',
 8999:                     course     => 'When adding a user to a course',
 9000:                     requestcrs => 'When requesting a course',
 9001:                     any        => 'Any',
 9002:                     official   => 'Institutional only ',
 9003:                     unofficial => 'Non-institutional only',
 9004:                     none       => 'None',
 9005:     );
 9006:     return %lt;
 9007: }
 9008: 
 9009: sub selfcreation_types {
 9010:     my %lt = &Apache::lonlocal::texthash (
 9011:                     selfcreate => 'User creates own account',
 9012:                     any        => 'Any',
 9013:                     official   => 'Institutional only ',
 9014:                     unofficial => 'Non-institutional only',
 9015:                     email      => 'E-mail address',
 9016:                     login      => 'Institutional Login',
 9017:                     sso        => 'SSO',
 9018:              );
 9019: }
 9020: 
 9021: sub authtype_names {
 9022:     my %lt = &Apache::lonlocal::texthash(
 9023:                       int    => 'Internal',
 9024:                       krb4   => 'Kerberos 4',
 9025:                       krb5   => 'Kerberos 5',
 9026:                       loc    => 'Local',
 9027:                       lti    => 'LTI',
 9028:                   );
 9029:     return %lt;
 9030: }
 9031: 
 9032: sub context_names {
 9033:     my %context_title = &Apache::lonlocal::texthash(
 9034:        author => 'Creating users when an Author',
 9035:        course => 'Creating users when in a course',
 9036:        domain => 'Creating users when a Domain Coordinator',
 9037:     );
 9038:     return %context_title;
 9039: }
 9040: 
 9041: sub print_usermodification {
 9042:     my ($position,$dom,$settings,$rowtotal) = @_;
 9043:     my $numinrow = 4;
 9044:     my ($context,$datatable,$rowcount);
 9045:     if ($position eq 'top') {
 9046:         $rowcount = 0;
 9047:         $context = 'author'; 
 9048:         foreach my $role ('ca','aa') {
 9049:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9050:                                                    $numinrow,$rowcount);
 9051:             $$rowtotal ++;
 9052:             $rowcount ++;
 9053:         }
 9054:     } elsif ($position eq 'bottom') {
 9055:         $context = 'course';
 9056:         $rowcount = 0;
 9057:         foreach my $role ('st','ep','ta','in','cr') {
 9058:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9059:                                                    $numinrow,$rowcount);
 9060:             $$rowtotal ++;
 9061:             $rowcount ++;
 9062:         }
 9063:     }
 9064:     return $datatable;
 9065: }
 9066: 
 9067: sub print_defaults {
 9068:     my ($position,$dom,$settings,$rowtotal) = @_;
 9069:     my $rownum = 0;
 9070:     my ($datatable,$css_class,$titles);
 9071:     unless ($position eq 'bottom') {
 9072:         $titles = &defaults_titles($dom);
 9073:     }
 9074:     if ($position eq 'top') {
 9075:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 9076:                      'datelocale_def','portal_def');
 9077:         my %defaults;
 9078:         if (ref($settings) eq 'HASH') {
 9079:             %defaults = %{$settings};
 9080:         } else {
 9081:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 9082:             foreach my $item (@items) {
 9083:                 $defaults{$item} = $domdefaults{$item};
 9084:             }
 9085:         }
 9086:         foreach my $item (@items) {
 9087:             if ($rownum%2) {
 9088:                 $css_class = '';
 9089:             } else {
 9090:                 $css_class = ' class="LC_odd_row" ';
 9091:             }
 9092:             $datatable .= '<tr'.$css_class.'>'.
 9093:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 9094:                           '</span></td><td class="LC_right_item" colspan="3">';
 9095:             if ($item eq 'auth_def') {
 9096:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
 9097:                 my %shortauth = (
 9098:                                  internal => 'int',
 9099:                                  krb4 => 'krb4',
 9100:                                  krb5 => 'krb5',
 9101:                                  localauth  => 'loc',
 9102:                                  lti => 'lti',
 9103:                                 );
 9104:                 my %authnames = &authtype_names();
 9105:                 foreach my $auth (@authtypes) {
 9106:                     my $checked = ' ';
 9107:                     if ($defaults{$item} eq $auth) {
 9108:                         $checked = ' checked="checked" ';
 9109:                     }
 9110:                     $datatable .= '<label><input type="radio" name="'.$item.
 9111:                                   '" value="'.$auth.'"'.$checked.'/>'.
 9112:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 9113:                 }
 9114:             } elsif ($item eq 'timezone_def') {
 9115:                 my $includeempty = 1;
 9116:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 9117:             } elsif ($item eq 'datelocale_def') {
 9118:                 my $includeempty = 1;
 9119:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 9120:             } elsif ($item eq 'lang_def') {
 9121:                 my $includeempty = 1;
 9122:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 9123:             } elsif ($item eq 'portal_def') {
 9124:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 9125:                               $defaults{$item}.'" size="25" onkeyup="portalExtras(this);" />';
 9126:                 my $portalsty = 'none';
 9127:                 if ($defaults{$item}) {
 9128:                     $portalsty = 'block';
 9129:                 }
 9130:                 foreach my $field ('email','web') {
 9131:                     my $checkedoff = ' checked="checked"';
 9132:                     my $checkedon;
 9133:                     if ($defaults{$item.'_'.$field}) {
 9134:                         $checkedon = $checkedoff;
 9135:                         $checkedoff = '';
 9136:                     }
 9137:                     $datatable .= '<div id="'.$item.'_'.$field.'_div" style="display:'.$portalsty.'">'.
 9138:                               '<span class="LC_nobreak">'.$titles->{$field}.'&nbsp;'.
 9139:                               '<label><input type="radio" name="'.$item.'_'.$field.'" value="1"'.$checkedon.'/>'.&mt('Yes').'</label>'.
 9140:                               ('&nbsp;'x2).
 9141:                               '<label><input type="radio" name="'.$item.'_'.$field.'" value="0"'.$checkedoff.'/>'.&mt('No').'</label>'.
 9142:                               '</div>';
 9143:                 }
 9144:             } else {
 9145:                 $datatable .= '<input type="text" name="'.$item.'" value="'.$defaults{$item}.'" />';
 9146:             }
 9147:             $datatable .= '</td></tr>';
 9148:             $rownum ++;
 9149:         }
 9150:     } elsif ($position eq 'middle') {
 9151:         my %defaults;
 9152:         if (ref($settings) eq 'HASH') {
 9153:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9154:                 my $maxnum = @{$settings->{'inststatusorder'}};
 9155:                 for (my $i=0; $i<$maxnum; $i++) {
 9156:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 9157:                     my $item = $settings->{'inststatusorder'}->[$i];
 9158:                     my $title = $settings->{'inststatustypes'}->{$item};
 9159:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 9160:                     $datatable .= '<tr'.$css_class.'>'.
 9161:                                   '<td><span class="LC_nobreak">'.
 9162:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 9163:                     for (my $k=0; $k<=$maxnum; $k++) {
 9164:                         my $vpos = $k+1;
 9165:                         my $selstr;
 9166:                         if ($k == $i) {
 9167:                             $selstr = ' selected="selected" ';
 9168:                         }
 9169:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9170:                     }
 9171:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 9172:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 9173:                                   &mt('delete').'</span></td>'.
 9174:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 9175:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 9176:                                   '</span></td></tr>';
 9177:                 }
 9178:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 9179:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 9180:                 $datatable .= '<tr '.$css_class.'>'.
 9181:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 9182:                 for (my $k=0; $k<=$maxnum; $k++) {
 9183:                     my $vpos = $k+1;
 9184:                     my $selstr;
 9185:                     if ($k == $maxnum) {
 9186:                         $selstr = ' selected="selected" ';
 9187:                     }
 9188:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9189:                 }
 9190:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 9191:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 9192:                               '&nbsp;'.&mt('(new)').
 9193:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 9194:                               &mt('Name displayed').':'.
 9195:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 9196:                               '</tr>'."\n";
 9197:                 $rownum ++;
 9198:             }
 9199:         }
 9200:     } else {
 9201:         my ($unamemaprules,$ruleorder) =
 9202:             &Apache::lonnet::inst_userrules($dom,'unamemap');
 9203:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 9204:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9205:             my $numinrow = 2;
 9206:             $datatable .= '<tr'.$css_class.'><td>'.&mt('Available conversions').'</td><td><table>'.
 9207:                           &user_formats_row('unamemap',$settings,$unamemaprules,
 9208:                                             $ruleorder,$numinrow).
 9209:                           '</table></td></tr>';
 9210:         }
 9211:         if ($datatable eq '') {
 9212:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 9213:                           &mt('No rules set for domain in customized localenroll.pm').
 9214:                           '</td></tr>';
 9215:         }
 9216:     }
 9217:     $$rowtotal += $rownum;
 9218:     return $datatable;
 9219: }
 9220: 
 9221: sub get_languages_hash {
 9222:     my %langchoices;
 9223:     foreach my $id (&Apache::loncommon::languageids()) {
 9224:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 9225:         if ($code ne '') {
 9226:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 9227:         }
 9228:     }
 9229:     return %langchoices;
 9230: }
 9231: 
 9232: sub defaults_titles {
 9233:     my ($dom) = @_;
 9234:     my %titles = &Apache::lonlocal::texthash (
 9235:                    'auth_def'      => 'Default authentication type',
 9236:                    'auth_arg_def'  => 'Default authentication argument',
 9237:                    'lang_def'      => 'Default language',
 9238:                    'timezone_def'  => 'Default timezone',
 9239:                    'datelocale_def' => 'Default locale for dates',
 9240:                    'portal_def'     => 'Portal/Default URL',
 9241:                    'email'          => 'Email links use portal URL',
 9242:                    'web'            => 'Public web links use portal URL',
 9243:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 9244:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 9245:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 9246:                  );
 9247:     if ($dom) {
 9248:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 9249:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 9250:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 9251:         $protocol = 'http' if ($protocol ne 'https');
 9252:         if ($uint_dom) {
 9253:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 9254:                                          $uint_dom);
 9255:         }
 9256:     }
 9257:     return (\%titles);
 9258: }
 9259: 
 9260: sub print_scantron {
 9261:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 9262:     if ($position eq 'top') {
 9263:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 9264:     } else {
 9265:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 9266:     }
 9267: }
 9268: 
 9269: sub scantron_javascript {
 9270:     return <<"ENDSCRIPT";
 9271: 
 9272: <script type="text/javascript">
 9273: // <![CDATA[
 9274: 
 9275: function toggleScantron(form) {
 9276:     var csvfieldset = new Array();
 9277:     if (document.getElementById('scantroncsv_cols')) {
 9278:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 9279:     }
 9280:     if (document.getElementById('scantroncsv_options')) {
 9281:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 9282:     }
 9283:     if (csvfieldset.length) {
 9284:         if (document.getElementById('scantronconfcsv')) {
 9285:             var scantroncsv = document.getElementById('scantronconfcsv');
 9286:             if (scantroncsv.checked) {
 9287:                 for (var i=0; i<csvfieldset.length; i++) {
 9288:                     csvfieldset[i].style.display = 'block';
 9289:                 }
 9290:             } else {
 9291:                 for (var i=0; i<csvfieldset.length; i++) {
 9292:                     csvfieldset[i].style.display = 'none';
 9293:                 }
 9294:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 9295:                 if (csvselects.length) {
 9296:                     for (var j=0; j<csvselects.length; j++) {
 9297:                         csvselects[j].selectedIndex = 0;
 9298:                     }
 9299:                 }
 9300:             }
 9301:         }
 9302:     }
 9303:     return;
 9304: }
 9305: // ]]>
 9306: </script>
 9307: 
 9308: ENDSCRIPT
 9309: 
 9310: }
 9311: 
 9312: sub print_scantronformat {
 9313:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 9314:     my $itemcount = 1;
 9315:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 9316:         %confhash);
 9317:     my $switchserver = &check_switchserver($dom,$confname);
 9318:     my %lt = &Apache::lonlocal::texthash (
 9319:                 default => 'Default bubblesheet format file error',
 9320:                 custom  => 'Custom bubblesheet format file error',
 9321:              );
 9322:     my %scantronfiles = (
 9323:         default => 'default.tab',
 9324:         custom => 'custom.tab',
 9325:     );
 9326:     foreach my $key (keys(%scantronfiles)) {
 9327:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 9328:                               .$scantronfiles{$key};
 9329:     }
 9330:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 9331:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 9332:         if (!$switchserver) {
 9333:             my $servadm = $r->dir_config('lonAdmEMail');
 9334:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 9335:             if ($configuserok eq 'ok') {
 9336:                 if ($author_ok eq 'ok') {
 9337:                     my %legacyfile = (
 9338:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 9339:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 9340:                     );
 9341:                     my %md5chk;
 9342:                     foreach my $type (keys(%legacyfile)) {
 9343:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 9344:                         chomp($md5chk{$type});
 9345:                     }
 9346:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 9347:                         foreach my $type (keys(%legacyfile)) {
 9348:                             ($scantronurls{$type},my $error) =
 9349:                                 &legacy_scantronformat($r,$dom,$confname,
 9350:                                                  $type,$legacyfile{$type},
 9351:                                                  $scantronurls{$type},
 9352:                                                  $scantronfiles{$type});
 9353:                             if ($error ne '') {
 9354:                                 $error{$type} = $error;
 9355:                             }
 9356:                         }
 9357:                         if (keys(%error) == 0) {
 9358:                             $is_custom = 1;
 9359:                             $confhash{'scantron'}{'scantronformat'} =
 9360:                                 $scantronurls{'custom'};
 9361:                             my $putresult =
 9362:                                 &Apache::lonnet::put_dom('configuration',
 9363:                                                          \%confhash,$dom);
 9364:                             if ($putresult ne 'ok') {
 9365:                                 $error{'custom'} =
 9366:                                     '<span class="LC_error">'.
 9367:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 9368:                             }
 9369:                         }
 9370:                     } else {
 9371:                         ($scantronurls{'default'},my $error) =
 9372:                             &legacy_scantronformat($r,$dom,$confname,
 9373:                                           'default',$legacyfile{'default'},
 9374:                                           $scantronurls{'default'},
 9375:                                           $scantronfiles{'default'});
 9376:                         if ($error eq '') {
 9377:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 9378:                             my $putresult =
 9379:                                 &Apache::lonnet::put_dom('configuration',
 9380:                                                          \%confhash,$dom);
 9381:                             if ($putresult ne 'ok') {
 9382:                                 $error{'default'} =
 9383:                                     '<span class="LC_error">'.
 9384:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 9385:                             }
 9386:                         } else {
 9387:                             $error{'default'} = $error;
 9388:                         }
 9389:                     }
 9390:                 }
 9391:             }
 9392:         } else {
 9393:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 9394:         }
 9395:     }
 9396:     if (ref($settings) eq 'HASH') {
 9397:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 9398:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 9399:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 9400:                 $scantronurl = '';
 9401:             } else {
 9402:                 $scantronurl = $settings->{'scantronformat'};
 9403:             }
 9404:             $is_custom = 1;
 9405:         } else {
 9406:             $scantronurl = $scantronurls{'default'};
 9407:         }
 9408:     } else {
 9409:         if ($is_custom) {
 9410:             $scantronurl = $scantronurls{'custom'};
 9411:         } else {
 9412:             $scantronurl = $scantronurls{'default'};
 9413:         }
 9414:     }
 9415:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9416:     $datatable .= '<tr'.$css_class.'>';
 9417:     if (!$is_custom) {
 9418:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 9419:                       '<span class="LC_nobreak">';
 9420:         if ($scantronurl) {
 9421:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 9422:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 9423:         } else {
 9424:             $datatable = &mt('File unavailable for display');
 9425:         }
 9426:         $datatable .= '</span></td>';
 9427:         if (keys(%error) == 0) { 
 9428:             $datatable .= '<td valign="bottom">';
 9429:             if (!$switchserver) {
 9430:                 $datatable .= &mt('Upload:').'<br />';
 9431:             }
 9432:         } else {
 9433:             my $errorstr;
 9434:             foreach my $key (sort(keys(%error))) {
 9435:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 9436:             }
 9437:             $datatable .= '<td>'.$errorstr;
 9438:         }
 9439:     } else {
 9440:         if (keys(%error) > 0) {
 9441:             my $errorstr;
 9442:             foreach my $key (sort(keys(%error))) {
 9443:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 9444:             } 
 9445:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 9446:         } elsif ($scantronurl) {
 9447:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 9448:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 9449:             $datatable .= '<td><span class="LC_nobreak">'.
 9450:                           $link.
 9451:                           '<label><input type="checkbox" name="scantronformat_del"'.
 9452:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 9453:                           '<td><span class="LC_nobreak">&nbsp;'.
 9454:                           &mt('Replace:').'</span><br />';
 9455:         }
 9456:     }
 9457:     if (keys(%error) == 0) {
 9458:         if ($switchserver) {
 9459:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 9460:         } else {
 9461:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 9462:                          '<input type="file" name="scantronformat" /></span>';
 9463:         }
 9464:     }
 9465:     $datatable .= '</td></tr>';
 9466:     $$rowtotal ++;
 9467:     return $datatable;
 9468: }
 9469: 
 9470: sub legacy_scantronformat {
 9471:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 9472:     my ($url,$error);
 9473:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 9474:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 9475:         my $modified = [];
 9476:         (my $result,$url) =
 9477:             &Apache::lonconfigsettings::publishlogo($r,'copy',$legacyfile,$dom,$confname,
 9478:                                                     'scantron','','',$newfile,$modified);
 9479:         if ($result eq 'ok') {
 9480:             &update_modify_urls($r,$modified);
 9481:         } else {
 9482:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 9483:         }
 9484:     }
 9485:     return ($url,$error);
 9486: }
 9487: 
 9488: sub print_scantronconfig {
 9489:     my ($dom,$settings,$rowtotal) = @_;
 9490:     my $itemcount = 2;
 9491:     my $is_checked = ' checked="checked"';
 9492:     my %optionson = (
 9493:                      hdr => ' checked="checked"',
 9494:                      pad => ' checked="checked"',
 9495:                      rem => ' checked="checked"',
 9496:                     );
 9497:     my %optionsoff = (
 9498:                       hdr => '',
 9499:                       pad => '',
 9500:                       rem => '',
 9501:                      );
 9502:     my $currcsvsty = 'none';
 9503:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 9504:     my @fields = &scantroncsv_fields();
 9505:     my %titles = &scantronconfig_titles();
 9506:     if (ref($settings) eq 'HASH') {
 9507:         if (ref($settings->{config}) eq 'HASH') {
 9508:             if ($settings->{config}->{dat}) {
 9509:                 $checked{'dat'} = $is_checked;
 9510:             }
 9511:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 9512:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 9513:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 9514:                     if (keys(%csvfields) > 0) {
 9515:                         $checked{'csv'} = $is_checked;
 9516:                         $currcsvsty = 'block';
 9517:                     }
 9518:                 }
 9519:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 9520:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 9521:                     foreach my $option (keys(%optionson)) {
 9522:                         unless ($csvoptions{$option}) {
 9523:                             $optionsoff{$option} = $optionson{$option};
 9524:                             $optionson{$option} = '';
 9525:                         }
 9526:                     }
 9527:                 }
 9528:             }
 9529:         } else {
 9530:             $checked{'dat'} = $is_checked;
 9531:         }
 9532:     } else {
 9533:         $checked{'dat'} = $is_checked;
 9534:     }
 9535:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 9536:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 9537:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 9538:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 9539:     foreach my $item ('dat','csv') {
 9540:         my $id;
 9541:         if ($item eq 'csv') {
 9542:             $id = 'id="scantronconfcsv" ';
 9543:         }
 9544:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 9545:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 9546:         if ($item eq 'csv') {
 9547:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 9548:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 9549:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 9550:             foreach my $col (@fields) {
 9551:                 my $selnone;
 9552:                 if ($csvfields{$col} eq '') {
 9553:                     $selnone = ' selected="selected"';
 9554:                 }
 9555:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 9556:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 9557:                               '<option value=""'.$selnone.'></option>';
 9558:                 for (my $i=0; $i<20; $i++) {
 9559:                     my $shown = $i+1;
 9560:                     my $sel;
 9561:                     unless ($selnone) {
 9562:                         if (exists($csvfields{$col})) {
 9563:                             if ($csvfields{$col} == $i) {
 9564:                                 $sel = ' selected="selected"';
 9565:                             }
 9566:                         }
 9567:                     }
 9568:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
 9569:                 }
 9570:                 $datatable .= '</select></td></tr>';
 9571:            }
 9572:            $datatable .= '</table></fieldset>'.
 9573:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
 9574:                          '<legend>'.&mt('CSV Options').'</legend>';
 9575:            foreach my $option ('hdr','pad','rem') {
 9576:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
 9577:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
 9578:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
 9579:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
 9580:            }
 9581:            $datatable .= '</fieldset>';
 9582:            $itemcount ++;
 9583:         }
 9584:     }
 9585:     $datatable .= '</td></tr>';
 9586:     $$rowtotal ++;
 9587:     return $datatable;
 9588: }
 9589: 
 9590: sub scantronconfig_titles {
 9591:     return &Apache::lonlocal::texthash(
 9592:                                           dat => 'Standard format (.dat)',
 9593:                                           csv => 'Comma separated values (.csv)',
 9594:                                           hdr => 'Remove first line in file (contains column titles)',
 9595:                                           pad => 'Prepend 0s to PaperID',
 9596:                                           rem => 'Remove leading spaces (except Question Response columns)',
 9597:                                           CODE => 'CODE',
 9598:                                           ID   => 'Student ID',
 9599:                                           PaperID => 'Paper ID',
 9600:                                           FirstName => 'First Name',
 9601:                                           LastName => 'Last Name',
 9602:                                           FirstQuestion => 'First Question Response',
 9603:                                           Section => 'Section',
 9604:     );
 9605: }
 9606: 
 9607: sub scantroncsv_fields {
 9608:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
 9609: }
 9610: 
 9611: sub print_coursecategories {
 9612:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 9613:     my $datatable;
 9614:     if ($position eq 'top') {
 9615:         my (%checked);
 9616:         my @catitems = ('unauth','auth');
 9617:         my @cattypes = ('std','domonly','codesrch','none');
 9618:         $checked{'unauth'} = 'std';
 9619:         $checked{'auth'} = 'std';
 9620:         if (ref($settings) eq 'HASH') {
 9621:             foreach my $type (@cattypes) {
 9622:                 if ($type eq $settings->{'unauth'}) {
 9623:                     $checked{'unauth'} = $type;
 9624:                 }
 9625:                 if ($type eq $settings->{'auth'}) {
 9626:                     $checked{'auth'} = $type;
 9627:                 }
 9628:             }
 9629:         }
 9630:         my %lt = &Apache::lonlocal::texthash (
 9631:                                                unauth   => 'Catalog type for unauthenticated users',
 9632:                                                auth     => 'Catalog type for authenticated users',
 9633:                                                none     => 'No catalog',
 9634:                                                std      => 'Standard catalog',
 9635:                                                domonly  => 'Domain-only catalog',
 9636:                                                codesrch => "Code search form",
 9637:                                              );
 9638:        my $itemcount = 0;
 9639:        foreach my $item (@catitems) {
 9640:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 9641:            $datatable .= '<tr '.$css_class.'>'.
 9642:                          '<td>'.$lt{$item}.'</td>'.
 9643:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 9644:            foreach my $type (@cattypes) {
 9645:                my $ischecked;
 9646:                if ($checked{$item} eq $type) {
 9647:                    $ischecked=' checked="checked"';
 9648:                }
 9649:                $datatable .= '<label>'.
 9650:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 9651:                              ' />'.$lt{$type}.'</label>&nbsp;';
 9652:            }
 9653:            $datatable .= '</span></td></tr>';
 9654:            $itemcount ++;
 9655:         }
 9656:         $$rowtotal += $itemcount;
 9657:     } elsif ($position eq 'middle') {
 9658:         my $toggle_cats_crs = ' ';
 9659:         my $toggle_cats_dom = ' checked="checked" ';
 9660:         my $can_cat_crs = ' ';
 9661:         my $can_cat_dom = ' checked="checked" ';
 9662:         my $toggle_catscomm_comm = ' ';
 9663:         my $toggle_catscomm_dom = ' checked="checked" ';
 9664:         my $can_catcomm_comm = ' ';
 9665:         my $can_catcomm_dom = ' checked="checked" ';
 9666: 
 9667:         if (ref($settings) eq 'HASH') {
 9668:             if ($settings->{'togglecats'} eq 'crs') {
 9669:                 $toggle_cats_crs = $toggle_cats_dom;
 9670:                 $toggle_cats_dom = ' ';
 9671:             }
 9672:             if ($settings->{'categorize'} eq 'crs') {
 9673:                 $can_cat_crs = $can_cat_dom;
 9674:                 $can_cat_dom = ' ';
 9675:             }
 9676:             if ($settings->{'togglecatscomm'} eq 'comm') {
 9677:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 9678:                 $toggle_catscomm_dom = ' ';
 9679:             }
 9680:             if ($settings->{'categorizecomm'} eq 'comm') {
 9681:                 $can_catcomm_comm = $can_catcomm_dom;
 9682:                 $can_catcomm_dom = ' ';
 9683:             }
 9684:         }
 9685:         my %title = &Apache::lonlocal::texthash (
 9686:                      togglecats     => 'Show/Hide a course in catalog',
 9687:                      togglecatscomm => 'Show/Hide a community in catalog',
 9688:                      categorize     => 'Assign a category to a course',
 9689:                      categorizecomm => 'Assign a category to a community',
 9690:                     );
 9691:         my %level = &Apache::lonlocal::texthash (
 9692:                      dom  => 'Set in Domain',
 9693:                      crs  => 'Set in Course',
 9694:                      comm => 'Set in Community',
 9695:                     );
 9696:         $datatable = '<tr class="LC_odd_row">'.
 9697:                   '<td>'.$title{'togglecats'}.'</td>'.
 9698:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9699:                   '<input type="radio" name="togglecats"'.
 9700:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9701:                   '<label><input type="radio" name="togglecats"'.
 9702:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 9703:                   '</tr><tr>'.
 9704:                   '<td>'.$title{'categorize'}.'</td>'.
 9705:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9706:                   '<label><input type="radio" name="categorize"'.
 9707:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9708:                   '<label><input type="radio" name="categorize"'.
 9709:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 9710:                   '</tr><tr class="LC_odd_row">'.
 9711:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 9712:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9713:                   '<input type="radio" name="togglecatscomm"'.
 9714:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9715:                   '<label><input type="radio" name="togglecatscomm"'.
 9716:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 9717:                   '</tr><tr>'.
 9718:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 9719:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9720:                   '<label><input type="radio" name="categorizecomm"'.
 9721:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9722:                   '<label><input type="radio" name="categorizecomm"'.
 9723:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 9724:                   '</tr>';
 9725:         $$rowtotal += 4;
 9726:     } else {
 9727:         my $css_class;
 9728:         my $itemcount = 1;
 9729:         my $cathash; 
 9730:         if (ref($settings) eq 'HASH') {
 9731:             $cathash = $settings->{'cats'};
 9732:         }
 9733:         if (ref($cathash) eq 'HASH') {
 9734:             my (@cats,@trails,%allitems,%idx,@jsarray);
 9735:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 9736:                                                    \%allitems,\%idx,\@jsarray);
 9737:             my $maxdepth = scalar(@cats);
 9738:             my $colattrib = '';
 9739:             if ($maxdepth > 2) {
 9740:                 $colattrib = ' colspan="2" ';
 9741:             }
 9742:             my @path;
 9743:             if (@cats > 0) {
 9744:                 if (ref($cats[0]) eq 'ARRAY') {
 9745:                     my $numtop = @{$cats[0]};
 9746:                     my $maxnum = $numtop;
 9747:                     my %default_names = (
 9748:                           instcode    => &mt('Official courses'),
 9749:                           communities => &mt('Communities'),
 9750:                     );
 9751: 
 9752:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 9753:                         ($cathash->{'instcode::0'} eq '') ||
 9754:                         (!grep(/^communities$/,@{$cats[0]})) || 
 9755:                         ($cathash->{'communities::0'} eq '')) {
 9756:                         $maxnum ++;
 9757:                     }
 9758:                     my $lastidx;
 9759:                     for (my $i=0; $i<$numtop; $i++) {
 9760:                         my $parent = $cats[0][$i];
 9761:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9762:                         my $item = &escape($parent).'::0';
 9763:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 9764:                         $lastidx = $idx{$item};
 9765:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9766:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 9767:                         for (my $k=0; $k<=$maxnum; $k++) {
 9768:                             my $vpos = $k+1;
 9769:                             my $selstr;
 9770:                             if ($k == $i) {
 9771:                                 $selstr = ' selected="selected" ';
 9772:                             }
 9773:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9774:                         }
 9775:                         $datatable .= '</select></span></td><td>';
 9776:                         if ($parent eq 'instcode' || $parent eq 'communities') {
 9777:                             $datatable .=  '<span class="LC_nobreak">'
 9778:                                            .$default_names{$parent}.'</span>';
 9779:                             if ($parent eq 'instcode') {
 9780:                                 $datatable .= '<br /><span class="LC_nobreak">('
 9781:                                               .&mt('with institutional codes')
 9782:                                               .')</span></td><td'.$colattrib.'>';
 9783:                             } else {
 9784:                                 $datatable .= '<table><tr><td>';
 9785:                             }
 9786:                             $datatable .= '<span class="LC_nobreak">'
 9787:                                           .'<label><input type="radio" name="'
 9788:                                           .$parent.'" value="1" checked="checked" />'
 9789:                                           .&mt('Display').'</label>';
 9790:                             if ($parent eq 'instcode') {
 9791:                                 $datatable .= '&nbsp;';
 9792:                             } else {
 9793:                                 $datatable .= '</span></td></tr><tr><td>'
 9794:                                               .'<span class="LC_nobreak">';
 9795:                             }
 9796:                             $datatable .= '<label><input type="radio" name="'
 9797:                                           .$parent.'" value="0" />'
 9798:                                           .&mt('Do not display').'</label></span>';
 9799:                             if ($parent eq 'communities') {
 9800:                                 $datatable .= '</td></tr></table>';
 9801:                             }
 9802:                             $datatable .= '</td>';
 9803:                         } else {
 9804:                             $datatable .= $parent
 9805:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 9806:                                           .'<input type="checkbox" name="deletecategory" '
 9807:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 9808:                         }
 9809:                         my $depth = 1;
 9810:                         push(@path,$parent);
 9811:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 9812:                         pop(@path);
 9813:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9814:                         $itemcount ++;
 9815:                     }
 9816:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9817:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 9818:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 9819:                     for (my $k=0; $k<=$maxnum; $k++) {
 9820:                         my $vpos = $k+1;
 9821:                         my $selstr;
 9822:                         if ($k == $numtop) {
 9823:                             $selstr = ' selected="selected" ';
 9824:                         }
 9825:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9826:                     }
 9827:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 9828:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 9829:                                   .'</tr>'."\n";
 9830:                     $itemcount ++;
 9831:                     foreach my $default ('instcode','communities') {
 9832:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 9833:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9834:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 9835:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 9836:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 9837:                             for (my $k=0; $k<=$maxnum; $k++) {
 9838:                                 my $vpos = $k+1;
 9839:                                 my $selstr;
 9840:                                 if ($k == $maxnum) {
 9841:                                     $selstr = ' selected="selected" ';
 9842:                                 }
 9843:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9844:                             }
 9845:                             $datatable .= '</select></span></td>'.
 9846:                                           '<td><span class="LC_nobreak">'.
 9847:                                           $default_names{$default}.'</span>';
 9848:                             if ($default eq 'instcode') {
 9849:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 9850:                                               .&mt('with institutional codes').')</span>';
 9851:                             }
 9852:                             $datatable .= '</td>'
 9853:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 9854:                                           .&mt('Display').'</label>&nbsp;'
 9855:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 9856:                                           .&mt('Do not display').'</label></span></td></tr>';
 9857:                         }
 9858:                     }
 9859:                 }
 9860:             } else {
 9861:                 $datatable .= &initialize_categories($itemcount);
 9862:             }
 9863:         } else {
 9864:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 9865:                           .&initialize_categories($itemcount);
 9866:         }
 9867:         $$rowtotal += $itemcount;
 9868:     }
 9869:     return $datatable;
 9870: }
 9871: 
 9872: sub print_serverstatuses {
 9873:     my ($dom,$settings,$rowtotal) = @_;
 9874:     my $datatable;
 9875:     my @pages = &serverstatus_pages();
 9876:     my (%namedaccess,%machineaccess);
 9877:     foreach my $type (@pages) {
 9878:         $namedaccess{$type} = '';
 9879:         $machineaccess{$type}= '';
 9880:     }
 9881:     if (ref($settings) eq 'HASH') {
 9882:         foreach my $type (@pages) {
 9883:             if (exists($settings->{$type})) {
 9884:                 if (ref($settings->{$type}) eq 'HASH') {
 9885:                     foreach my $key (keys(%{$settings->{$type}})) {
 9886:                         if ($key eq 'namedusers') {
 9887:                             $namedaccess{$type} = $settings->{$type}->{$key};
 9888:                         } elsif ($key eq 'machines') {
 9889:                             $machineaccess{$type} = $settings->{$type}->{$key};
 9890:                         }
 9891:                     }
 9892:                 }
 9893:             }
 9894:         }
 9895:     }
 9896:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 9897:     my $rownum = 0;
 9898:     my $css_class;
 9899:     foreach my $type (@pages) {
 9900:         $rownum ++;
 9901:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 9902:         $datatable .= '<tr'.$css_class.'>'.
 9903:                       '<td><span class="LC_nobreak">'.
 9904:                       $titles->{$type}.'</span></td>'.
 9905:                       '<td class="LC_left_item">'.
 9906:                       '<input type="text" name="'.$type.'_namedusers" '.
 9907:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 9908:                       '<td class="LC_right_item">'.
 9909:                       '<span class="LC_nobreak">'.
 9910:                       '<input type="text" name="'.$type.'_machines" '.
 9911:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 9912:                       '</span></td></tr>'."\n";
 9913:     }
 9914:     $$rowtotal += $rownum;
 9915:     return $datatable;
 9916: }
 9917: 
 9918: sub serverstatus_pages {
 9919:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 9920:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 9921:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 9922:             'uniquecodes','diskusage','coursecatalog');
 9923: }
 9924: 
 9925: sub defaults_javascript {
 9926:     my ($settings) = @_;
 9927:     return unless (ref($settings) eq 'HASH');
 9928:     my $portal_js = <<"ENDPORTAL";
 9929: 
 9930: function portalExtras(caller) {
 9931:     var x = caller.value;
 9932:     var y = new Array('email','web');
 9933:     for (var i=0; i<y.length; i++) {
 9934:         if (document.getElementById('portal_def_'+y[i]+'_div')) {
 9935:             var z = document.getElementById('portal_def_'+y[i]+'_div');
 9936:             if (x.length > 0) {
 9937:                 z.style.display = 'block';
 9938:             } else {
 9939:                 z.style.display = 'none';
 9940:             }
 9941:         }
 9942:     }
 9943: }
 9944: ENDPORTAL
 9945:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9946:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 9947:         if ($maxnum eq '') {
 9948:             $maxnum = 0;
 9949:         }
 9950:         $maxnum ++;
 9951:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 9952:         return <<"ENDSCRIPT";
 9953: <script type="text/javascript">
 9954: // <![CDATA[
 9955: function reorderTypes(form,caller) {
 9956:     var changedVal;
 9957: $jstext 
 9958:     var newpos = 'addinststatus_pos';
 9959:     var current = new Array;
 9960:     var maxh = $maxnum;
 9961:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 9962:     var oldVal;
 9963:     if (caller == newpos) {
 9964:         changedVal = newitemVal;
 9965:     } else {
 9966:         var curritem = 'inststatus_pos_'+caller;
 9967:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 9968:         current[newitemVal] = newpos;
 9969:     }
 9970:     for (var i=0; i<inststatuses.length; i++) {
 9971:         if (inststatuses[i] != caller) {
 9972:             var elementName = 'inststatus_pos_'+inststatuses[i];
 9973:             if (form.elements[elementName]) {
 9974:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 9975:                 current[currVal] = elementName;
 9976:             }
 9977:         }
 9978:     }
 9979:     for (var j=0; j<maxh; j++) {
 9980:         if (current[j] == undefined) {
 9981:             oldVal = j;
 9982:         }
 9983:     }
 9984:     if (oldVal < changedVal) {
 9985:         for (var k=oldVal+1; k<=changedVal ; k++) {
 9986:            var elementName = current[k];
 9987:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 9988:         }
 9989:     } else {
 9990:         for (var k=changedVal; k<oldVal; k++) {
 9991:             var elementName = current[k];
 9992:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 9993:         }
 9994:     }
 9995:     return;
 9996: }
 9997: 
 9998: $portal_js
 9999: 
10000: // ]]>
10001: </script>
10002: 
10003: ENDSCRIPT
10004:     } else {
10005: return <<"ENDSCRIPT";
10006: <script type="text/javascript">
10007: // <![CDATA[
10008: $portal_js
10009: // ]]>
10010: </script>
10011: 
10012: ENDSCRIPT
10013:     }
10014:     return;
10015: }
10016: 
10017: sub passwords_javascript {
10018:     my ($prefix) = @_;
10019:     my %intalert;
10020:     if ($prefix eq 'passwords') {
10021:         %intalert = &Apache::lonlocal::texthash (
10022:             authcheck => 'Warning: disallowing login for an authenticated user if the stored cost is less than the default will require a password reset by/for the user.',
10023:             authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
10024:             passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
10025:             passmax => 'Warning: maximum password length must be a positive integer (or blank).',
10026:             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
10027:         );
10028:     } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
10029:         %intalert = &Apache::lonlocal::texthash (
10030:             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
10031:             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
10032:         );
10033:     }
10034:     &js_escape(\%intalert);
10035:     my $defmin = $Apache::lonnet::passwdmin;
10036:     my $intauthjs;
10037:     if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
10038: 
10039: function warnIntAuth(field) {
10040:     if (field.name == 'intauth_check') {
10041:         if (field.value == '2') {
10042:             alert('$intalert{authcheck}');
10043:         }
10044:     }
10045:     if (field.name == 'intauth_cost') {
10046:         field.value.replace(/\s/g,'');
10047:         if (field.value != '') {
10048:             var regexdigit=/^\\d+\$/;
10049:             if (!regexdigit.test(field.value)) {
10050:                 alert('$intalert{authcost}');
10051:             }
10052:         }
10053:     }
10054:     return;
10055: }
10056: 
10057: ENDSCRIPT
10058: 
10059:      }
10060: 
10061:      $intauthjs .= <<"ENDSCRIPT";
10062: 
10063: function warnInt$prefix(field) {
10064:     field.value.replace(/^\s+/,'');
10065:     field.value.replace(/\s+\$/,'');
10066:     var regexdigit=/^\\d+\$/;
10067:     if (field.name == '${prefix}_min') {
10068:         if (field.value == '') {
10069:             alert('$intalert{passmin}');
10070:             field.value = '$defmin';
10071:         } else {
10072:             if (!regexdigit.test(field.value)) {
10073:                 alert('$intalert{passmin}');
10074:                 field.value = '$defmin';
10075:             }
10076:             var minval = parseInt(field.value,10);
10077:             if (minval < $defmin) {
10078:                 alert('$intalert{passmin}');
10079:                 field.value = '$defmin';
10080:             }
10081:         }
10082:     } else {
10083:         if (field.value == '0') {
10084:             field.value = '';
10085:         }
10086:         if (field.value != '') {
10087:             if (!regexdigit.test(field.value)) {
10088:                 if (field.name == '${prefix}_max') {
10089:                     alert('$intalert{passmax}');
10090:                 } else {
10091:                     if (field.name == '${prefix}_numsaved') {
10092:                         alert('$intalert{passnum}');
10093:                     }
10094:                 }
10095:                 field.value = '';
10096:             }
10097:         }
10098:     }
10099:     return;
10100: }
10101: 
10102: ENDSCRIPT
10103:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
10104: }
10105: 
10106: sub coursecategories_javascript {
10107:     my ($settings) = @_;
10108:     my ($output,$jstext,$cathash);
10109:     if (ref($settings) eq 'HASH') {
10110:         $cathash = $settings->{'cats'};
10111:     }
10112:     if (ref($cathash) eq 'HASH') {
10113:         my (@cats,@jsarray,%idx);
10114:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
10115:         if (@jsarray > 0) {
10116:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
10117:             for (my $i=0; $i<@jsarray; $i++) {
10118:                 if (ref($jsarray[$i]) eq 'ARRAY') {
10119:                     my $catstr = join('","',@{$jsarray[$i]});
10120:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
10121:                 }
10122:             }
10123:         }
10124:     } else {
10125:         $jstext  = '    var categories = Array(1);'."\n".
10126:                    '    categories[0] = Array("instcode_pos");'."\n"; 
10127:     }
10128:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
10129:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
10130:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
10131:     &js_escape(\$instcode_reserved);
10132:     &js_escape(\$communities_reserved);
10133:     &js_escape(\$choose_again);
10134:     $output = <<"ENDSCRIPT";
10135: <script type="text/javascript">
10136: // <![CDATA[
10137: function reorderCats(form,parent,item,idx) {
10138:     var changedVal;
10139: $jstext
10140:     var newpos = 'addcategory_pos';
10141:     if (parent == '') {
10142:         var has_instcode = 0;
10143:         var maxtop = categories[idx].length;
10144:         for (var j=0; j<maxtop; j++) {
10145:             if (categories[idx][j] == 'instcode::0') {
10146:                 has_instcode == 1;
10147:             }
10148:         }
10149:         if (has_instcode == 0) {
10150:             categories[idx][maxtop] = 'instcode_pos';
10151:         }
10152:     } else {
10153:         newpos += '_'+parent;
10154:     }
10155:     var maxh = 1 + categories[idx].length;
10156:     var current = new Array;
10157:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10158:     if (item == newpos) {
10159:         changedVal = newitemVal;
10160:     } else {
10161:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
10162:         current[newitemVal] = newpos;
10163:     }
10164:     for (var i=0; i<categories[idx].length; i++) {
10165:         var elementName = categories[idx][i];
10166:         if (elementName != item) {
10167:             if (form.elements[elementName]) {
10168:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10169:                 current[currVal] = elementName;
10170:             }
10171:         }
10172:     }
10173:     var oldVal;
10174:     for (var j=0; j<maxh; j++) {
10175:         if (current[j] == undefined) {
10176:             oldVal = j;
10177:         }
10178:     }
10179:     if (oldVal < changedVal) {
10180:         for (var k=oldVal+1; k<=changedVal ; k++) {
10181:            var elementName = current[k];
10182:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10183:         }
10184:     } else {
10185:         for (var k=changedVal; k<oldVal; k++) {
10186:             var elementName = current[k];
10187:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10188:         }
10189:     }
10190:     return;
10191: }
10192: 
10193: function categoryCheck(form) {
10194:     if (form.elements['addcategory_name'].value == 'instcode') {
10195:         alert('$instcode_reserved\\n$choose_again');
10196:         return false;
10197:     }
10198:     if (form.elements['addcategory_name'].value == 'communities') {
10199:         alert('$communities_reserved\\n$choose_again');
10200:         return false;
10201:     }
10202:     return true;
10203: }
10204: 
10205: // ]]>
10206: </script>
10207: 
10208: ENDSCRIPT
10209:     return $output;
10210: }
10211: 
10212: sub initialize_categories {
10213:     my ($itemcount) = @_;
10214:     my ($datatable,$css_class,$chgstr);
10215:     my %default_names = &Apache::lonlocal::texthash (
10216:                       instcode    => 'Official courses (with institutional codes)',
10217:                       communities => 'Communities',
10218:                         );
10219:     my $select0 = ' selected="selected"';
10220:     my $select1 = '';
10221:     foreach my $default ('instcode','communities') {
10222:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10223:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
10224:         if ($default eq 'communities') {
10225:             $select1 = $select0;
10226:             $select0 = '';
10227:         }
10228:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10229:                      .'<select name="'.$default.'_pos">'
10230:                      .'<option value="0"'.$select0.'>1</option>'
10231:                      .'<option value="1"'.$select1.'>2</option>'
10232:                      .'<option value="2">3</option></select>&nbsp;'
10233:                      .$default_names{$default}
10234:                      .'</span></td><td><span class="LC_nobreak">'
10235:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
10236:                      .&mt('Display').'</label>&nbsp;<label>'
10237:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
10238:                  .'</label></span></td></tr>';
10239:         $itemcount ++;
10240:     }
10241:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10242:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
10243:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10244:                   .'<select name="addcategory_pos"'.$chgstr.'>'
10245:                   .'<option value="0">1</option>'
10246:                   .'<option value="1">2</option>'
10247:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
10248:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
10249:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
10250:                   .'</td></tr>';
10251:     return $datatable;
10252: }
10253: 
10254: sub build_category_rows {
10255:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
10256:     my ($text,$name,$item,$chgstr);
10257:     if (ref($cats) eq 'ARRAY') {
10258:         my $maxdepth = scalar(@{$cats});
10259:         if (ref($cats->[$depth]) eq 'HASH') {
10260:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10261:                 my $numchildren = @{$cats->[$depth]{$parent}};
10262:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10263:                 $text .= '<td><table class="LC_data_table">';
10264:                 my ($idxnum,$parent_name,$parent_item);
10265:                 my $higher = $depth - 1;
10266:                 if ($higher == 0) {
10267:                     $parent_name = &escape($parent).'::'.$higher;
10268:                 } else {
10269:                     if (ref($path) eq 'ARRAY') {
10270:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
10271:                     }
10272:                 }
10273:                 $parent_item = 'addcategory_pos_'.$parent_name;
10274:                 for (my $j=0; $j<=$numchildren; $j++) {
10275:                     if ($j < $numchildren) {
10276:                         $name = $cats->[$depth]{$parent}[$j];
10277:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
10278:                         $idxnum = $idx->{$item};
10279:                     } else {
10280:                         $name = $parent_name;
10281:                         $item = $parent_item;
10282:                     }
10283:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
10284:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
10285:                     for (my $i=0; $i<=$numchildren; $i++) {
10286:                         my $vpos = $i+1;
10287:                         my $selstr;
10288:                         if ($j == $i) {
10289:                             $selstr = ' selected="selected" ';
10290:                         }
10291:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
10292:                     }
10293:                     $text .= '</select>&nbsp;';
10294:                     if ($j < $numchildren) {
10295:                         my $deeper = $depth+1;
10296:                         $text .= $name.'&nbsp;'
10297:                                  .'<label><input type="checkbox" name="deletecategory" value="'
10298:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
10299:                         if(ref($path) eq 'ARRAY') {
10300:                             push(@{$path},$name);
10301:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
10302:                             pop(@{$path});
10303:                         }
10304:                     } else {
10305:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
10306:                         if ($j == $numchildren) {
10307:                             $text .= $name;
10308:                         } else {
10309:                             $text .= $item;
10310:                         }
10311:                         $text .= '" value="" />';
10312:                     }
10313:                     $text .= '</td></tr>';
10314:                 }
10315:                 $text .= '</table></td>';
10316:             } else {
10317:                 my $higher = $depth-1;
10318:                 if ($higher == 0) {
10319:                     $name = &escape($parent).'::'.$higher;
10320:                 } else {
10321:                     if (ref($path) eq 'ARRAY') {
10322:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
10323:                     }
10324:                 }
10325:                 my $colspan;
10326:                 if ($parent ne 'instcode') {
10327:                     $colspan = $maxdepth - $depth - 1;
10328:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
10329:                 }
10330:             }
10331:         }
10332:     }
10333:     return $text;
10334: }
10335: 
10336: sub modifiable_userdata_row {
10337:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
10338:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
10339:     my ($role,$rolename,$statustype);
10340:     $role = $item;
10341:     if ($context eq 'cancreate') {
10342:         if ($item =~ /^(emailusername)_(.+)$/) {
10343:             $role = $1;
10344:             $statustype = $2;
10345:             if (ref($usertypes) eq 'HASH') {
10346:                 if ($usertypes->{$statustype}) {
10347:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
10348:                 } else {
10349:                     $rolename = &mt('Data provided by user');
10350:                 }
10351:             }
10352:         }
10353:     } elsif ($context eq 'selfcreate') {
10354:         if (ref($usertypes) eq 'HASH') {
10355:             $rolename = $usertypes->{$role};
10356:         } else {
10357:             $rolename = $role;
10358:         }
10359:     } elsif ($context eq 'lti') {
10360:         $rolename = &mt('Institutional data used (if available)');
10361:     } else {
10362:         if ($role eq 'cr') {
10363:             $rolename = &mt('Custom role');
10364:         } else {
10365:             $rolename = &Apache::lonnet::plaintext($role);
10366:         }
10367:     }
10368:     my (@fields,%fieldtitles);
10369:     if (ref($fieldsref) eq 'ARRAY') {
10370:         @fields = @{$fieldsref};
10371:     } else {
10372:         @fields = ('lastname','firstname','middlename','generation',
10373:                    'permanentemail','id');
10374:     }
10375:     if ((ref($titlesref) eq 'HASH')) {
10376:         %fieldtitles = %{$titlesref};
10377:     } else {
10378:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10379:     }
10380:     my $output;
10381:     my $css_class;
10382:     if ($rowcount%2) {
10383:         $css_class = 'LC_odd_row';
10384:     }
10385:     if ($customcss) {
10386:         $css_class .= " $customcss";
10387:     }
10388:     $css_class =~ s/^\s+//;
10389:     if ($css_class) {
10390:         $css_class = ' class="'.$css_class.'"';
10391:     }
10392:     if ($rowstyle) {
10393:         $css_class .= ' style="'.$rowstyle.'"';
10394:     }
10395:     if ($rowid) {
10396:         $rowid = ' id="'.$rowid.'"';
10397:     }
10398:     $output = '<tr '.$css_class.$rowid.'>'.
10399:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
10400:               '<td class="LC_left_item" colspan="2"><table>';
10401:     my $rem;
10402:     my %checks;
10403:     if (ref($settings) eq 'HASH') {
10404:         my $hashref;
10405:         if ($context eq 'lti') {
10406:             if (ref($settings) eq 'HASH') {
10407:                 $hashref = $settings->{'instdata'};
10408:             }
10409:         } elsif (ref($settings->{$context}) eq 'HASH') {
10410:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
10411:                 $hashref = $settings->{'lti_instdata'};
10412:             }
10413:             if ($role eq 'emailusername') {
10414:                 if ($statustype) {
10415:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
10416:                         $hashref = $settings->{$context}->{$role}->{$statustype};
10417:                     }
10418:                 }
10419:             }
10420:         }
10421:         if (ref($hashref) eq 'HASH') {
10422:             foreach my $field (@fields) {
10423:                 if ($hashref->{$field}) {
10424:                     if ($role eq 'emailusername') {
10425:                         $checks{$field} = $hashref->{$field};
10426:                     } else {
10427:                         $checks{$field} = ' checked="checked" ';
10428:                     }
10429:                 }
10430:             }
10431:         }
10432:     }
10433:     my $total = scalar(@fields);
10434:     for (my $i=0; $i<$total; $i++) {
10435:         $rem = $i%($numinrow);
10436:         if ($rem == 0) {
10437:             if ($i > 0) {
10438:                 $output .= '</tr>';
10439:             }
10440:             $output .= '<tr>';
10441:         }
10442:         my $check = ' ';
10443:         unless ($role eq 'emailusername') {
10444:             if (exists($checks{$fields[$i]})) {
10445:                 $check = $checks{$fields[$i]};
10446:             } elsif ($context ne 'lti') {
10447:                 if ($role eq 'st') {
10448:                     if (ref($settings) ne 'HASH') {
10449:                         $check = ' checked="checked" '; 
10450:                     }
10451:                 }
10452:             }
10453:         }
10454:         $output .= '<td class="LC_left_item">'.
10455:                    '<span class="LC_nobreak">';
10456:         my $prefix = 'canmodify';
10457:         if ($role eq 'emailusername') {
10458:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
10459:                 $checks{$fields[$i]} = 'omit';
10460:             }
10461:             foreach my $option ('required','optional','omit') {
10462:                 my $checked='';
10463:                 if ($checks{$fields[$i]} eq $option) {
10464:                     $checked='checked="checked" ';
10465:                 }
10466:                 $output .= '<label>'.
10467:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
10468:                            &mt($option).'</label>'.('&nbsp;' x2);
10469:             }
10470:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
10471:         } else {
10472:             if ($context eq 'lti') {
10473:                 $prefix = 'lti';
10474:             }
10475:             $output .= '<label>'.
10476:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
10477:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
10478:                        '</label>';
10479:         }
10480:         $output .= '</span></td>';
10481:     }
10482:     $rem = $total%$numinrow;
10483:     my $colsleft;
10484:     if ($rem) {
10485:         $colsleft = $numinrow - $rem;
10486:     }
10487:     if ($colsleft > 1) {
10488:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10489:                    '&nbsp;</td>';
10490:     } elsif ($colsleft == 1) {
10491:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10492:     }
10493:     $output .= '</tr></table></td></tr>';
10494:     return $output;
10495: }
10496: 
10497: sub insttypes_row {
10498:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
10499:         $customcss,$rowstyle) = @_;
10500:     my %lt = &Apache::lonlocal::texthash (
10501:                       cansearch => 'Users allowed to search',
10502:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
10503:                       lockablenames => 'User preference to lock name',
10504:                       selfassign    => 'Self-reportable affiliations',
10505:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
10506:              );
10507:     my $showdom;
10508:     if ($context eq 'cansearch') {
10509:         $showdom = ' ('.$dom.')';
10510:     }
10511:     my $class = 'LC_left_item';
10512:     if ($context eq 'statustocreate') {
10513:         $class = 'LC_right_item';
10514:     }
10515:     my $css_class;
10516:     if ($$rowtotal%2) {
10517:         $css_class = 'LC_odd_row';
10518:     }
10519:     if ($customcss) {
10520:         $css_class .= ' '.$customcss;
10521:     }
10522:     $css_class =~ s/^\s+//;
10523:     if ($css_class) {
10524:         $css_class = ' class="'.$css_class.'"';
10525:     }
10526:     if ($rowstyle) {
10527:         $css_class .= ' style="'.$rowstyle.'"';
10528:     }
10529:     if ($onclick) {
10530:         $onclick = 'onclick="'.$onclick.'" ';
10531:     }
10532:     my $output = '<tr'.$css_class.'>'.
10533:                  '<td>'.$lt{$context}.$showdom.
10534:                  '</td><td class="'.$class.'" colspan="2"><table>';
10535:     my $rem;
10536:     if (ref($types) eq 'ARRAY') {
10537:         for (my $i=0; $i<@{$types}; $i++) {
10538:             if (defined($usertypes->{$types->[$i]})) {
10539:                 my $rem = $i%($numinrow);
10540:                 if ($rem == 0) {
10541:                     if ($i > 0) {
10542:                         $output .= '</tr>';
10543:                     }
10544:                     $output .= '<tr>';
10545:                 }
10546:                 my $check = ' ';
10547:                 if (ref($settings) eq 'HASH') {
10548:                     if (ref($settings->{$context}) eq 'ARRAY') {
10549:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
10550:                             $check = ' checked="checked" ';
10551:                         }
10552:                     } elsif (ref($settings->{$context}) eq 'HASH') {
10553:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
10554:                             $check = ' checked="checked" ';
10555:                         }
10556:                     } elsif ($context eq 'statustocreate') {
10557:                         $check = ' checked="checked" ';
10558:                     }
10559:                 }
10560:                 $output .= '<td class="LC_left_item">'.
10561:                            '<span class="LC_nobreak"><label>'.
10562:                            '<input type="checkbox" name="'.$context.'" '.
10563:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
10564:                            $usertypes->{$types->[$i]}.'</label></span></td>';
10565:             }
10566:         }
10567:         $rem = @{$types}%($numinrow);
10568:     }
10569:     my $colsleft = $numinrow - $rem;
10570:     if ($context eq 'overrides') {
10571:         if ($colsleft > 1) {
10572:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
10573:         } else {
10574:             $output .= '<td class="LC_left_item">';
10575:         }
10576:         $output .= '&nbsp;';
10577:     } else {
10578:         if ($rem == 0) {
10579:             $output .= '<tr>';
10580:         }
10581:         if ($colsleft > 1) {
10582:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
10583:         } else {
10584:             $output .= '<td class="LC_left_item">';
10585:         }
10586:         my $defcheck = ' ';
10587:         if (ref($settings) eq 'HASH') {  
10588:             if (ref($settings->{$context}) eq 'ARRAY') {
10589:                 if (grep(/^default$/,@{$settings->{$context}})) {
10590:                     $defcheck = ' checked="checked" ';
10591:                 }
10592:             } elsif ($context eq 'statustocreate') {
10593:                 $defcheck = ' checked="checked" ';
10594:             }
10595:         }
10596:         $output .= '<span class="LC_nobreak"><label>'.
10597:                    '<input type="checkbox" name="'.$context.'" '.
10598:                    'value="default"'.$defcheck.$onclick.' />'.
10599:                    $othertitle.'</label></span>';
10600:     }
10601:     $output .= '</td></tr></table></td></tr>';
10602:     return $output;
10603: }
10604: 
10605: sub sorted_searchtitles {
10606:     my %searchtitles = &Apache::lonlocal::texthash(
10607:                          'uname' => 'username',
10608:                          'lastname' => 'last name',
10609:                          'lastfirst' => 'last name, first name',
10610:                      );
10611:     my @titleorder = ('uname','lastname','lastfirst');
10612:     return (\%searchtitles,\@titleorder);
10613: }
10614: 
10615: sub sorted_searchtypes {
10616:     my %srchtypes_desc = (
10617:                            exact    => 'is exact match',
10618:                            contains => 'contains ..',
10619:                            begins   => 'begins with ..',
10620:                          );
10621:     my @srchtypeorder = ('exact','begins','contains');
10622:     return (\%srchtypes_desc,\@srchtypeorder);
10623: }
10624: 
10625: sub usertype_update_row {
10626:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
10627:     my $datatable;
10628:     my $numinrow = 4;
10629:     foreach my $type (@{$types}) {
10630:         if (defined($usertypes->{$type})) {
10631:             $$rownums ++;
10632:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
10633:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
10634:                           '</td><td class="LC_left_item"><table>';
10635:             for (my $i=0; $i<@{$fields}; $i++) {
10636:                 my $rem = $i%($numinrow);
10637:                 if ($rem == 0) {
10638:                     if ($i > 0) {
10639:                         $datatable .= '</tr>';
10640:                     }
10641:                     $datatable .= '<tr>';
10642:                 }
10643:                 my $check = ' ';
10644:                 if (ref($settings) eq 'HASH') {
10645:                     if (ref($settings->{'fields'}) eq 'HASH') {
10646:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
10647:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
10648:                                 $check = ' checked="checked" ';
10649:                             }
10650:                         }
10651:                     }
10652:                 }
10653: 
10654:                 if ($i == @{$fields}-1) {
10655:                     my $colsleft = $numinrow - $rem;
10656:                     if ($colsleft > 1) {
10657:                         $datatable .= '<td colspan="'.$colsleft.'">';
10658:                     } else {
10659:                         $datatable .= '<td>';
10660:                     }
10661:                 } else {
10662:                     $datatable .= '<td>';
10663:                 }
10664:                 $datatable .= '<span class="LC_nobreak"><label>'.
10665:                               '<input type="checkbox" name="updateable_'.$type.
10666:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
10667:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
10668:             }
10669:             $datatable .= '</tr></table></td></tr>';
10670:         }
10671:     }
10672:     return $datatable;
10673: }
10674: 
10675: sub modify_login {
10676:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
10677:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
10678:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
10679:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlwindow,%samlnotsso);
10680:     %title = ( coursecatalog => 'Display course catalog',
10681:                adminmail => 'Display administrator E-mail address',
10682:                helpdesk  => 'Display "Contact Helpdesk" link',
10683:                newuser => 'Link for visitors to create a user account',
10684:                loginheader => 'Log-in box header',
10685:                saml => 'Dual SSO and non-SSO login');
10686:     @offon = ('off','on');
10687:     if (ref($domconfig{login}) eq 'HASH') {
10688:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
10689:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
10690:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
10691:             }
10692:         }
10693:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
10694:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
10695:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
10696:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
10697:                     $saml{$lonhost} = 1;
10698:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
10699:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
10700:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
10701:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
10702:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
10703:                     $samlwindow{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'window'};
10704:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
10705:                 }
10706:             }
10707:         }
10708:     }
10709:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
10710:                                            \%domconfig,\%loginhash);
10711:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
10712:     foreach my $item (@toggles) {
10713:         $loginhash{login}{$item} = $env{'form.'.$item};
10714:     }
10715:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
10716:     if (ref($colchanges{'login'}) eq 'HASH') {  
10717:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
10718:                                          \%loginhash);
10719:     }
10720: 
10721:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
10722:     my %domservers = &Apache::lonnet::get_servers($dom);
10723:     my @loginvia_attribs = ('serverpath','custompath','exempt');
10724:     if (keys(%servers) > 1) {
10725:         foreach my $lonhost (keys(%servers)) {
10726:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
10727:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
10728:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
10729:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
10730:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
10731:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10732:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10733:                         $changes{'loginvia'}{$lonhost} = 1;
10734:                     } else {
10735:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
10736:                         $changes{'loginvia'}{$lonhost} = 1;
10737:                     }
10738:                 } else {
10739:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10740:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10741:                         $changes{'loginvia'}{$lonhost} = 1;
10742:                     }
10743:                 }
10744:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
10745:                     foreach my $item (@loginvia_attribs) {
10746:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
10747:                     }
10748:                 } else {
10749:                     foreach my $item (@loginvia_attribs) {
10750:                         my $new = $env{'form.'.$lonhost.'_'.$item};
10751:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
10752:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
10753:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
10754:                                 $new = '/';
10755:                             }
10756:                         }
10757:                         if (($item eq 'custompath') && 
10758:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
10759:                             $new = '';
10760:                         }
10761:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
10762:                             $changes{'loginvia'}{$lonhost} = 1;
10763:                         }
10764:                         if ($item eq 'exempt') {
10765:                             $new = &check_exempt_addresses($new);
10766:                         }
10767:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
10768:                     }
10769:                 }
10770:             } else {
10771:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10772:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10773:                     $changes{'loginvia'}{$lonhost} = 1;
10774:                     foreach my $item (@loginvia_attribs) {
10775:                         my $new = $env{'form.'.$lonhost.'_'.$item};
10776:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
10777:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
10778:                                 $new = '/';
10779:                             }
10780:                         }
10781:                         if (($item eq 'custompath') && 
10782:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
10783:                             $new = '';
10784:                         }
10785:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
10786:                     }
10787:                 }
10788:             }
10789:         }
10790:     }
10791: 
10792:     my $servadm = $r->dir_config('lonAdmEMail');
10793:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
10794:     if (ref($domconfig{'login'}) eq 'HASH') {
10795:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
10796:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
10797:                 if ($lang eq 'nolang') {
10798:                     push(@currlangs,$lang);
10799:                 } elsif (defined($langchoices{$lang})) {
10800:                     push(@currlangs,$lang);
10801:                 } else {
10802:                     next;
10803:                 }
10804:             }
10805:         }
10806:     }
10807:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
10808:     if (@currlangs > 0) {
10809:         foreach my $lang (@currlangs) {
10810:             if (grep(/^\Q$lang\E$/,@delurls)) {
10811:                 $changes{'helpurl'}{$lang} = 1;
10812:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
10813:                 $changes{'helpurl'}{$lang} = 1;
10814:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
10815:                 push(@newlangs,$lang);
10816:             } else {
10817:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
10818:             }
10819:         }
10820:     }
10821:     unless (grep(/^nolang$/,@currlangs)) {
10822:         if ($env{'form.loginhelpurl_nolang.filename'}) {
10823:             $changes{'helpurl'}{'nolang'} = 1;
10824:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
10825:             push(@newlangs,'nolang');
10826:         }
10827:     }
10828:     if ($env{'form.loginhelpurl_add_lang'}) {
10829:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
10830:             ($env{'form.loginhelpurl_add_file.filename'})) {
10831:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
10832:             $addedfile = $env{'form.loginhelpurl_add_lang'};
10833:         }
10834:     }
10835:     if ((@newlangs > 0) || ($addedfile)) {
10836:         my $error;
10837:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10838:         if ($configuserok eq 'ok') {
10839:             if ($switchserver) {
10840:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
10841:             } elsif ($author_ok eq 'ok') {
10842:                 my @allnew = @newlangs;
10843:                 if ($addedfile ne '') {
10844:                     push(@allnew,$addedfile);
10845:                 }
10846:                 my $modified = [];
10847:                 foreach my $lang (@allnew) {
10848:                     my $formelem = 'loginhelpurl_'.$lang;
10849:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
10850:                         $formelem = 'loginhelpurl_add_file';
10851:                     }
10852:                     (my $result,$newurl{$lang}) =
10853:                         &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
10854:                                                                 "help/$lang",'','',$newfile{$lang},
10855:                                                                 $modified);
10856:                     if ($result eq 'ok') {
10857:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
10858:                         $changes{'helpurl'}{$lang} = 1;
10859:                     } else {
10860:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
10861:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10862:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
10863:                             (!grep(/^\Q$lang\E$/,@delurls))) {
10864:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
10865:                         }
10866:                     }
10867:                 }
10868:                 &update_modify_urls($r,$modified);
10869:             } else {
10870:                 $error = &mt("Upload of custom log-in help file(s) failed because an author role could not be assigned to a Domain Configuration user ([_1]) in domain: [_2].  Error was: [_3].",$confname,$dom,$author_ok);
10871:             }
10872:         } else {
10873:             $error = &mt("Upload of custom log-in help file(s) failed because a Domain Configuration user ([_1]) could not be created in domain: [_2].  Error was: [_3].",$confname,$dom,$configuserok);
10874:         }
10875:         if ($error) {
10876:             &Apache::lonnet::logthis($error);
10877:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10878:         }
10879:     }
10880: 
10881:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
10882:     if (ref($domconfig{'login'}) eq 'HASH') {
10883:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
10884:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
10885:                 if ($domservers{$lonhost}) {
10886:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
10887:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
10888:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
10889:                     }
10890:                 }
10891:             }
10892:         }
10893:     }
10894:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
10895:     foreach my $lonhost (sort(keys(%domservers))) {
10896:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
10897:             $changes{'headtag'}{$lonhost} = 1;
10898:         } else {
10899:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
10900:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
10901:             }
10902:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
10903:                 push(@newhosts,$lonhost);
10904:             } elsif ($currheadtagurls{$lonhost}) {
10905:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
10906:                 if ($currexempt{$lonhost}) {
10907:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
10908:                         $changes{'headtag'}{$lonhost} = 1;
10909:                     }
10910:                 } elsif ($possexempt{$lonhost}) {
10911:                     $changes{'headtag'}{$lonhost} = 1;
10912:                 }
10913:                 if ($possexempt{$lonhost}) {
10914:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
10915:                 }
10916:             }
10917:         }
10918:     }
10919:     if (@newhosts) {
10920:         my $error;
10921:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10922:         if ($configuserok eq 'ok') {
10923:             if ($switchserver) {
10924:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
10925:             } elsif ($author_ok eq 'ok') {
10926:                 my $modified = [];
10927:                 foreach my $lonhost (@newhosts) {
10928:                     my $formelem = 'loginheadtag_'.$lonhost;
10929:                     (my $result,$newheadtagurls{$lonhost}) =
10930:                         &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
10931:                                                                 "login/headtag/$lonhost",'','',
10932:                                                                 $env{'form.loginheadtag_'.$lonhost.'.filename'},
10933:                                                                 $modified);
10934:                     if ($result eq 'ok') {
10935:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
10936:                         $changes{'headtag'}{$lonhost} = 1;
10937:                         if ($possexempt{$lonhost}) {
10938:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
10939:                         }
10940:                     } else {
10941:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
10942:                                            $newheadtagurls{$lonhost},$result);
10943:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10944:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
10945:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
10946:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
10947:                         }
10948:                     }
10949:                 }
10950:                 &update_modify_urls($r,$modified);
10951:             } else {
10952:                 $error = &mt("Upload of custom markup file(s) failed because an author role could not be assigned to a Domain Configuration user ([_1]) in domain: [_2].  Error was: [_3].",$confname,$dom,$author_ok);
10953:             }
10954:         } else {
10955:             $error = &mt("Upload of custom markup file(s) failed because a Domain Configuration user ([_1]) could not be created in domain: [_2].  Error was: [_3].",$confname,$dom,$configuserok);
10956:         }
10957:         if ($error) {
10958:             &Apache::lonnet::logthis($error);
10959:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10960:         }
10961:     }
10962:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
10963:     my @newsamlimgs;
10964:     foreach my $lonhost (keys(%domservers)) {
10965:         if ($env{'form.saml_'.$lonhost}) {
10966:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
10967:                 push(@newsamlimgs,$lonhost);
10968:             }
10969:             foreach my $item ('text','alt','url','title','window','notsso') {
10970:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
10971:             }
10972:             if ($saml{$lonhost}) {
10973:                 if ($env{'form.saml_window_'.$lonhost} ne '1') {
10974:                     $env{'form.saml_window_'.$lonhost} = '';
10975:                 }
10976:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
10977: #FIXME Need to obsolete published image
10978:                     delete($currsaml{$lonhost}{'img'});
10979:                     $changes{'saml'}{$lonhost} = 1;
10980:                 }
10981:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
10982:                     $changes{'saml'}{$lonhost} = 1;
10983:                 }
10984:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
10985:                     $changes{'saml'}{$lonhost} = 1;
10986:                 }
10987:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
10988:                     $changes{'saml'}{$lonhost} = 1;
10989:                 }
10990:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
10991:                     $changes{'saml'}{$lonhost} = 1;
10992:                 }
10993:                 if ($env{'form.saml_window_'.$lonhost} ne $samlwindow{$lonhost}) {
10994:                     $changes{'saml'}{$lonhost} = 1;
10995:                 }
10996:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
10997:                     $changes{'saml'}{$lonhost} = 1;
10998:                 }
10999:             } else {
11000:                 $changes{'saml'}{$lonhost} = 1;
11001:             }
11002:             foreach my $item ('text','alt','url','title','window','notsso') {
11003:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
11004:             }
11005:         } else {
11006:             if ($saml{$lonhost}) {
11007:                 $changes{'saml'}{$lonhost} = 1;
11008:                 delete($currsaml{$lonhost});
11009:             }
11010:         }
11011:     }
11012:     foreach my $posshost (keys(%currsaml)) {
11013:         unless (exists($domservers{$posshost})) {
11014:             delete($currsaml{$posshost});
11015:         }
11016:     }
11017:     %{$loginhash{'login'}{'saml'}} = %currsaml;
11018:     if (@newsamlimgs) {
11019:         my $error;
11020:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11021:         if ($configuserok eq 'ok') {
11022:             if ($switchserver) {
11023:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
11024:             } elsif ($author_ok eq 'ok') {
11025:                 my $modified = [];
11026:                 foreach my $lonhost (@newsamlimgs) {
11027:                     my $formelem = 'saml_img_'.$lonhost;
11028:                     my ($result,$imgurl) =
11029:                         &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
11030:                                                                 "login/saml/$lonhost",'','',
11031:                                                                 $env{'form.saml_img_'.$lonhost.'.filename'},
11032:                                                                 $modified);
11033:                     if ($result eq 'ok') {
11034:                         $currsaml{$lonhost}{'img'} = $imgurl;
11035:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
11036:                         $changes{'saml'}{$lonhost} = 1;
11037:                     } else {
11038:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
11039:                                            $lonhost,$result);
11040:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11041:                     }
11042:                 }
11043:                 &update_modify_urls($r,$modified);
11044:             } else {
11045:                 $error = &mt("Upload of SSO button image file(s) failed because an author role could not be assigned to a Domain Configuration user ([_1]) in domain: [_2].  Error was: [_3].",$confname,$dom,$author_ok);
11046:             }
11047:         } else {
11048:             $error = &mt("Upload of SSO button image file(s) failed because a Domain Configuration user ([_1]) could not be created in domain: [_2].  Error was: [_3].",$confname,$dom,$configuserok);
11049:         }
11050:         if ($error) {
11051:             &Apache::lonnet::logthis($error);
11052:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11053:         }
11054:     }
11055:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
11056: 
11057:     my $defaulthelpfile = '/adm/loginproblems.html';
11058:     my $defaulttext = &mt('Default in use');
11059: 
11060:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
11061:                                              $dom);
11062:     if ($putresult eq 'ok') {
11063:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11064:         my %defaultchecked = (
11065:                     'coursecatalog' => 'on',
11066:                     'helpdesk'      => 'on',
11067:                     'adminmail'     => 'off',
11068:                     'newuser'       => 'off',
11069:         );
11070:         if (ref($domconfig{'login'}) eq 'HASH') {
11071:             foreach my $item (@toggles) {
11072:                 if ($defaultchecked{$item} eq 'on') { 
11073:                     if (($domconfig{'login'}{$item} eq '0') &&
11074:                         ($env{'form.'.$item} eq '1')) {
11075:                         $changes{$item} = 1;
11076:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11077:                               $domconfig{'login'}{$item} eq '1') &&
11078:                              ($env{'form.'.$item} eq '0')) {
11079:                         $changes{$item} = 1;
11080:                     }
11081:                 } elsif ($defaultchecked{$item} eq 'off') {
11082:                     if (($domconfig{'login'}{$item} eq '1') &&
11083:                         ($env{'form.'.$item} eq '0')) {
11084:                         $changes{$item} = 1;
11085:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11086:                               $domconfig{'login'}{$item} eq '0') &&
11087:                              ($env{'form.'.$item} eq '1')) {
11088:                         $changes{$item} = 1;
11089:                     }
11090:                 }
11091:             }
11092:         }
11093:         if (keys(%changes) > 0 || $colchgtext) {
11094:             &Apache::loncommon::devalidate_domconfig_cache($dom);
11095:             if (exists($changes{'saml'})) {
11096:                 my $hostid_in_use;
11097:                 my @hosts = &Apache::lonnet::current_machine_ids();
11098:                 if (@hosts > 1) {
11099:                     foreach my $hostid (@hosts) {
11100:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
11101:                             $hostid_in_use = $hostid;
11102:                             last;
11103:                         }
11104:                     }
11105:                 } else {
11106:                     $hostid_in_use = $r->dir_config('lonHostID');
11107:                 }
11108:                 if (($hostid_in_use) &&
11109:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
11110:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
11111:                 }
11112:                 if (ref($lastactref) eq 'HASH') {
11113:                     if (ref($changes{'saml'}) eq 'HASH') {
11114:                         my %updates;
11115:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
11116:                         $lastactref->{'samllanding'} = \%updates;
11117:                     }
11118:                 }
11119:             }
11120:             if (ref($lastactref) eq 'HASH') {
11121:                 $lastactref->{'domainconfig'} = 1;
11122:             }
11123:             $resulttext = &mt('Changes made:').'<ul>';
11124:             foreach my $item (sort(keys(%changes))) {
11125:                 if ($item eq 'loginvia') {
11126:                     if (ref($changes{$item}) eq 'HASH') {
11127:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
11128:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11129:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
11130:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
11131:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
11132:                                     $protocol = 'http' if ($protocol ne 'https');
11133:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
11134: 
11135:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
11136:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
11137:                                     } else {
11138:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
11139:                                     }
11140:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
11141:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
11142:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
11143:                                     }
11144:                                     $resulttext .= '</li>';
11145:                                 } else {
11146:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
11147:                                 }
11148:                             } else {
11149:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
11150:                             }
11151:                         }
11152:                         $resulttext .= '</ul></li>';
11153:                     }
11154:                 } elsif ($item eq 'helpurl') {
11155:                     if (ref($changes{$item}) eq 'HASH') {
11156:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
11157:                             if (grep(/^\Q$lang\E$/,@delurls)) {
11158:                                 my ($chg,$link);
11159:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
11160:                                 if ($lang eq 'nolang') {
11161:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
11162:                                 } else {
11163:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
11164:                                 }
11165:                                 $resulttext .= '<li>'.$chg.'</li>';
11166:                             } else {
11167:                                 my $chg;
11168:                                 if ($lang eq 'nolang') {
11169:                                     $chg = &mt('custom log-in help file for no preferred language');
11170:                                 } else {
11171:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
11172:                                 }
11173:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
11174:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
11175:                                                       '?inhibitmenu=yes',$chg,600,500).
11176:                                                '</li>';
11177:                             }
11178:                         }
11179:                     }
11180:                 } elsif ($item eq 'headtag') {
11181:                     if (ref($changes{$item}) eq 'HASH') {
11182:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11183:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11184:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
11185:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11186:                                 $resulttext .= '<li><a href="'.
11187:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
11188:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
11189:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
11190:                                 if ($possexempt{$lonhost}) {
11191:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
11192:                                 } else {
11193:                                     $resulttext .= &mt('included for any client IP');
11194:                                 }
11195:                                 $resulttext .= '</li>';
11196:                             }
11197:                         }
11198:                     }
11199:                 } elsif ($item eq 'saml') {
11200:                     if (ref($changes{$item}) eq 'HASH') {
11201:                         my %notlt = (
11202:                                        text   => 'Text for log-in by SSO',
11203:                                        img    => 'SSO button image',
11204:                                        alt    => 'Alt text for button image',
11205:                                        url    => 'SSO URL',
11206:                                        title  => 'Tooltip for SSO link',
11207:                                        window => 'Pop-up window if iframe',
11208:                                        notsso => 'Text for non-SSO log-in',
11209:                                     );
11210:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11211:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
11212:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
11213:                                                '<ul>';
11214:                                 foreach my $key ('text','img','alt','url','title','window','notsso') {
11215:                                     if ($currsaml{$lonhost}{$key} eq '') {
11216:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
11217:                                     } else {
11218:                                         my $value = "'$currsaml{$lonhost}{$key}'";
11219:                                         if ($key eq 'img') {
11220:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
11221:                                         } elsif ($key eq 'window') {
11222:                                             $value = 'On';
11223:                                         }
11224:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
11225:                                                                   $value).'</li>';
11226:                                     }
11227:                                 }
11228:                                 $resulttext .= '</ul></li>';
11229:                             } else {
11230:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
11231:                             }
11232:                         }
11233:                     }
11234:                 } elsif ($item eq 'captcha') {
11235:                     if (ref($loginhash{'login'}) eq 'HASH') {
11236:                         my $chgtxt;
11237:                         if ($loginhash{'login'}{$item} eq 'notused') {
11238:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
11239:                         } else {
11240:                             my %captchas = &captcha_phrases();
11241:                             if ($captchas{$loginhash{'login'}{$item}}) {
11242:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
11243:                             } else {
11244:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
11245:                             }
11246:                         }
11247:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11248:                     }
11249:                 } elsif ($item eq 'recaptchakeys') {
11250:                     if (ref($loginhash{'login'}) eq 'HASH') {
11251:                         my ($privkey,$pubkey);
11252:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
11253:                             $pubkey = $loginhash{'login'}{$item}{'public'};
11254:                             $privkey = $loginhash{'login'}{$item}{'private'};
11255:                         }
11256:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
11257:                         if (!$pubkey) {
11258:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
11259:                         } else {
11260:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
11261:                         }
11262:                         if (!$privkey) {
11263:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
11264:                         } else {
11265:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
11266:                         }
11267:                         $chgtxt .= '</ul>';
11268:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11269:                     }
11270:                 } elsif ($item eq 'recaptchaversion') {
11271:                     if (ref($loginhash{'login'}) eq 'HASH') {
11272:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
11273:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
11274:                                            '</li>';
11275:                         }
11276:                     }
11277:                 } else {
11278:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
11279:                 }
11280:             }
11281:             $resulttext .= $colchgtext.'</ul>';
11282:         } else {
11283:             $resulttext = &mt('No changes made to log-in page settings');
11284:         }
11285:     } else {
11286:         $resulttext = '<span class="LC_error">'.
11287: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11288:     }
11289:     if ($errors) {
11290:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
11291:                        $errors.'</ul>';
11292:     }
11293:     return $resulttext;
11294: }
11295: 
11296: sub check_exempt_addresses {
11297:     my ($iplist) = @_;
11298:     $iplist =~ s/^\s+//;
11299:     $iplist =~ s/\s+$//;
11300:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
11301:     my (@okips,$new);
11302:     foreach my $ip (@poss_ips) {
11303:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
11304:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
11305:                 push(@okips,$ip);
11306:             }
11307:         }
11308:     }
11309:     if (@okips > 0) {
11310:         $new = join(',',@okips);
11311:     } else {
11312:         $new = '';
11313:     }
11314:     return $new;
11315: }
11316: 
11317: sub color_font_choices {
11318:     my %choices =
11319:         &Apache::lonlocal::texthash (
11320:             img => "Header",
11321:             bgs => "Background colors",
11322:             links => "Link colors",
11323:             images => "Images",
11324:             font => "Font color",
11325:             fontmenu => "Font menu",
11326:             pgbg => "Page",
11327:             tabbg => "Header",
11328:             sidebg => "Border",
11329:             link => "Link",
11330:             alink => "Active link",
11331:             vlink => "Visited link",
11332:         );
11333:     return %choices;
11334: }
11335: 
11336: sub modify_ipaccess {
11337:     my ($dom,$lastactref,%domconfig) = @_;
11338:     my (@allpos,%changes,%confhash,$errors,$resulttext);
11339:     my (@items,%deletions,%itemids,@warnings);
11340:     my ($typeorder,$types) = &commblocktype_text();
11341:     if ($env{'form.ipaccess_add'}) {
11342:         my $name = $env{'form.ipaccess_name_add'};
11343:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
11344:         if ($newid) {
11345:             $itemids{'add'} = $newid;
11346:             push(@items,'add');
11347:             $changes{$newid} = 1;
11348:         } else {
11349:             $error = &mt('Failed to acquire unique ID for new IP access control item');
11350:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11351:         }
11352:     }
11353:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
11354:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
11355:         if (@todelete) {
11356:             map { $deletions{$_} = 1; } @todelete;
11357:         }
11358:         my $maxnum = $env{'form.ipaccess_maxnum'};
11359:         for (my $i=0; $i<$maxnum; $i++) {
11360:             my $itemid = $env{'form.ipaccess_id_'.$i};
11361:             $itemid =~ s/\D+//g;
11362:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
11363:                 if ($deletions{$itemid}) {
11364:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
11365:                 } else {
11366:                     push(@items,$i);
11367:                     $itemids{$i} = $itemid;
11368:                 }
11369:             }
11370:         }
11371:     }
11372:     foreach my $idx (@items) {
11373:         my $itemid = $itemids{$idx};
11374:         next unless ($itemid);
11375:         my %current;
11376:         unless ($idx eq 'add') {
11377:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
11378:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
11379:             }
11380:         }
11381:         my $position = $env{'form.ipaccess_pos_'.$itemid};
11382:         $position =~ s/\D+//g;
11383:         if ($position ne '') {
11384:             $allpos[$position] = $itemid;
11385:         }
11386:         my $name = $env{'form.ipaccess_name_'.$idx};
11387:         $name =~ s/^\s+|\s+$//g;
11388:         $confhash{$itemid}{'name'} = $name;
11389:         my $possrange = $env{'form.ipaccess_range_'.$idx};
11390:         $possrange =~ s/^\s+|\s+$//g;
11391:         unless ($possrange eq '') {
11392:             $possrange =~ s/[\r\n]+/\s/g;
11393:             $possrange =~ s/\s*-\s*/-/g;
11394:             $possrange =~ s/\s+/,/g;
11395:             $possrange =~ s/,+/,/g;
11396:             if ($possrange ne '') {
11397:                 my (@ok,$count);
11398:                 $count = 0;
11399:                 foreach my $poss (split(/\,/,$possrange)) {
11400:                     $count ++;
11401:                     $poss = &validate_ip_pattern($poss);
11402:                     if ($poss ne '') {
11403:                         push(@ok,$poss);
11404:                     }
11405:                 }
11406:                 my $diff = $count - scalar(@ok);
11407:                 if ($diff) {
11408:                     $errors .= '<li><span class="LC_error">'.
11409:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
11410:                                    $diff,$name).
11411:                                '</span></li>';
11412:                 }
11413:                 if (@ok) {
11414:                     my @cidr_list;
11415:                     foreach my $item (@ok) {
11416:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
11417:                     }
11418:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
11419:                 }
11420:             }
11421:         }
11422:         foreach my $field ('name','ip') {
11423:             unless (($idx eq 'add') || ($changes{$itemid})) {
11424:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
11425:                     $changes{$itemid} = 1;
11426:                     last;
11427:                 }
11428:             }
11429:         }
11430:         $confhash{$itemid}{'commblocks'} = {};
11431: 
11432:         my %commblocks;
11433:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);
11434:         foreach my $type (@{$typeorder}) {
11435:             if ($commblocks{$type}) {
11436:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
11437:             }
11438:             unless (($idx eq 'add') || ($changes{$itemid})) {
11439:                 if (ref($current{'commblocks'}) eq 'HASH') {
11440:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
11441:                         $changes{$itemid} = 1;
11442:                     }
11443:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
11444:                     $changes{$itemid} = 1;
11445:                 }
11446:             }
11447:         }
11448:         $confhash{$itemid}{'courses'} = {};
11449:         my %crsdeletions;
11450:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
11451:         if (@delcrs) {
11452:             map { $crsdeletions{$_} = 1; } @delcrs;
11453:         }
11454:         if (ref($current{'courses'}) eq 'HASH') {
11455:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
11456:                 if ($crsdeletions{$cid}) {
11457:                     $changes{$itemid} = 1;
11458:                 } else {
11459:                     $confhash{$itemid}{'courses'}{$cid} = 1;
11460:                 }
11461:             }
11462:         }
11463:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
11464:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
11465:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) &&
11466:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
11467:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
11468:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
11469:                 $errors .= '<li><span class="LC_error">'.
11470:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
11471:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
11472:                            '</span></li>';
11473:             } else {
11474:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
11475:                 $changes{$itemid} = 1;
11476:             }
11477:         }
11478:     }
11479:     if (@allpos > 0) {
11480:         my $idx = 0;
11481:         foreach my $itemid (@allpos) {
11482:             if ($itemid ne '') {
11483:                 $confhash{$itemid}{'order'} = $idx;
11484:                 unless ($changes{$itemid}) {
11485:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
11486:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
11487:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
11488:                                 $changes{$itemid} = 1;
11489:                             }
11490:                         }
11491:                     }
11492:                 }
11493:                 $idx ++;
11494:             }
11495:         }
11496:     }
11497:     if (keys(%changes)) {
11498:         my %defaultshash = (
11499:                               ipaccess => \%confhash,
11500:                            );
11501:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
11502:                                                  $dom);
11503:         if ($putresult eq 'ok') {
11504:             my $cachetime = 1800;
11505:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
11506:             if (ref($lastactref) eq 'HASH') {
11507:                 $lastactref->{'ipaccess'} = 1;
11508:             }
11509:             $resulttext = &mt('Changes made:').'<ul>';
11510:             my %bynum;
11511:             foreach my $itemid (sort(keys(%changes))) {
11512:                 if (ref($confhash{$itemid}) eq 'HASH') {
11513:                     my $position = $confhash{$itemid}{'order'};
11514:                     if ($position =~ /^\d+$/) {
11515:                         $bynum{$position} = $itemid;
11516:                     }
11517:                 }
11518:             }
11519:             if (keys(%deletions)) {
11520:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
11521:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
11522:                 }
11523:             }
11524:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
11525:                 my $itemid = $bynum{$pos};
11526:                 if (ref($confhash{$itemid}) eq 'HASH') {
11527:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
11528:                     my $position = $pos + 1;
11529:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
11530:                     if ($confhash{$itemid}{'ip'} eq '') {
11531:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
11532:                     } else {
11533:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
11534:                     }
11535:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
11536:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
11537:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
11538:                                        '</li>';
11539:                     } else {
11540:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
11541:                     }
11542:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
11543:                         my @courses;
11544:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
11545:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
11546:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
11547:                         }
11548:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
11549:                                              join('</li><li>',@courses).'</li></ul>';
11550:                     } else {
11551:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
11552:                     }
11553:                     $resulttext .= '</ul></li>';
11554:                 }
11555:             }
11556:             $resulttext .= '</ul>';
11557:         } else {
11558:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
11559:         }
11560:     } else {
11561:         $resulttext = &mt('No changes made');
11562:     }
11563:     if ($errors) {
11564:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
11565:                        $errors.'</ul></p>';
11566:     }
11567:     return $resulttext;
11568: }
11569: 
11570: sub get_ipaccess_id {
11571:     my ($domain,$location) = @_;
11572:     # get lock on ipaccess db
11573:     my $lockhash = {
11574:                       lock => $env{'user.name'}.
11575:                               ':'.$env{'user.domain'},
11576:                    };
11577:     my $tries = 0;
11578:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
11579:     my ($id,$error);
11580: 
11581:     while (($gotlock ne 'ok') && ($tries<10)) {
11582:         $tries ++;
11583:         sleep (0.1);
11584:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
11585:     }
11586:     if ($gotlock eq 'ok') {
11587:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
11588:         if ($currids{'lock'}) {
11589:             delete($currids{'lock'});
11590:             if (keys(%currids)) {
11591:                 my @curr = sort { $a <=> $b } keys(%currids);
11592:                 if ($curr[-1] =~ /^\d+$/) {
11593:                     $id = 1 + $curr[-1];
11594:                 }
11595:             } else {
11596:                 $id = 1;
11597:             }
11598:             if ($id) {
11599:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
11600:                     $error = 'nostore';
11601:                 }
11602:             } else {
11603:                 $error = 'nonumber';
11604:             }
11605:         }
11606:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
11607:     } else {
11608:         $error = 'nolock';
11609:     }
11610:     return ($id,$error);
11611: }
11612: 
11613: sub modify_rolecolors {
11614:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
11615:     my ($resulttext,%rolehash);
11616:     $rolehash{'rolecolors'} = {};
11617:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
11618:         if ($domconfig{'rolecolors'} eq '') {
11619:             $domconfig{'rolecolors'} = {};
11620:         }
11621:     }
11622:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
11623:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
11624:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
11625:                                              $dom);
11626:     if ($putresult eq 'ok') {
11627:         if (keys(%changes) > 0) {
11628:             &Apache::loncommon::devalidate_domconfig_cache($dom);
11629:             if (ref($lastactref) eq 'HASH') {
11630:                 $lastactref->{'domainconfig'} = 1;
11631:             }
11632:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
11633:                                              $rolehash{'rolecolors'});
11634:         } else {
11635:             $resulttext = &mt('No changes made to default color schemes');
11636:         }
11637:     } else {
11638:         $resulttext = '<span class="LC_error">'.
11639: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11640:     }
11641:     if ($errors) {
11642:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
11643:                        $errors.'</ul>';
11644:     }
11645:     return $resulttext;
11646: }
11647: 
11648: sub modify_colors {
11649:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
11650:     my (%changes,%choices);
11651:     my @bgs;
11652:     my @links = ('link','alink','vlink');
11653:     my @logintext;
11654:     my @images;
11655:     my $servadm = $r->dir_config('lonAdmEMail');
11656:     my $errors;
11657:     my %defaults;
11658:     foreach my $role (@{$roles}) {
11659:         if ($role eq 'login') {
11660:             %choices = &login_choices();
11661:             @logintext = ('textcol','bgcol');
11662:         } else {
11663:             %choices = &color_font_choices();
11664:         }
11665:         if ($role eq 'login') {
11666:             @images = ('img','logo','domlogo','login');
11667:             @bgs = ('pgbg','mainbg','sidebg');
11668:         } else {
11669:             @images = ('img');
11670:             @bgs = ('pgbg','tabbg','sidebg');
11671:         }
11672:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
11673:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
11674:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
11675:         }
11676:         if ($role eq 'login') {
11677:             foreach my $item (@logintext) {
11678:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11679:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11680:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11681:                 }
11682:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
11683:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11684:                 }
11685:             }
11686:         } else {
11687:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
11688:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
11689:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
11690:             }
11691:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
11692:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
11693:             }
11694:         }
11695:         foreach my $item (@bgs) {
11696:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11697:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11698:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11699:             }
11700:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
11701:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11702:             }
11703:         }
11704:         foreach my $item (@links) {
11705:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11706:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11707:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11708:             }
11709:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
11710:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11711:             }
11712:         }
11713:         my ($configuserok,$author_ok,$switchserver) = 
11714:             &config_check($dom,$confname,$servadm);
11715:         my ($width,$height) = &thumb_dimensions();
11716:         if (ref($domconfig->{$role}) ne 'HASH') {
11717:             $domconfig->{$role} = {};
11718:         }
11719:         foreach my $img (@images) {
11720:             if ($role eq 'login') {
11721:                 if (($img eq 'img') || ($img eq 'logo')) {  
11722:                     if (defined($env{'form.login_showlogo_'.$img})) {
11723:                         $confhash->{$role}{'showlogo'}{$img} = 1;
11724:                     } else { 
11725:                         $confhash->{$role}{'showlogo'}{$img} = 0;
11726:                     }
11727:                 }
11728:                 if ($env{'form.login_alt_'.$img} ne '') {
11729:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
11730:                 }
11731:             }
11732: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
11733: 		 && !defined($domconfig->{$role}{$img})
11734: 		 && !$env{'form.'.$role.'_del_'.$img}
11735: 		 && $env{'form.'.$role.'_import_'.$img}) {
11736: 		# import the old configured image from the .tab setting
11737: 		# if they haven't provided a new one 
11738: 		$domconfig->{$role}{$img} = 
11739: 		    $env{'form.'.$role.'_import_'.$img};
11740: 	    }
11741:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
11742:                 my $error;
11743:                 if ($configuserok eq 'ok') {
11744:                     if ($switchserver) {
11745:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
11746:                     } else {
11747:                         if ($author_ok eq 'ok') {
11748:                             my $modified = [];
11749:                             my ($result,$logourl) = 
11750:                                 &Apache::lonconfigsettings::publishlogo($r,'upload',$role.'_'.$img,
11751:                                                                         $dom,$confname,$img,$width,$height,
11752:                                                                         '',$modified);
11753:                             if ($result eq 'ok') {
11754:                                 $confhash->{$role}{$img} = $logourl;
11755:                                 $changes{$role}{'images'}{$img} = 1;
11756:                                 &update_modify_urls($r,$modified);
11757:                             } else {
11758:                                 $error = &mt("Upload of [_1] image for $role page(s) failed because an error occurred publishing the file in RES space. Error was: [_2].",$choices{img},$result);
11759:                             }
11760:                         } else {
11761:                             $error = &mt("Upload of [_1] image for $role page(s) failed because an author role could not be assigned to a Domain Configuration user ([_2]) in domain: [_3].  Error was: [_4].",$choices{$img},$confname,$dom,$author_ok);
11762:                         }
11763:                     }
11764:                 } else {
11765:                     $error = &mt("Upload of [_1] image for $role page(s) failed because a Domain Configuration user ([_2]) could not be created in domain: [_3].  Error was: [_4].",$choices{$img},$confname,$dom,$configuserok);
11766:                 }
11767:                 if ($error) {
11768:                     &Apache::lonnet::logthis($error);
11769:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11770:                 }
11771:             } elsif ($domconfig->{$role}{$img} ne '') {
11772:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
11773:                     my $error;
11774:                     if ($configuserok eq 'ok') {
11775: # is confname an author?
11776:                         if ($switchserver eq '') {
11777:                             if ($author_ok eq 'ok') {
11778:                                 my $modified = [];
11779:                                 my ($result,$logourl) = 
11780:                                     &Apache::lonconfigsettings::publishlogo($r,'copy',$domconfig->{$role}{$img},
11781:                                                                             $dom,$confname,$img,$width,$height,
11782:                                                                             '',$modified);
11783:                                 if ($result eq 'ok') {
11784:                                     $confhash->{$role}{$img} = $logourl;
11785: 				    $changes{$role}{'images'}{$img} = 1;
11786:                                     &update_modify_urls($r,$modified);
11787:                                 }
11788:                             }
11789:                         }
11790:                     }
11791:                 }
11792:             }
11793:         }
11794:         if (ref($domconfig) eq 'HASH') {
11795:             if (ref($domconfig->{$role}) eq 'HASH') {
11796:                 foreach my $img (@images) {
11797:                     if ($domconfig->{$role}{$img} ne '') {
11798:                         if ($env{'form.'.$role.'_del_'.$img}) {
11799:                             $confhash->{$role}{$img} = '';
11800:                             $changes{$role}{'images'}{$img} = 1;
11801:                         } else {
11802:                             if ($confhash->{$role}{$img} eq '') {
11803:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
11804:                             }
11805:                         }
11806:                     } else {
11807:                         if ($env{'form.'.$role.'_del_'.$img}) {
11808:                             $confhash->{$role}{$img} = '';
11809:                             $changes{$role}{'images'}{$img} = 1;
11810:                         } 
11811:                     }
11812:                     if ($role eq 'login') {
11813:                         if (($img eq 'logo') || ($img eq 'img')) {
11814:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
11815:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
11816:                                     $domconfig->{$role}{'showlogo'}{$img}) {
11817:                                     $changes{$role}{'showlogo'}{$img} = 1; 
11818:                                 }
11819:                             } else {
11820:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
11821:                                     $changes{$role}{'showlogo'}{$img} = 1;
11822:                                 }
11823:                             }
11824:                         }
11825:                         if ($img ne 'login') {
11826:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
11827:                                 if ($confhash->{$role}{'alttext'}{$img} ne
11828:                                     $domconfig->{$role}{'alttext'}{$img}) {
11829:                                     $changes{$role}{'alttext'}{$img} = 1;
11830:                                 }
11831:                             } else {
11832:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
11833:                                     $changes{$role}{'alttext'}{$img} = 1;
11834:                                 }
11835:                             }
11836:                         }
11837:                     }
11838:                 }
11839:                 if ($domconfig->{$role}{'font'} ne '') {
11840:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
11841:                         $changes{$role}{'font'} = 1;
11842:                     }
11843:                 } else {
11844:                     if ($confhash->{$role}{'font'}) {
11845:                         $changes{$role}{'font'} = 1;
11846:                     }
11847:                 }
11848:                 if ($role ne 'login') {
11849:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
11850:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
11851:                             $changes{$role}{'fontmenu'} = 1;
11852:                         }
11853:                     } else {
11854:                         if ($confhash->{$role}{'fontmenu'}) {
11855:                             $changes{$role}{'fontmenu'} = 1;
11856:                         }
11857:                     }
11858:                 }
11859:                 foreach my $item (@bgs) {
11860:                     if ($domconfig->{$role}{$item} ne '') {
11861:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11862:                             $changes{$role}{'bgs'}{$item} = 1;
11863:                         } 
11864:                     } else {
11865:                         if ($confhash->{$role}{$item}) {
11866:                             $changes{$role}{'bgs'}{$item} = 1;
11867:                         }
11868:                     }
11869:                 }
11870:                 foreach my $item (@links) {
11871:                     if ($domconfig->{$role}{$item} ne '') {
11872:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11873:                             $changes{$role}{'links'}{$item} = 1;
11874:                         }
11875:                     } else {
11876:                         if ($confhash->{$role}{$item}) {
11877:                             $changes{$role}{'links'}{$item} = 1;
11878:                         }
11879:                     }
11880:                 }
11881:                 foreach my $item (@logintext) {
11882:                     if ($domconfig->{$role}{$item} ne '') {
11883:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11884:                             $changes{$role}{'logintext'}{$item} = 1;
11885:                         }
11886:                     } else {
11887:                         if ($confhash->{$role}{$item}) {
11888:                             $changes{$role}{'logintext'}{$item} = 1;
11889:                         }
11890:                     }
11891:                 }
11892:             } else {
11893:                 &default_change_checker($role,\@images,\@links,\@bgs,
11894:                                         \@logintext,$confhash,\%changes); 
11895:             }
11896:         } else {
11897:             &default_change_checker($role,\@images,\@links,\@bgs,
11898:                                     \@logintext,$confhash,\%changes); 
11899:         }
11900:     }
11901:     return ($errors,%changes);
11902: }
11903: 
11904: sub config_check {
11905:     my ($dom,$confname,$servadm) = @_;
11906:     my ($configuserok,$author_ok,$switchserver,%currroles);
11907:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
11908:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
11909:                                                    $confname,$servadm);
11910:     if ($configuserok eq 'ok') {
11911:         $switchserver = &check_switchserver($dom,$confname);
11912:         if ($switchserver eq '') {
11913:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
11914:         }
11915:     }
11916:     return ($configuserok,$author_ok,$switchserver);
11917: }
11918: 
11919: sub default_change_checker {
11920:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
11921:     foreach my $item (@{$links}) {
11922:         if ($confhash->{$role}{$item}) {
11923:             $changes->{$role}{'links'}{$item} = 1;
11924:         }
11925:     }
11926:     foreach my $item (@{$bgs}) {
11927:         if ($confhash->{$role}{$item}) {
11928:             $changes->{$role}{'bgs'}{$item} = 1;
11929:         }
11930:     }
11931:     foreach my $item (@{$logintext}) {
11932:         if ($confhash->{$role}{$item}) {
11933:             $changes->{$role}{'logintext'}{$item} = 1;
11934:         }
11935:     }
11936:     foreach my $img (@{$images}) {
11937:         if ($env{'form.'.$role.'_del_'.$img}) {
11938:             $confhash->{$role}{$img} = '';
11939:             $changes->{$role}{'images'}{$img} = 1;
11940:         }
11941:         if ($role eq 'login') {
11942:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
11943:                 $changes->{$role}{'showlogo'}{$img} = 1;
11944:             }
11945:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
11946:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
11947:                     $changes->{$role}{'alttext'}{$img} = 1;
11948:                 }
11949:             }
11950:         }
11951:     }
11952:     if ($confhash->{$role}{'font'}) {
11953:         $changes->{$role}{'font'} = 1;
11954:     }
11955: }
11956: 
11957: sub display_colorchgs {
11958:     my ($dom,$changes,$roles,$confhash) = @_;
11959:     my (%choices,$resulttext);
11960:     if (!grep(/^login$/,@{$roles})) {
11961:         $resulttext = &mt('Changes made:').'<br />';
11962:     }
11963:     foreach my $role (@{$roles}) {
11964:         if ($role eq 'login') {
11965:             %choices = &login_choices();
11966:         } else {
11967:             %choices = &color_font_choices();
11968:         }
11969:         if (ref($changes->{$role}) eq 'HASH') {
11970:             if ($role ne 'login') {
11971:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
11972:             }
11973:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
11974:                 if ($role ne 'login') {
11975:                     $resulttext .= '<ul>';
11976:                 }
11977:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
11978:                     if ($role ne 'login') {
11979:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
11980:                     }
11981:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
11982:                         if (($role eq 'login') && ($key eq 'showlogo')) {
11983:                             if ($confhash->{$role}{$key}{$item}) {
11984:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
11985:                             } else {
11986:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
11987:                             }
11988:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
11989:                             if ($confhash->{$role}{$key}{$item} ne '') {
11990:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
11991:                                                $confhash->{$role}{$key}{$item}).'</li>';
11992:                             } else {
11993:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
11994:                             }
11995:                         } elsif ($confhash->{$role}{$item} eq '') {
11996:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
11997:                         } else {
11998:                             my $newitem = $confhash->{$role}{$item};
11999:                             if ($key eq 'images') {
12000:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
12001:                             }
12002:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
12003:                         }
12004:                     }
12005:                     if ($role ne 'login') {
12006:                         $resulttext .= '</ul></li>';
12007:                     }
12008:                 } else {
12009:                     if ($confhash->{$role}{$key} eq '') {
12010:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
12011:                     } else {
12012:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
12013:                     }
12014:                 }
12015:                 if ($role ne 'login') {
12016:                     $resulttext .= '</ul>';
12017:                 }
12018:             }
12019:         }
12020:     }
12021:     return $resulttext;
12022: }
12023: 
12024: sub thumb_dimensions {
12025:     return ('200','50');
12026: }
12027: 
12028: sub check_dimensions {
12029:     my ($inputfile) = @_;
12030:     my ($fullwidth,$fullheight);
12031:     if ($inputfile =~ m|^[/\w.\-]+$|) {
12032:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
12033:             my $imageinfo = <PIPE>;
12034:             if (!close(PIPE)) {
12035:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
12036:             }
12037:             chomp($imageinfo);
12038:             my ($fullsize) = 
12039:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
12040:             if ($fullsize) {
12041:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
12042:             }
12043:         }
12044:     }
12045:     return ($fullwidth,$fullheight);
12046: }
12047: 
12048: sub check_configuser {
12049:     my ($uhome,$dom,$confname,$servadm) = @_;
12050:     my ($configuserok,%currroles);
12051:     if ($uhome eq 'no_host') {
12052:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
12053:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
12054:         $configuserok = 
12055:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
12056:                              $configpass,'','','','','',undef,$servadm);
12057:     } else {
12058:         $configuserok = 'ok';
12059:         %currroles = 
12060:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
12061:     }
12062:     return ($configuserok,%currroles);
12063: }
12064: 
12065: sub check_authorstatus {
12066:     my ($dom,$confname,%currroles) = @_;
12067:     my $author_ok;
12068:     if (!$currroles{':'.$dom.':au'}) {
12069:         my $start = time;
12070:         my $end = 0;
12071:         $author_ok = 
12072:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
12073:                                         'au',$end,$start,'','','domconfig');
12074:     } else {
12075:         $author_ok = 'ok';
12076:     }
12077:     return $author_ok;
12078: }
12079: 
12080: sub update_modify_urls {
12081:     my ($r,$modified) = @_;
12082:     if ((ref($modified) eq 'ARRAY') && (@{$modified})) {
12083:         push(@{$modified_urls},$modified);
12084:         unless ($registered_cleanup) {
12085:             my $handlers = $r->get_handlers('PerlCleanupHandler');
12086:             $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12087:             $registered_cleanup=1;
12088:         }
12089:     }
12090: }
12091: 
12092: sub notifysubscribed {
12093:     foreach my $targetsource (@{$modified_urls}){
12094:         next unless (ref($targetsource) eq 'ARRAY');
12095:         my ($target,$source)=@{$targetsource};
12096:         if ($source ne '') {
12097:             if (open(my $logfh,">>",$source.'.log')) {
12098:                 print $logfh "\nCleanup phase: Notifications\n";
12099:                 my @subscribed=&subscribed_hosts($target);
12100:                 foreach my $subhost (@subscribed) {
12101:                     print $logfh "\nNotifying host ".$subhost.':';
12102:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
12103:                     print $logfh $reply;
12104:                 }
12105:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
12106:                 foreach my $subhost (@subscribedmeta) {
12107:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
12108:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
12109:                                                         $subhost);
12110:                     print $logfh $reply;
12111:                 }
12112:                 print $logfh "\n============ Done ============\n";
12113:                 close($logfh);
12114:             }
12115:         }
12116:     }
12117:     return OK;
12118: }
12119: 
12120: sub subscribed_hosts {
12121:     my ($target) = @_;
12122:     my @subscribed;
12123:     if (open(my $fh,"<","$target.subscription")) {
12124:         while (my $subline=<$fh>) {
12125:             if ($subline =~ /^($match_lonid):/) {
12126:                 my $host = $1;
12127:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
12128:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
12129:                         push(@subscribed,$host);
12130:                     }
12131:                 }
12132:             }
12133:         }
12134:     }
12135:     return @subscribed;
12136: }
12137: 
12138: sub check_switchserver {
12139:     my ($dom,$confname) = @_;
12140:     my ($allowed,$switchserver,$home);
12141:     if ($confname eq '') {
12142:         $home = &Apache::lonnet::domain($dom,'primary');
12143:     } else {
12144:         $home = &Apache::lonnet::homeserver($confname,$dom);
12145:         if ($home eq 'no_host') {
12146:             $home = &Apache::lonnet::domain($dom,'primary');
12147:         }
12148:     }
12149:     my @ids=&Apache::lonnet::current_machine_ids();
12150:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
12151:     if (!$allowed) {
12152: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role='.
12153:                       &HTML::Entities::encode($env{'request.role'},'\'<>"&').
12154:                       '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
12155:     }
12156:     return $switchserver;
12157: }
12158: 
12159: sub modify_quotas {
12160:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12161:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
12162:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
12163:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
12164:         $validationfieldsref);
12165:     if ($action eq 'quotas') {
12166:         $context = 'tools'; 
12167:     } else {
12168:         $context = $action;
12169:     }
12170:     if ($context eq 'requestcourses') {
12171:         @usertools = ('official','unofficial','community','textbook','lti');
12172:         @options =('norequest','approval','validate','autolimit');
12173:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
12174:         %titles = &courserequest_titles();
12175:         $toolregexp = join('|',@usertools);
12176:         %conditions = &courserequest_conditions();
12177:         $confname = $dom.'-domainconfig';
12178:         my $servadm = $r->dir_config('lonAdmEMail');
12179:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12180:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
12181:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
12182:     } elsif ($context eq 'requestauthor') {
12183:         @usertools = ('author');
12184:         %titles = &authorrequest_titles();
12185:     } else {
12186:         @usertools = ('aboutme','blog','webdav','portfolio','timezone');
12187:         %titles = &tool_titles();
12188:     }
12189:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12190:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12191:     foreach my $key (keys(%env)) {
12192:         if ($context eq 'requestcourses') {
12193:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
12194:                 my $item = $1;
12195:                 my $type = $2;
12196:                 if ($type =~ /^limit_(.+)/) {
12197:                     $limithash{$item}{$1} = $env{$key};
12198:                 } else {
12199:                     $confhash{$item}{$type} = $env{$key};
12200:                 }
12201:             }
12202:         } elsif ($context eq 'requestauthor') {
12203:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
12204:                 $confhash{$1} = $env{$key};
12205:             }
12206:         } else {
12207:             if ($key =~ /^form\.quota_(.+)$/) {
12208:                 $confhash{'defaultquota'}{$1} = $env{$key};
12209:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
12210:                 $confhash{'authorquota'}{$1} = $env{$key};
12211:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
12212:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
12213:             }
12214:         }
12215:     }
12216:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12217:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
12218:         @approvalnotify = sort(@approvalnotify);
12219:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
12220:         my @crstypes = ('official','unofficial','community','textbook','lti');
12221:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
12222:         foreach my $type (@hasuniquecode) {
12223:             if (grep(/^\Q$type\E$/,@crstypes)) {
12224:                 $confhash{'uniquecode'}{$type} = 1;
12225:             }
12226:         }
12227:         my (%newbook,%allpos);
12228:         if ($context eq 'requestcourses') {
12229:             foreach my $type ('textbooks','templates') {
12230:                 @{$allpos{$type}} = (); 
12231:                 my $invalid;
12232:                 if ($type eq 'textbooks') {
12233:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
12234:                 } else {
12235:                     $invalid = &mt('Invalid LON-CAPA course for template');
12236:                 }
12237:                 if ($env{'form.'.$type.'_addbook'}) {
12238:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
12239:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
12240:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
12241:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
12242:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12243:                         } else {
12244:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
12245:                             my $position = $env{'form.'.$type.'_addbook_pos'};
12246:                             $position =~ s/\D+//g;
12247:                             if ($position ne '') {
12248:                                 $allpos{$type}[$position] = $newbook{$type};
12249:                             }
12250:                         }
12251:                     } else {
12252:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12253:                     }
12254:                 }
12255:             } 
12256:         }
12257:         if (ref($domconfig{$action}) eq 'HASH') {
12258:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
12259:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
12260:                     $changes{'notify'}{'approval'} = 1;
12261:                 }
12262:             } else {
12263:                 if ($confhash{'notify'}{'approval'}) {
12264:                     $changes{'notify'}{'approval'} = 1;
12265:                 }
12266:             }
12267:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
12268:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
12269:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
12270:                         unless ($confhash{'uniquecode'}{$crstype}) {
12271:                             $changes{'uniquecode'} = 1;
12272:                         }
12273:                     }
12274:                     unless ($changes{'uniquecode'}) {
12275:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
12276:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
12277:                                 $changes{'uniquecode'} = 1;
12278:                             }
12279:                         }
12280:                     }
12281:                } else {
12282:                    $changes{'uniquecode'} = 1;
12283:                }
12284:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
12285:                 $changes{'uniquecode'} = 1;
12286:             }
12287:             if ($context eq 'requestcourses') {
12288:                 foreach my $type ('textbooks','templates') {
12289:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
12290:                         my %deletions;
12291:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
12292:                         if (@todelete) {
12293:                             map { $deletions{$_} = 1; } @todelete;
12294:                         }
12295:                         my %imgdeletions;
12296:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
12297:                         if (@todeleteimages) {
12298:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
12299:                         }
12300:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
12301:                         for (my $i=0; $i<=$maxnum; $i++) {
12302:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
12303:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
12304:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
12305:                                 if ($deletions{$key}) {
12306:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
12307:                                         #FIXME need to obsolete item in RES space
12308:                                     }
12309:                                     next;
12310:                                 } else {
12311:                                     my $newpos = $env{'form.'.$itemid};
12312:                                     $newpos =~ s/\D+//g;
12313:                                     foreach my $item ('subject','title','publisher','author') {
12314:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12315:                                                  ($type eq 'templates'));
12316:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
12317:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
12318:                                             $changes{$type}{$key} = 1;
12319:                                         }
12320:                                     }
12321:                                     $allpos{$type}[$newpos] = $key;
12322:                                 }
12323:                                 if ($imgdeletions{$key}) {
12324:                                     $changes{$type}{$key} = 1;
12325:                                     #FIXME need to obsolete item in RES space
12326:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
12327:                                     my ($cdom,$cnum) = split(/_/,$key);
12328:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12329:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12330:                                     } else {
12331:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
12332:                                                                                       $cdom,$cnum,$type,$configuserok,
12333:                                                                                       $switchserver,$author_ok);
12334:                                         if ($imgurl) {
12335:                                             $confhash{$type}{$key}{'image'} = $imgurl;
12336:                                             $changes{$type}{$key} = 1; 
12337:                                         }
12338:                                         if ($error) {
12339:                                             &Apache::lonnet::logthis($error);
12340:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12341:                                         }
12342:                                     }
12343:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
12344:                                     $confhash{$type}{$key}{'image'} = 
12345:                                         $domconfig{$action}{$type}{$key}{'image'};
12346:                                 }
12347:                             }
12348:                         }
12349:                     }
12350:                 }
12351:             }
12352:         } else {
12353:             if ($confhash{'notify'}{'approval'}) {
12354:                 $changes{'notify'}{'approval'} = 1;
12355:             }
12356:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
12357:                 $changes{'uniquecode'} = 1;
12358:             }
12359:         }
12360:         if ($context eq 'requestcourses') {
12361:             foreach my $type ('textbooks','templates') {
12362:                 if ($newbook{$type}) {
12363:                     $changes{$type}{$newbook{$type}} = 1;
12364:                     foreach my $item ('subject','title','publisher','author') {
12365:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12366:                                  ($type eq 'template'));
12367:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
12368:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
12369:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
12370:                         }
12371:                     }
12372:                     if ($type eq 'textbooks') {
12373:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
12374:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
12375:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12376:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12377:                             } else {
12378:                                 my ($imageurl,$error) =
12379:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
12380:                                                             $configuserok,$switchserver,$author_ok);
12381:                                 if ($imageurl) {
12382:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
12383:                                 }
12384:                                 if ($error) {
12385:                                     &Apache::lonnet::logthis($error);
12386:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12387:                                 }
12388:                             }
12389:                         }
12390:                     }
12391:                 }
12392:                 if (@{$allpos{$type}} > 0) {
12393:                     my $idx = 0;
12394:                     foreach my $item (@{$allpos{$type}}) {
12395:                         if ($item ne '') {
12396:                             $confhash{$type}{$item}{'order'} = $idx;
12397:                             if (ref($domconfig{$action}) eq 'HASH') {
12398:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
12399:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
12400:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
12401:                                             $changes{$type}{$item} = 1;
12402:                                         }
12403:                                     }
12404:                                 }
12405:                             }
12406:                             $idx ++;
12407:                         }
12408:                     }
12409:                 }
12410:             }
12411:             if (ref($validationitemsref) eq 'ARRAY') {
12412:                 foreach my $item (@{$validationitemsref}) {
12413:                     if ($item eq 'fields') {
12414:                         my @changed;
12415:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
12416:                         if (@{$confhash{'validation'}{$item}} > 0) {
12417:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
12418:                         }
12419:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12420:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12421:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
12422:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
12423:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
12424:                                 } else {
12425:                                     @changed = @{$confhash{'validation'}{$item}};
12426:                                 }
12427:                             } else {
12428:                                 @changed = @{$confhash{'validation'}{$item}};
12429:                             }
12430:                         } else {
12431:                             @changed = @{$confhash{'validation'}{$item}};
12432:                         }
12433:                         if (@changed) {
12434:                             if ($confhash{'validation'}{$item}) {
12435:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
12436:                             } else {
12437:                                 $changes{'validation'}{$item} = &mt('None');
12438:                             }
12439:                         }
12440:                     } else {
12441:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
12442:                         if ($item eq 'markup') {
12443:                             if ($env{'form.requestcourses_validation_'.$item}) {
12444:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
12445:                             }
12446:                         }
12447:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12448:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12449:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
12450:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12451:                                 }
12452:                             } else {
12453:                                 if ($confhash{'validation'}{$item} ne '') {
12454:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12455:                                 }
12456:                             }
12457:                         } else {
12458:                             if ($confhash{'validation'}{$item} ne '') {
12459:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12460:                             }
12461:                         }
12462:                     }
12463:                 }
12464:             }
12465:             if ($env{'form.validationdc'}) {
12466:                 my $newval = $env{'form.validationdc'};
12467:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
12468:                 if (exists($domcoords{$newval})) {
12469:                     $confhash{'validation'}{'dc'} = $newval;
12470:                 }
12471:             }
12472:             if (ref($confhash{'validation'}) eq 'HASH') {
12473:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12474:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12475:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
12476:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
12477:                                 if ($confhash{'validation'}{'dc'} eq '') {
12478:                                     $changes{'validation'}{'dc'} = &mt('None');
12479:                                 } else {
12480:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12481:                                 }
12482:                             }
12483:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
12484:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12485:                         }
12486:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
12487:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12488:                     }
12489:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
12490:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12491:                 }
12492:             } else {
12493:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12494:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12495:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
12496:                             $changes{'validation'}{'dc'} = &mt('None');
12497:                         }
12498:                     }
12499:                 }
12500:             }
12501:         }
12502:     } else {
12503:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
12504:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
12505:     }
12506:     foreach my $item (@usertools) {
12507:         foreach my $type (@{$types},'default','_LC_adv') {
12508:             my $unset; 
12509:             if ($context eq 'requestcourses') {
12510:                 $unset = '0';
12511:                 if ($type eq '_LC_adv') {
12512:                     $unset = '';
12513:                 }
12514:                 if ($confhash{$item}{$type} eq 'autolimit') {
12515:                     $confhash{$item}{$type} .= '=';
12516:                     unless ($limithash{$item}{$type} =~ /\D/) {
12517:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
12518:                     }
12519:                 }
12520:             } elsif ($context eq 'requestauthor') {
12521:                 $unset = '0';
12522:                 if ($type eq '_LC_adv') {
12523:                     $unset = '';
12524:                 }
12525:             } else {
12526:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
12527:                     $confhash{$item}{$type} = 1;
12528:                 } else {
12529:                     $confhash{$item}{$type} = 0;
12530:                 }
12531:             }
12532:             if (ref($domconfig{$action}) eq 'HASH') {
12533:                 if ($action eq 'requestauthor') {
12534:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
12535:                         $changes{$type} = 1;
12536:                     }
12537:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
12538:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
12539:                         $changes{$item}{$type} = 1;
12540:                     }
12541:                 } else {
12542:                     if ($context eq 'requestcourses') {
12543:                         if ($confhash{$item}{$type} ne $unset) {
12544:                             $changes{$item}{$type} = 1;
12545:                         }
12546:                     } else {
12547:                         if (!$confhash{$item}{$type}) {
12548:                             $changes{$item}{$type} = 1;
12549:                         }
12550:                     }
12551:                 }
12552:             } else {
12553:                 if ($context eq 'requestcourses') {
12554:                     if ($confhash{$item}{$type} ne $unset) {
12555:                         $changes{$item}{$type} = 1;
12556:                     }
12557:                 } elsif ($context eq 'requestauthor') {
12558:                     if ($confhash{$type} ne $unset) {
12559:                         $changes{$type} = 1;
12560:                     }
12561:                 } else {
12562:                     if (!$confhash{$item}{$type}) {
12563:                         $changes{$item}{$type} = 1;
12564:                     }
12565:                 }
12566:             }
12567:         }
12568:     }
12569:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12570:         if (ref($domconfig{'quotas'}) eq 'HASH') {
12571:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
12572:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
12573:                     if (exists($confhash{'defaultquota'}{$key})) {
12574:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
12575:                             $changes{'defaultquota'}{$key} = 1;
12576:                         }
12577:                     } else {
12578:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
12579:                     }
12580:                 }
12581:             } else {
12582:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
12583:                     if (exists($confhash{'defaultquota'}{$key})) {
12584:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
12585:                             $changes{'defaultquota'}{$key} = 1;
12586:                         }
12587:                     } else {
12588:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
12589:                     }
12590:                 }
12591:             }
12592:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
12593:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
12594:                     if (exists($confhash{'authorquota'}{$key})) {
12595:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
12596:                             $changes{'authorquota'}{$key} = 1;
12597:                         }
12598:                     } else {
12599:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
12600:                     }
12601:                 }
12602:             }
12603:         }
12604:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
12605:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
12606:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
12607:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
12608:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
12609:                             $changes{'defaultquota'}{$key} = 1;
12610:                         }
12611:                     } else {
12612:                         if (!exists($domconfig{'quotas'}{$key})) {
12613:                             $changes{'defaultquota'}{$key} = 1;
12614:                         }
12615:                     }
12616:                 } else {
12617:                     $changes{'defaultquota'}{$key} = 1;
12618:                 }
12619:             }
12620:         }
12621:         if (ref($confhash{'authorquota'}) eq 'HASH') {
12622:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
12623:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
12624:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
12625:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
12626:                             $changes{'authorquota'}{$key} = 1;
12627:                         }
12628:                     } else {
12629:                         $changes{'authorquota'}{$key} = 1;
12630:                     }
12631:                 } else {
12632:                     $changes{'authorquota'}{$key} = 1;
12633:                 }
12634:             }
12635:         }
12636:     }
12637: 
12638:     if ($context eq 'requestauthor') {
12639:         $domdefaults{'requestauthor'} = \%confhash;
12640:     } else {
12641:         foreach my $key (keys(%confhash)) {
12642:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
12643:                 $domdefaults{$key} = $confhash{$key};
12644:             }
12645:         }
12646:     }
12647: 
12648:     my %quotahash = (
12649:                       $action => { %confhash }
12650:                     );
12651:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
12652:                                              $dom);
12653:     if ($putresult eq 'ok') {
12654:         if (keys(%changes) > 0) {
12655:             my $cachetime = 24*60*60;
12656:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12657:             if (ref($lastactref) eq 'HASH') {
12658:                 $lastactref->{'domdefaults'} = 1;
12659:             }
12660:             $resulttext = &mt('Changes made:').'<ul>';
12661:             unless (($context eq 'requestcourses') ||
12662:                     ($context eq 'requestauthor')) {
12663:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
12664:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
12665:                     foreach my $type (@{$types},'default') {
12666:                         if (defined($changes{'defaultquota'}{$type})) {
12667:                             my $typetitle = $usertypes->{$type};
12668:                             if ($type eq 'default') {
12669:                                 $typetitle = $othertitle;
12670:                             }
12671:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
12672:                         }
12673:                     }
12674:                     $resulttext .= '</ul></li>';
12675:                 }
12676:                 if (ref($changes{'authorquota'}) eq 'HASH') {
12677:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
12678:                     foreach my $type (@{$types},'default') {
12679:                         if (defined($changes{'authorquota'}{$type})) {
12680:                             my $typetitle = $usertypes->{$type};
12681:                             if ($type eq 'default') {
12682:                                 $typetitle = $othertitle;
12683:                             }
12684:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
12685:                         }
12686:                     }
12687:                     $resulttext .= '</ul></li>';
12688:                 }
12689:             }
12690:             my %newenv;
12691:             foreach my $item (@usertools) {
12692:                 my (%haschgs,%inconf);
12693:                 if ($context eq 'requestauthor') {
12694:                     %haschgs = %changes;
12695:                     %inconf = %confhash;
12696:                 } else {
12697:                     if (ref($changes{$item}) eq 'HASH') {
12698:                         %haschgs = %{$changes{$item}};
12699:                     }
12700:                     if (ref($confhash{$item}) eq 'HASH') {
12701:                         %inconf = %{$confhash{$item}};
12702:                     }
12703:                 }
12704:                 if (keys(%haschgs) > 0) {
12705:                     my $newacc = 
12706:                         &Apache::lonnet::usertools_access($env{'user.name'},
12707:                                                           $env{'user.domain'},
12708:                                                           $item,'reload',$context);
12709:                     if (($context eq 'requestcourses') ||
12710:                         ($context eq 'requestauthor')) {
12711:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
12712:                             $newenv{'environment.canrequest.'.$item} = $newacc;
12713:                         }
12714:                     } else {
12715:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
12716:                             $newenv{'environment.availabletools.'.$item} = $newacc;
12717:                         }
12718:                     }
12719:                     unless ($context eq 'requestauthor') {
12720:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
12721:                     }
12722:                     foreach my $type (@{$types},'default','_LC_adv') {
12723:                         if ($haschgs{$type}) {
12724:                             my $typetitle = $usertypes->{$type};
12725:                             if ($type eq 'default') {
12726:                                 $typetitle = $othertitle;
12727:                             } elsif ($type eq '_LC_adv') {
12728:                                 $typetitle = 'LON-CAPA Advanced Users'; 
12729:                             }
12730:                             if ($inconf{$type}) {
12731:                                 if ($context eq 'requestcourses') {
12732:                                     my $cond;
12733:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
12734:                                         if ($1 eq '') {
12735:                                             $cond = &mt('(Automatic processing of any request).');
12736:                                         } else {
12737:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
12738:                                         }
12739:                                     } else { 
12740:                                         $cond = $conditions{$inconf{$type}};
12741:                                     }
12742:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
12743:                                 } elsif ($context eq 'requestauthor') {
12744:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
12745:                                                              $titles{$inconf{$type}},$typetitle);
12746: 
12747:                                 } else {
12748:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
12749:                                 }
12750:                             } else {
12751:                                 if ($type eq '_LC_adv') {
12752:                                     if ($inconf{$type} eq '0') {
12753:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
12754:                                     } else { 
12755:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
12756:                                     }
12757:                                 } else {
12758:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
12759:                                 }
12760:                             }
12761:                         }
12762:                     }
12763:                     unless ($context eq 'requestauthor') {
12764:                         $resulttext .= '</ul></li>';
12765:                     }
12766:                 }
12767:             }
12768:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
12769:                 if (ref($changes{'notify'}) eq 'HASH') {
12770:                     if ($changes{'notify'}{'approval'}) {
12771:                         if (ref($confhash{'notify'}) eq 'HASH') {
12772:                             if ($confhash{'notify'}{'approval'}) {
12773:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
12774:                             } else {
12775:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
12776:                             }
12777:                         }
12778:                     }
12779:                 }
12780:             }
12781:             if ($action eq 'requestcourses') {
12782:                 my @offon = ('off','on');
12783:                 if ($changes{'uniquecode'}) {
12784:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
12785:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
12786:                         $resulttext .= '<li>'.
12787:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
12788:                                        '</li>';
12789:                     } else {
12790:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
12791:                                        '</li>';
12792:                     }
12793:                 }
12794:                 foreach my $type ('textbooks','templates') {
12795:                     if (ref($changes{$type}) eq 'HASH') {
12796:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
12797:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
12798:                             my %coursehash = &Apache::lonnet::coursedescription($key);
12799:                             my $coursetitle = $coursehash{'description'};
12800:                             my $position = $confhash{$type}{$key}{'order'} + 1;
12801:                             $resulttext .= '<li>';
12802:                             foreach my $item ('subject','title','publisher','author') {
12803:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
12804:                                          ($type eq 'templates'));
12805:                                 my $name = $item.':';
12806:                                 $name =~ s/^(\w)/\U$1/;
12807:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
12808:                             }
12809:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
12810:                             if ($type eq 'textbooks') {
12811:                                 if ($confhash{$type}{$key}{'image'}) {
12812:                                     $resulttext .= ' '.&mt('Image: [_1]',
12813:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
12814:                                                    ' alt="Textbook cover" />').'<br />';
12815:                                 }
12816:                             }
12817:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
12818:                         }
12819:                         $resulttext .= '</ul></li>';
12820:                     }
12821:                 }
12822:                 if (ref($changes{'validation'}) eq 'HASH') {
12823:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
12824:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
12825:                         foreach my $item (@{$validationitemsref}) {
12826:                             if (exists($changes{'validation'}{$item})) {
12827:                                 if ($item eq 'markup') {
12828:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
12829:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
12830:                                 } else {
12831:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
12832:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
12833:                                 }
12834:                             }
12835:                         }
12836:                         if (exists($changes{'validation'}{'dc'})) {
12837:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
12838:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
12839:                         }
12840:                     }
12841:                 }
12842:             }
12843:             $resulttext .= '</ul>';
12844:             if (keys(%newenv)) {
12845:                 &Apache::lonnet::appenv(\%newenv);
12846:             }
12847:         } else {
12848:             if ($context eq 'requestcourses') {
12849:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
12850:             } elsif ($context eq 'requestauthor') {
12851:                 $resulttext = &mt('No changes made to rights to request author space.');
12852:             } else {
12853:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
12854:             }
12855:         }
12856:     } else {
12857:         $resulttext = '<span class="LC_error">'.
12858: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12859:     }
12860:     if ($errors) {
12861:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
12862:                        '<ul>'.$errors.'</ul></p>';
12863:     }
12864:     return $resulttext;
12865: }
12866: 
12867: sub process_textbook_image {
12868:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
12869:     my $filename = $env{'form.'.$caller.'.filename'};
12870:     my ($error,$url);
12871:     my ($width,$height) = (50,50);
12872:     if ($configuserok eq 'ok') {
12873:         if ($switchserver) {
12874:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
12875:                          $switchserver);
12876:         } elsif ($author_ok eq 'ok') {
12877:             my $modified = [];
12878:             my ($result,$imageurl) =
12879:                 &Apache::lonconfigsettings::publishlogo($r,'upload',$caller,$dom,$confname,
12880:                                                         "$type/$cdom/$cnum/cover",$width,$height,
12881:                                                         '',$modified);
12882:             if ($result eq 'ok') {
12883:                 $url = $imageurl;
12884:                 &update_modify_urls($r,$modified);
12885:             } else {
12886:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
12887:             }
12888:         } else {
12889:             $error = &mt("Upload of [_1] failed because an author role could not be assigned to a Domain Configuration user ([_2]) in domain: [_3].  Error was: [_4].",$filename,$confname,$dom,$author_ok);
12890:         }
12891:     } else {
12892:         $error = &mt("Upload of [_1] failed because a Domain Configuration user ([_2]) could not be created in domain: [_3].  Error was: [_4].",$filename,$confname,$dom,$configuserok);
12893:     }
12894:     return ($url,$error);
12895: }
12896: 
12897: sub modify_ltitools {
12898:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12899:     my (%currtoolsec,%secchanges,%newtoolsec,%newkeyset);
12900:     &fetch_secrets($dom,'toolsec',\%domconfig,\%currtoolsec,\%secchanges,\%newtoolsec,\%newkeyset);
12901: 
12902:     my $confname = $dom.'-domainconfig';
12903:     my $servadm = $r->dir_config('lonAdmEMail');
12904:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12905: 
12906:     my ($resulttext,$ltitoolsoutput,$is_home,$errors,%ltitoolschg,%newtoolsenc,%newltitools);
12907:     my $toolserror =
12908:         &Apache::courseprefs::process_ltitools($r,$dom,$confname,$domconfig{'ltitools'},\%ltitoolschg,'domain',
12909:                                                $lastactref,$configuserok,$switchserver,$author_ok);
12910: 
12911:     my $home = &Apache::lonnet::domain($dom,'primary');
12912:     unless (($home eq 'no_host') || ($home eq '')) {
12913:         my @ids=&Apache::lonnet::current_machine_ids();
12914:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; last; } }
12915:     }
12916: 
12917:     if (keys(%ltitoolschg)) {
12918:         foreach my $id (keys(%ltitoolschg)) {
12919:             if (ref($ltitoolschg{$id}) eq 'HASH') {
12920:                 foreach my $inner (keys(%{$ltitoolschg{$id}})) {
12921:                     if (($inner eq 'secret') || ($inner eq 'key')) {
12922:                         if ($is_home) {
12923:                             $newtoolsenc{$id}{$inner} = $ltitoolschg{$id}{$inner};
12924:                         }
12925:                     }
12926:                 }
12927:             }
12928:         }
12929:         $ltitoolsoutput = &Apache::courseprefs::store_ltitools($dom,'','domain',\%ltitoolschg,$domconfig{'ltitools'});
12930:         if (keys(%ltitoolschg)) {
12931:             %newltitools = %ltitoolschg;
12932:         }
12933:     }
12934:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
12935:         foreach my $id (%{$domconfig{'ltitools'}}) {
12936:             next if ($id !~ /^\d+$/);
12937:             unless (exists($ltitoolschg{$id})) {
12938:                 if (ref($domconfig{'ltitools'}{$id}) eq 'HASH') {
12939:                     foreach my $inner (keys(%{$domconfig{'ltitools'}{$id}})) {
12940:                         if (($inner eq 'secret') || ($inner eq 'key')) {
12941:                             if ($is_home) {
12942:                                 $newtoolsenc{$id}{$inner} = $domconfig{'ltitools'}{$id}{$inner};
12943:                             }
12944:                         } else {
12945:                             $newltitools{$id}{$inner} = $domconfig{'ltitools'}{$id}{$inner};
12946:                         }
12947:                     }
12948:                 } else {
12949:                     $newltitools{$id} = $domconfig{'ltitools'}{$id};
12950:                 }
12951:             }
12952:         }
12953:     }
12954:     if ($toolserror) {
12955:         $errors = '<li>'.$toolserror.'</li>';
12956:     }
12957:     if ((keys(%ltitoolschg) == 0) && (keys(%secchanges) == 0)) {
12958:         $resulttext = &mt('No changes made.');
12959:         if ($errors) {
12960:             $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12961:                                  $errors.'</ul>';
12962:         }
12963:         return $resulttext;
12964:     }
12965:     my %ltitoolshash = (
12966:                           $action => { %newltitools }
12967:                        );
12968:     if (keys(%secchanges)) {
12969:         $ltitoolshash{'toolsec'} = \%newtoolsec;
12970:     }
12971:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,$dom);
12972:     if ($putresult eq 'ok') {
12973:         my %keystore;
12974:         if ($is_home) {
12975:             my %toolsenchash = (
12976:                                    $action => { %newtoolsenc }
12977:                                );
12978:             &Apache::lonnet::put_dom('encconfig',\%toolsenchash,$dom,undef,1);
12979:             my $cachetime = 24*60*60;
12980:             &Apache::lonnet::do_cache_new('ltitoolsenc',$dom,\%newtoolsenc,$cachetime);
12981:             &store_security($dom,'ltitools',\%secchanges,\%newkeyset,\%keystore,$lastactref);
12982:         }
12983:         $resulttext = &mt('Changes made:').'<ul>';
12984:         if (keys(%secchanges) > 0) {
12985:             $resulttext .= &lti_security_results($dom,'ltitools',\%secchanges,\%newtoolsec,\%newkeyset,\%keystore);
12986:         }
12987:         if (keys(%ltitoolschg) > 0) {
12988:             $resulttext .= $ltitoolsoutput;
12989:         }
12990:         my $cachetime = 24*60*60;
12991:         &Apache::lonnet::do_cache_new('ltitools',$dom,\%newltitools,$cachetime);
12992:         if (ref($lastactref) eq 'HASH') {
12993:             $lastactref->{'ltitools'} = 1;
12994:         }
12995:     } else {
12996:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
12997:     }
12998:     if ($errors) {
12999:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
13000:                        $errors.'</ul></p>';
13001:     }
13002:     return $resulttext;
13003: }
13004: 
13005: sub fetch_secrets {
13006:     my ($dom,$context,$domconfig,$currsec,$secchanges,$newsec,$newkeyset) = @_;
13007:     my %keyset;
13008:     %{$currsec} = ();
13009:     $newsec->{'private'}{'keys'} = [];
13010:     $newsec->{'encrypt'} = {};
13011:     $newsec->{'rules'} = {};
13012:     if ($context eq 'ltisec') {
13013:         $newsec->{'linkprot'} = {};
13014:     }
13015:     if (ref($domconfig->{$context}) eq 'HASH') {
13016:         %{$currsec} = %{$domconfig->{$context}};
13017:         if ($context eq 'ltisec') {
13018:             if (ref($currsec->{'linkprot'}) eq 'HASH') {
13019:                 foreach my $id (keys(%{$currsec->{'linkprot'}})) {
13020:                     unless ($id =~ /^\d+$/) {
13021:                         delete($currsec->{'linkprot'}{$id});
13022:                     }
13023:                 }
13024:             }
13025:         }
13026:         if (ref($currsec->{'private'}) eq 'HASH') {
13027:             if (ref($currsec->{'private'}{'keys'}) eq 'ARRAY') {
13028:                 $newsec->{'private'}{'keys'} = $currsec->{'private'}{'keys'};
13029:                 map { $keyset{$_} = 1; } @{$currsec->{'private'}{'keys'}};
13030:             }
13031:         }
13032:     }
13033:     my @items= ('crs','dom');
13034:     if ($context eq 'ltisec') {
13035:         push(@items,'consumers');
13036:     }
13037:     foreach my $item (@items) {
13038:         my $formelement;
13039:         if (($context eq 'toolsec') || ($item eq 'consumers')) {
13040:             $formelement = 'form.'.$context.'_'.$item;
13041:         } else {
13042:             $formelement = 'form.'.$context.'_'.$item.'linkprot';
13043:         }
13044:         if ($env{$formelement}) {
13045:             $newsec->{'encrypt'}{$item} = 1;
13046:             if (ref($currsec->{'encrypt'}) eq 'HASH') {
13047:                 unless ($currsec->{'encrypt'}{$item}) {
13048:                     $secchanges->{'encrypt'} = 1;
13049:                 }
13050:             } else {
13051:                 $secchanges->{'encrypt'} = 1;
13052:             }
13053:         } elsif (ref($currsec->{'encrypt'}) eq 'HASH') {
13054:             if ($currsec->{'encrypt'}{$item}) {
13055:                 $secchanges->{'encrypt'} = 1;
13056:             }
13057:         }
13058:     }
13059:     my $secrets;
13060:     if ($context eq 'ltisec') {
13061:         $secrets = 'ltisecrets';
13062:     } else {
13063:         $secrets = 'toolsecrets';
13064:     }
13065:     unless (exists($currsec->{'rules'})) {
13066:         $currsec->{'rules'} = {};
13067:     }
13068:     &password_rule_changes($secrets,$newsec->{'rules'},$currsec->{'rules'},$secchanges);
13069: 
13070:     my @ids=&Apache::lonnet::current_machine_ids();
13071:     my %servers = &Apache::lonnet::get_servers($dom,'library');
13072: 
13073:     foreach my $hostid (keys(%servers)) {
13074:         if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
13075:             my $keyitem = 'form.'.$context.'_privkey_'.$hostid;
13076:             if (exists($env{$keyitem})) {
13077:                 $env{$keyitem} =~ s/(`)/'/g;
13078:                 if ($keyset{$hostid}) {
13079:                     if ($env{'form.'.$context.'_changeprivkey_'.$hostid}) {
13080:                         if ($env{$keyitem} ne '') {
13081:                             $secchanges->{'private'} = 1;
13082:                             $newkeyset->{$hostid} = $env{$keyitem};
13083:                         }
13084:                     }
13085:                 } elsif ($env{$keyitem} ne '') {
13086:                     unless (grep(/^\Q$hostid\E$/,@{$newsec->{'private'}{'keys'}})) {
13087:                         push(@{$newsec->{'private'}{'keys'}},$hostid);
13088:                     }
13089:                     $secchanges->{'private'} = 1;
13090:                     $newkeyset->{$hostid} = $env{$keyitem};
13091:                 }
13092:             }
13093:         }
13094:     }
13095: }
13096: 
13097: sub store_security {
13098:     my ($dom,$context,$secchanges,$newkeyset,$keystore) = @_;
13099:     return unless ((ref($secchanges) eq 'HASH') && (ref($newkeyset) eq 'HASH') &&
13100:                    (ref($keystore) eq 'HASH'));
13101:     if (keys(%{$secchanges})) {
13102:         if ($secchanges->{'private'}) {
13103:             my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
13104:             foreach my $hostid (keys(%{$newkeyset})) {
13105:                 my $storehash = {
13106:                                    key => $newkeyset->{$hostid},
13107:                                    who => $env{'user.name'}.':'.$env{'user.domain'},
13108:                                 };
13109:                 $keystore->{$hostid} = &Apache::lonnet::store_dom($storehash,$context,'private',
13110:                                                                   $dom,$hostid);
13111:             }
13112:         }
13113:     }
13114: }
13115: 
13116: sub lti_security_results {
13117:     my ($dom,$context,$secchanges,$newsec,$newkeyset,$keystore) = @_;
13118:     my $output;
13119:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
13120:     my $needs_update;
13121:     foreach my $item (keys(%{$secchanges})) {
13122:         if ($item eq 'encrypt') {
13123:             $needs_update = 1;
13124:             my %encrypted;
13125:             if ($context eq 'lti') {
13126:                 %encrypted = (
13127:                               crs  => {
13128:                                         on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
13129:                                         off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
13130:                                       },
13131:                               dom => {
13132:                                        on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
13133:                                        off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
13134:                                      },
13135:                               consumers => {
13136:                                              on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
13137:                                              off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
13138:                                            },
13139:                              );
13140:             } else {
13141:                 %encrypted = (
13142:                               crs  => {
13143:                                         on => &mt('Encryption of stored external tool secrets defined in courses enabled'),
13144:                                         off => &mt('Encryption of stored external tool secrets defined in courses disabled'),
13145:                                       },
13146:                               dom => {
13147:                                        on => &mt('Encryption of stored external tool secrets defined in domain enabled'),
13148:                                        off => &mt('Encryption of stored external tool secrets defined in domain disabled'),
13149:                                      },
13150:                              );
13151: 
13152:             }
13153:             my @types= ('crs','dom');
13154:             if ($context eq 'lti') {
13155:                 foreach my $type (@types) {
13156:                     undef($domdefaults{'linkprotenc_'.$type});
13157:                 }
13158:                 push(@types,'consumers');
13159:                 undef($domdefaults{'ltienc_consumers'});
13160:             } elsif ($context eq 'ltitools') {
13161:                 foreach my $type (@types) {
13162:                     undef($domdefaults{'toolenc_'.$type});
13163:                 }
13164:             }
13165:             foreach my $type (@types) {
13166:                 my $shown = $encrypted{$type}{'off'};
13167:                 if (ref($newsec->{$item}) eq 'HASH') {
13168:                     if ($newsec->{$item}{$type}) {
13169:                         if ($context eq 'lti') {
13170:                             if ($type eq 'consumers') {
13171:                                 $domdefaults{'ltienc_consumers'} = 1;
13172:                             } else {
13173:                                 $domdefaults{'linkprotenc_'.$type} = 1;
13174:                             }
13175:                         } elsif ($context eq 'ltitools') {
13176:                             $domdefaults{'toolenc_'.$type} = 1;
13177:                         }
13178:                         $shown = $encrypted{$type}{'on'};
13179:                     }
13180:                 }
13181:                 $output .= '<li>'.$shown.'</li>';
13182:             }
13183:         } elsif ($item eq 'rules') {
13184:             my %titles = &Apache::lonlocal::texthash(
13185:                                       min   => 'Minimum password length',
13186:                                       max   => 'Maximum password length',
13187:                                       chars => 'Required characters',
13188:                          );
13189:             foreach my $rule ('min','max') {
13190:                 if ($newsec->{rules}{$rule} eq '') {
13191:                     if ($rule eq 'min') {
13192:                         $output .= '<li>'.&mt('[_1] not set.',$titles{$rule});
13193:                                    ' '.&mt('Default of [_1] will be used',
13194:                                            $Apache::lonnet::passwdmin).'</li>';
13195:                     } else {
13196:                         $output .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
13197:                     }
13198:                 } else {
13199:                     $output .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newsec->{rules}{$rule}).'</li>';
13200:                 }
13201:             }
13202:             if (ref($newsec->{'rules'}{'chars'}) eq 'ARRAY') {
13203:                 if (@{$newsec->{'rules'}{'chars'}} > 0) {
13204:                     my %rulenames = &Apache::lonlocal::texthash(
13205:                                              uc => 'At least one upper case letter',
13206:                                              lc => 'At least one lower case letter',
13207:                                              num => 'At least one number',
13208:                                              spec => 'At least one non-alphanumeric',
13209:                                     );
13210:                     my $needed = '<ul><li>'.
13211:                                  join('</li><li>',map {$rulenames{$_} } @{$newsec->{'rules'}{'chars'}}).
13212:                                  '</li></ul>';
13213:                     $output .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
13214:                 } else {
13215:                     $output .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
13216:                 }
13217:             } else {
13218:                 $output .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
13219:             }
13220:         } elsif ($item eq 'private') {
13221:             $needs_update = 1;
13222:             if ($context eq 'lti') {
13223:                 undef($domdefaults{'ltiprivhosts'});
13224:             } elsif ($context eq 'ltitools') {
13225:                 undef($domdefaults{'toolprivhosts'});
13226:             }
13227:             if (keys(%{$newkeyset})) {
13228:                 my @privhosts;
13229:                 foreach my $hostid (sort(keys(%{$newkeyset}))) {
13230:                     if ($keystore->{$hostid} eq 'ok') {
13231:                         $output .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
13232:                         unless (grep(/^\Q$hostid\E$/,@privhosts)) {
13233:                             push(@privhosts,$hostid);
13234:                         }
13235:                     }
13236:                 }
13237:                 if (@privhosts) {
13238:                     if ($context eq 'lti') {
13239:                         $domdefaults{'ltiprivhosts'} = \@privhosts;
13240:                     } elsif ($context eq 'ltitools') {
13241:                         $domdefaults{'toolprivhosts'} = \@privhosts;
13242:                     }
13243:                 }
13244:             }
13245:         } elsif ($item eq 'linkprot') {
13246:             next;
13247:         }
13248:     }
13249:     if ($needs_update) {
13250:         my $cachetime = 24*60*60;
13251:         &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13252:     }
13253:     return $output;
13254: }
13255: 
13256: sub modify_lti {
13257:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13258:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13259:     my ($newid,@allpos,%changes,%confhash,%ltienc,$errors,$resulttext);
13260:     my (%posslti,%posslticrs,%posscrstype);
13261:     my @courseroles = ('cc','in','ta','ep','st');
13262:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
13263:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
13264:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
13265:     my %coursetypetitles = &Apache::lonlocal::texthash (
13266:                                official   => 'Official',
13267:                                unofficial => 'Unofficial',
13268:                                community  => 'Community',
13269:                                textbook   => 'Textbook',
13270:                                placement  => 'Placement Test',
13271:                                lti        => 'LTI Provider',
13272:     );
13273:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
13274:     my %lt = &lti_names();
13275:     map { $posslti{$_} = 1; } @ltiroles;
13276:     map { $posslticrs{$_} = 1; } @lticourseroles;
13277:     map { $posscrstype{$_} = 1; } @coursetypes;
13278: 
13279:     my %menutitles = &ltimenu_titles();
13280:     my (%currltisec,%secchanges,%newltisec,%newltienc,%newkeyset);
13281: 
13282:     &fetch_secrets($dom,'ltisec',\%domconfig,\%currltisec,\%secchanges,\%newltisec,\%newkeyset);
13283: 
13284:     my (%linkprotchg,$linkprotoutput,$is_home);
13285:     my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
13286:                                                            \%linkprotchg,'domain');
13287:     my $home = &Apache::lonnet::domain($dom,'primary');
13288:     unless (($home eq 'no_host') || ($home eq '')) {
13289:         my @ids=&Apache::lonnet::current_machine_ids();
13290:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; } }
13291:     }
13292: 
13293:     if (keys(%linkprotchg)) {
13294:         $secchanges{'linkprot'} = 1;
13295:         my %oldlinkprot;
13296:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
13297:             %oldlinkprot = %{$currltisec{'linkprot'}};
13298:         }
13299:         foreach my $id (keys(%linkprotchg)) {
13300:             if (ref($linkprotchg{$id}) eq 'HASH') {
13301:                 foreach my $inner (keys(%{$linkprotchg{$id}})) {
13302:                     if (($inner eq 'secret') || ($inner eq 'key')) {
13303:                         if ($is_home) {
13304:                             $newltienc{$id}{$inner} = $linkprotchg{$id}{$inner};
13305:                         }
13306:                     }
13307:                 }
13308:             } else {
13309:                 $newltisec{'linkprot'}{$id} = $linkprotchg{$id};
13310:             }
13311:         }
13312:         $linkprotoutput = &Apache::courseprefs::store_linkprot($dom,'','domain',\%linkprotchg,\%oldlinkprot);
13313:         if (keys(%linkprotchg)) {
13314:             %{$newltisec{'linkprot'}} = %linkprotchg;
13315:         }
13316:     }
13317:     if (ref($currltisec{'linkprot'}) eq 'HASH') {
13318:         foreach my $id (%{$currltisec{'linkprot'}}) {
13319:             next if ($id !~ /^\d+$/);
13320:             unless (exists($linkprotchg{$id})) {
13321:                 if (ref($currltisec{'linkprot'}{$id}) eq 'HASH') {
13322:                     foreach my $inner (keys(%{$currltisec{'linkprot'}{$id}})) {
13323:                         if (($inner eq 'secret') || ($inner eq 'key')) {
13324:                             if ($is_home) {
13325:                                 $newltienc{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
13326:                             }
13327:                         } else {
13328:                             $newltisec{'linkprot'}{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
13329:                         }
13330:                     }
13331:                 } else {
13332:                     $newltisec{'linkprot'}{$id} = $currltisec{'linkprot'}{$id};
13333:                 }
13334:             }
13335:         }
13336:     }
13337:     if ($proterror) {
13338:         $errors .= '<li>'.$proterror.'</li>';
13339:     }
13340:     my (@items,%deletions,%itemids);
13341:     if ($env{'form.lti_add'}) {
13342:         my $consumer = $env{'form.lti_consumer_add'};
13343:         $consumer =~ s/(`)/'/g;
13344:         ($newid,my $error) = &get_lti_id($dom,$consumer);
13345:         if ($newid) {
13346:             $itemids{'add'} = $newid;
13347:             push(@items,'add');
13348:             $changes{$newid} = 1;
13349:         } else {
13350:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
13351:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13352:         }
13353:     }
13354:     if (ref($domconfig{$action}) eq 'HASH') {
13355:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
13356:         if (@todelete) {
13357:             map { $deletions{$_} = 1; } @todelete;
13358:         }
13359:         my $maxnum = $env{'form.lti_maxnum'};
13360:         for (my $i=0; $i<$maxnum; $i++) {
13361:             my $itemid = $env{'form.lti_id_'.$i};
13362:             $itemid =~ s/\D+//g;
13363:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13364:                 if ($deletions{$itemid}) {
13365:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
13366:                 } else {
13367:                     push(@items,$i);
13368:                     $itemids{$i} = $itemid;
13369:                 }
13370:             }
13371:         }
13372:     }
13373:     my (%keystore,$secstored);
13374:     if ($is_home) {
13375:         &store_security($dom,'lti',\%secchanges,\%newkeyset,\%keystore);
13376:     }
13377: 
13378:     my ($cipher,$privnum);
13379:     if ((@items > 0) && ($is_home)) {
13380:         ($cipher,$privnum) = &get_priv_creds($dom,$home,$secchanges{'encrypt'},
13381:                                              $newltisec{'encrypt'},$keystore{$home});
13382:     }
13383:     foreach my $idx (@items) {
13384:         my $itemid = $itemids{$idx};
13385:         next unless ($itemid);
13386:         my %currlti;
13387:         unless ($idx eq 'add') {
13388:             if (ref($domconfig{$action}) eq 'HASH') {
13389:                 if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13390:                     %currlti = %{$domconfig{$action}{$itemid}};
13391:                 }
13392:             }
13393:         }
13394:         my $position = $env{'form.lti_pos_'.$itemid};
13395:         $position =~ s/\D+//g;
13396:         if ($position ne '') {
13397:             $allpos[$position] = $itemid;
13398:         }
13399:         foreach my $item ('consumer','lifetime','requser','crsinc') {
13400:             my $formitem = 'form.lti_'.$item.'_'.$idx;
13401:             $env{$formitem} =~ s/(`)/'/g;
13402:             if ($item eq 'lifetime') {
13403:                 $env{$formitem} =~ s/[^\d.]//g;
13404:             }
13405:             if ($env{$formitem} ne '') {
13406:                 $confhash{$itemid}{$item} = $env{$formitem};
13407:                 unless (($idx eq 'add') || ($changes{$itemid})) {
13408:                     if ($currlti{$item} ne $confhash{$itemid}{$item}) {
13409:                         $changes{$itemid} = 1;
13410:                     }
13411:                 }
13412:             }
13413:         }
13414:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
13415:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
13416:         }
13417:         if ($confhash{$itemid}{'requser'}) {
13418:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
13419:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid';
13420:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
13421:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
13422:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
13423:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
13424:                 $mapuser =~ s/(`)/'/g;
13425:                 $mapuser =~ s/^\s+|\s+$//g;
13426:                 $confhash{$itemid}{'mapuser'} = $mapuser;
13427:             }
13428:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
13429:             my @makeuser;
13430:             foreach my $ltirole (sort(@possmakeuser)) {
13431:                 if ($posslti{$ltirole}) {
13432:                     push(@makeuser,$ltirole);
13433:                 }
13434:             }
13435:             $confhash{$itemid}{'makeuser'} = \@makeuser;
13436:             if (@makeuser) {
13437:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
13438:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
13439:                     $confhash{$itemid}{'lcauth'} = $lcauth;
13440:                     if ($lcauth ne 'internal') {
13441:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
13442:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
13443:                         $lcauthparm =~ s/`//g;
13444:                         if ($lcauthparm ne '') {
13445:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
13446:                         }
13447:                     }
13448:                 } else {
13449:                     $confhash{$itemid}{'lcauth'} = 'lti';
13450:                 }
13451:             }
13452:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
13453:             if (@possinstdata) {
13454:                 foreach my $field (@possinstdata) {
13455:                     if (exists($fieldtitles{$field})) {
13456:                         push(@{$confhash{$itemid}{'instdata'}});
13457:                     }
13458:                 }
13459:             }
13460:             if ($env{'form.lti_callback_'.$idx}) {
13461:                 if ($env{'form.lti_callbackparam_'.$idx}) {
13462:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
13463:                     $callback =~ s/^\s+|\s+$//g;
13464:                     $confhash{$itemid}{'callback'} = $callback;
13465:                 }
13466:             }
13467:             foreach my $field ('topmenu','inlinemenu') {
13468:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
13469:                     $confhash{$itemid}{$field} = 1;
13470:                 }
13471:             }
13472:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
13473:                 $confhash{$itemid}{lcmenu} = [];
13474:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
13475:                 foreach my $field (@possmenu) {
13476:                     if (exists($menutitles{$field})) {
13477:                         if ($field eq 'grades') {
13478:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
13479:                         }
13480:                         push(@{$confhash{$itemid}{lcmenu}},$field);
13481:                     }
13482:                 }
13483:             }
13484:             if ($confhash{$itemid}{'crsinc'}) {
13485:                 if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
13486:                     ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
13487:                     $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
13488:                 } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
13489:                     my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx};
13490:                     $mapcrs =~ s/(`)/'/g;
13491:                     $mapcrs =~ s/^\s+|\s+$//g;
13492:                     $confhash{$itemid}{'mapcrs'} = $mapcrs;
13493:                 }
13494:                 my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
13495:                 my @crstypes;
13496:                 foreach my $type (sort(@posstypes)) {
13497:                     if ($posscrstype{$type}) {
13498:                         push(@crstypes,$type);
13499:                     }
13500:                 }
13501:                 $confhash{$itemid}{'mapcrstype'} = \@crstypes;
13502:                 if ($env{'form.lti_storecrs_'.$idx}) {
13503:                     $confhash{$itemid}{'storecrs'} = 1;
13504:                 }
13505:                 if ($env{'form.lti_makecrs_'.$idx}) {
13506:                     $confhash{$itemid}{'makecrs'} = 1;
13507:                 }
13508:                 foreach my $ltirole (@lticourseroles) {
13509:                     my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
13510:                     if (grep(/^\Q$possrole\E$/,@courseroles)) {
13511:                         $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
13512:                     }
13513:                 }
13514:                 my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
13515:                 my @selfenroll;
13516:                 foreach my $type (sort(@possenroll)) {
13517:                     if ($posslticrs{$type}) {
13518:                         push(@selfenroll,$type);
13519:                     }
13520:                 }
13521:                 $confhash{$itemid}{'selfenroll'} = \@selfenroll;
13522:                 if ($env{'form.lti_crssec_'.$idx}) {
13523:                     if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
13524:                         $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
13525:                     } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
13526:                         my $section = $env{'form.lti_customsection_'.$idx};
13527:                         $section =~ s/(`)/'/g;
13528:                         $section =~ s/^\s+|\s+$//g;
13529:                         if ($section ne '') {
13530:                             $confhash{$itemid}{'section'} = $section;
13531:                         }
13532:                     }
13533:                 }
13534:                 foreach my $field ('passback','roster') {
13535:                     if ($env{'form.lti_'.$field.'_'.$idx}) {
13536:                         $confhash{$itemid}{$field} = 1;
13537:                     }
13538:                 }
13539:                 if ($env{'form.lti_passback_'.$idx}) {
13540:                     if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
13541:                         $confhash{$itemid}{'passbackformat'} = '1.0';
13542:                     } else {
13543:                         $confhash{$itemid}{'passbackformat'} = '1.1';
13544:                     }
13545:                 }
13546:             }
13547:             unless (($idx eq 'add') || ($changes{$itemid})) {
13548:                 if ($confhash{$itemid}{'crsinc'}) {
13549:                     foreach my $field ('mapcrs','storecrs','makecrs','section','passback','roster') {
13550:                         if ($currlti{$field} ne $confhash{$itemid}{$field}) {
13551:                             $changes{$itemid} = 1;
13552:                         }
13553:                     }
13554:                     unless ($changes{$itemid}) {
13555:                         if ($currlti{'passback'} eq $confhash{$itemid}{'passback'}) {
13556:                             if ($currlti{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
13557:                                 $changes{$itemid} = 1;
13558:                             }
13559:                         }
13560:                     }
13561:                     foreach my $field ('mapcrstype','selfenroll') {
13562:                         unless ($changes{$itemid}) {
13563:                             if (ref($currlti{$field}) eq 'ARRAY') {
13564:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
13565:                                     my @diffs = &Apache::loncommon::compare_arrays($currlti{$field},
13566:                                                                                    $confhash{$itemid}{$field});
13567:                                     if (@diffs) {
13568:                                         $changes{$itemid} = 1;
13569:                                     }
13570:                                 } elsif (@{$currlti{$field}} > 0) {
13571:                                     $changes{$itemid} = 1;
13572:                                 }
13573:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
13574:                                 if (@{$confhash{$itemid}{$field}} > 0) {
13575:                                     $changes{$itemid} = 1;
13576:                                 }
13577:                             }
13578:                         }
13579:                     }
13580:                     unless ($changes{$itemid}) {
13581:                         if (ref($currlti{'maproles'}) eq 'HASH') {
13582:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
13583:                                 foreach my $ltirole (keys(%{$currlti{'maproles'}})) {
13584:                                     if ($currlti{'maproles'}{$ltirole} ne
13585:                                         $confhash{$itemid}{'maproles'}{$ltirole}) {
13586:                                         $changes{$itemid} = 1;
13587:                                         last;
13588:                                     }
13589:                                 }
13590:                                 unless ($changes{$itemid}) {
13591:                                     foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
13592:                                         if ($confhash{$itemid}{'maproles'}{$ltirole} ne
13593:                                             $currlti{'maproles'}{$ltirole}) {
13594:                                             $changes{$itemid} = 1;
13595:                                             last;
13596:                                         }
13597:                                     }
13598:                                 }
13599:                             } elsif (keys(%{$currlti{'maproles'}}) > 0) {
13600:                                 $changes{$itemid} = 1;
13601:                             }
13602:                         } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
13603:                             unless ($changes{$itemid}) {
13604:                                 if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
13605:                                     $changes{$itemid} = 1;
13606:                                 }
13607:                             }
13608:                         }
13609:                     }
13610:                 }
13611:                 unless ($changes{$itemid}) {
13612:                     foreach my $field ('mapuser','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
13613:                         if ($currlti{$field} ne $confhash{$itemid}{$field}) {
13614:                             $changes{$itemid} = 1;
13615:                         }
13616:                     }
13617:                     unless ($changes{$itemid}) {
13618:                         foreach my $field ('makeuser','lcmenu') {
13619:                             if (ref($currlti{$field}) eq 'ARRAY') {
13620:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
13621:                                     my @diffs = &Apache::loncommon::compare_arrays($currlti{$field},
13622:                                                                                    $confhash{$itemid}{$field});
13623:                                     if (@diffs) {
13624:                                         $changes{$itemid} = 1;
13625:                                     }
13626:                                 } elsif (@{$currlti{$field}} > 0) {
13627:                                     $changes{$itemid} = 1;
13628:                                 }
13629:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
13630:                                 if (@{$confhash{$itemid}{$field}} > 0) {
13631:                                     $changes{$itemid} = 1;
13632:                                 }
13633:                             }
13634:                         }
13635:                     }
13636:                 }
13637:             }
13638:         }
13639:         if ($is_home) {
13640:             my $keyitem = 'form.lti_key_'.$idx;
13641:             $env{$keyitem} =~ s/(`)/'/g;
13642:             if ($env{$keyitem} ne '') {
13643:                 $ltienc{$itemid}{'key'} = $env{$keyitem};
13644:                 unless ($changes{$itemid}) {
13645:                     if ($currlti{'key'} ne $env{$keyitem}) {
13646:                         $changes{$itemid} = 1;
13647:                     }
13648:                 }
13649:             }
13650:             my $secretitem = 'form.lti_secret_'.$idx;
13651:             $env{$secretitem} =~ s/(`)/'/g;
13652:             if ($currlti{'usable'}) {
13653:                 if ($env{'form.lti_changesecret_'.$idx}) {
13654:                     if ($env{$secretitem} ne '') {
13655:                         if ($privnum && $cipher) {
13656:                             $ltienc{$itemid}{'secret'} = $cipher->encrypt_hex($env{$secretitem});
13657:                             $confhash{$itemid}{'cipher'} = $privnum;
13658:                         } else {
13659:                             $ltienc{$itemid}{'secret'} = $env{$secretitem};
13660:                         }
13661:                         $changes{$itemid} = 1;
13662:                     }
13663:                 } else {
13664:                     $ltienc{$itemid}{'secret'} = $currlti{'secret'};
13665:                     $confhash{$itemid}{'cipher'} = $currlti{'cipher'};
13666:                 }
13667:                 if (ref($ltienc{$itemid}) eq 'HASH') {
13668:                     if (($ltienc{$itemid}{'key'} ne '') && ($ltienc{$itemid}{'secret'} ne '')) {
13669:                         $confhash{$itemid}{'usable'} = 1;
13670:                     }
13671:                 }
13672:             } elsif ($env{$secretitem} ne '') {
13673:                 if ($privnum && $cipher) {
13674:                     $ltienc{$itemid}{'secret'} = $cipher->encrypt_hex($env{$secretitem});
13675:                     $confhash{$itemid}{'cipher'} = $privnum;
13676:                 } else {
13677:                     $ltienc{$itemid}{'secret'} = $env{$secretitem};
13678:                 }
13679:                 if (ref($ltienc{$itemid}) eq 'HASH') {
13680:                     if (($ltienc{$itemid}{'key'} ne '') && ($ltienc{$itemid}{'key'} ne '')) {
13681:                         $confhash{$itemid}{'usable'} = 1;
13682:                     }
13683:                 }
13684:                 $changes{$itemid} = 1;
13685:             }
13686:         }
13687:         unless ($changes{$itemid}) {
13688:             foreach my $key (keys(%currlti)) {
13689:                 if (ref($currlti{$key}) eq 'HASH') {
13690:                     if (ref($confhash{$itemid}{$key}) eq 'HASH') {
13691:                         foreach my $innerkey (keys(%{$currlti{$key}})) {
13692:                             unless (exists($confhash{$itemid}{$key}{$innerkey})) {
13693:                                 $changes{$itemid} = 1;
13694:                                 last;
13695:                             }
13696:                         }
13697:                     } elsif (keys(%{$currlti{$key}}) > 0) {
13698:                         $changes{$itemid} = 1;
13699:                     }
13700:                 }
13701:                 last if ($changes{$itemid});
13702:             }
13703:         }
13704:     }
13705:     if (@allpos > 0) {
13706:         my $idx = 0;
13707:         foreach my $itemid (@allpos) {
13708:             if ($itemid ne '') {
13709:                 $confhash{$itemid}{'order'} = $idx;
13710:                 if (ref($domconfig{$action}) eq 'HASH') {
13711:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13712:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
13713:                             $changes{$itemid} = 1;
13714:                         }
13715:                     }
13716:                 }
13717:                 $idx ++;
13718:             }
13719:         }
13720:     }
13721: 
13722:     if ((keys(%changes) == 0) && (keys(%secchanges) == 0)) {
13723:         return &mt('No changes made.');
13724:     }
13725: 
13726:     my %ltihash = (
13727:                       $action => { %confhash }
13728:                   );
13729:     my %ltienchash;
13730: 
13731:     if ($is_home) {
13732:         %ltienchash = (
13733:                          $action => { %ltienc }
13734:                       );
13735:     }
13736:     if (keys(%secchanges)) {
13737:         $ltihash{'ltisec'} = \%newltisec;
13738:         if ($secchanges{'linkprot'}) {
13739:             if ($is_home) {
13740:                 $ltienchash{'linkprot'} = \%newltienc;
13741:             }
13742:         }
13743:     }
13744:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
13745:     if ($putresult eq 'ok') {
13746:         if (keys(%ltienchash)) {
13747:             &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
13748:         }
13749:         $resulttext = &mt('Changes made:').'<ul>';
13750:         if (keys(%secchanges) > 0) {
13751:             $resulttext .= &lti_security_results($dom,'lti',\%secchanges,\%newltisec,\%newkeyset,\%keystore);
13752:             if (exists($secchanges{'linkprot'})) {
13753:                 $resulttext .= $linkprotoutput;
13754:             }
13755:         }
13756:         if (keys(%changes) > 0) {
13757:             my $cachetime = 24*60*60;
13758:             &Apache::lonnet::do_cache_new('lti',$dom,\%confhash,$cachetime);
13759:             if (ref($lastactref) eq 'HASH') {
13760:                 $lastactref->{'lti'} = 1;
13761:             }
13762:             my %bynum;
13763:             foreach my $itemid (sort(keys(%changes))) {
13764:                 if (ref($confhash{$itemid}) eq 'HASH') {
13765:                     my $position = $confhash{$itemid}{'order'};
13766:                     $bynum{$position} = $itemid;
13767:                 }
13768:             }
13769:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13770:                 my $itemid = $bynum{$pos};
13771:                 if (ref($confhash{$itemid}) eq 'HASH') {
13772:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b><ul>';
13773:                     my $position = $pos + 1;
13774:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13775:                     foreach my $item ('version','lifetime') {
13776:                         if ($confhash{$itemid}{$item} ne '') {
13777:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
13778:                         }
13779:                     }
13780:                     if ($ltienc{$itemid}{'key'} ne '') {
13781:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$ltienc{$itemid}{'key'}.'</li>';
13782:                     }
13783:                     if ($ltienc{$itemid}{'secret'} ne '') {
13784:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;['.&mt('not shown').']</li>';
13785:                     }
13786:                     if ($confhash{$itemid}{'requser'}) {
13787:                         if ($confhash{$itemid}{'callback'}) {
13788:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
13789:                         } else {
13790:                             $resulttext .= '<li>'.&mt('Callback to logout LON-CAPA on log out from Consumer').'</li>';
13791:                         }
13792:                         if ($confhash{$itemid}{'mapuser'}) {
13793:                             my $shownmapuser;
13794:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
13795:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
13796:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
13797:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
13798:                             } else {
13799:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
13800:                             }
13801:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
13802:                         }
13803:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
13804:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) {
13805:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
13806:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
13807:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
13808:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
13809:                                 } else {
13810:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
13811:                                                        $confhash{$itemid}{'lcauth'});
13812:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
13813:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
13814:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
13815:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
13816:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
13817:                                         }
13818:                                     } else {
13819:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
13820:                                     }
13821:                                 }
13822:                                 $resulttext .= '</li>';
13823:                             } else {
13824:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
13825:                             }
13826:                         }
13827:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
13828:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
13829:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
13830:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
13831:                             } else {
13832:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
13833:                             }
13834:                         }
13835:                         foreach my $item ('topmenu','inlinemenu') {
13836:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
13837:                             if ($confhash{$itemid}{$item}) {
13838:                                 $resulttext .= &mt('Yes');
13839:                             } else {
13840:                                 $resulttext .= &mt('No');
13841:                             }
13842:                             $resulttext .= '</li>';
13843:                         }
13844:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
13845:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
13846:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
13847:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>';
13848:                             } else {
13849:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>';
13850:                             }
13851:                         }
13852:                         if ($confhash{$itemid}{'crsinc'}) {
13853:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
13854:                                 my $rolemaps;
13855:                                 foreach my $role (@ltiroles) {
13856:                                     if ($confhash{$itemid}{'maproles'}{$role}) {
13857:                                         $rolemaps .= ('&nbsp;'x2).$role.'='.
13858:                                                      &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
13859:                                                                                 'Course').',';
13860:                                     }
13861:                                 }
13862:                                 if ($rolemaps) {
13863:                                     $rolemaps =~ s/,$//;
13864:                                     $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
13865:                                 }
13866:                             }
13867:                             if ($confhash{$itemid}{'mapcrs'}) {
13868:                                 $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
13869:                             }
13870:                             if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
13871:                                 if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
13872:                                     $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
13873:                                                    join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
13874:                                                    '</li>';
13875:                                 } else {
13876:                                     $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
13877:                                 }
13878:                             }
13879:                             if ($confhash{$itemid}{'storecrs'}) {
13880:                                 $resulttext .= '<li>'.&mt('Store mapping of course identifier to LON-CAPA CourseID').': '.$confhash{$itemid}{'storecrs'}.'</li>';
13881:                             }
13882:                             if ($confhash{$itemid}{'makecrs'}) {
13883:                                 $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
13884:                             } else {
13885:                                 $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
13886:                             }
13887:                             if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
13888:                                 if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
13889:                                     $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
13890:                                                               join(', ',@{$confhash{$itemid}{'selfenroll'}})).
13891:                                                    '</li>';
13892:                                 } else {
13893:                                     $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
13894:                                 }
13895:                             }
13896:                             if ($confhash{$itemid}{'section'}) {
13897:                                 if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
13898:                                     $resulttext .= '<li>'.&mt('User section from standard field:').
13899:                                                          ' (course_section_sourcedid)'.'</li>';
13900:                                 } else {
13901:                                     $resulttext .= '<li>'.&mt('User section from:').' '.
13902:                                                           $confhash{$itemid}{'section'}.'</li>';
13903:                                 }
13904:                             } else {
13905:                                 $resulttext .= '<li>'.&mt('No section assignment').'</li>';
13906:                             }
13907:                             foreach my $item ('passback','roster','topmenu','inlinemenu') {
13908:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
13909:                                 if ($confhash{$itemid}{$item}) {
13910:                                     $resulttext .= &mt('Yes');
13911:                                     if ($item eq 'passback') {
13912:                                         if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
13913:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
13914:                                         } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
13915:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
13916:                                         }
13917:                                     }
13918:                                 } else {
13919:                                     $resulttext .= &mt('No');
13920:                                 }
13921:                                 $resulttext .= '</li>';
13922:                             }
13923:                             if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
13924:                                 if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
13925:                                     $resulttext .= '<li>'.&mt('Menu items:').' '.
13926:                                                    join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>';
13927:                                 } else {
13928:                                     $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>';
13929:                                 }
13930:                             }
13931:                         }
13932:                     }
13933:                     $resulttext .= '</ul></li>';
13934:                 }
13935:             }
13936:             if (keys(%deletions)) {
13937:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
13938:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13939:                 }
13940:             }
13941:         }
13942:         $resulttext .= '</ul>';
13943:         if (ref($lastactref) eq 'HASH') {
13944:             if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
13945:                 $lastactref->{'domdefaults'} = 1;
13946:             }
13947:         }
13948:     } else {
13949:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13950:     }
13951:     if ($errors) {
13952:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13953:                        $errors.'</ul>';
13954:     }
13955:     return $resulttext;
13956: }
13957: 
13958: sub get_priv_creds {
13959:     my ($dom,$home,$encchg,$encrypt,$storedsec) = @_;
13960:     my ($needenc,$cipher,$privnum);
13961:     my %domdefs = &Apache::lonnet::get_domain_defaults($dom);
13962:     if (($encchg) && (ref($encrypt) eq 'HASH')) {
13963:         $needenc = $encrypt->{'consumers'}
13964:     } else {
13965:         $needenc = $domdefs{'ltienc_consumers'};
13966:     }
13967:     if ($needenc) {
13968:         if (($storedsec eq 'ok') || ((ref($domdefs{'ltiprivhosts'}) eq 'ARRAY') &&
13969:                                      (grep(/^\Q$home\E$/,@{$domdefs{'ltiprivhosts'}})))) {
13970:                         my %privhash  = &Apache::lonnet::restore_dom('lti','private',$dom,$home,1);
13971:             my $privkey = $privhash{'key'};
13972:             $privnum = $privhash{'version'};
13973:             if (($privnum) && ($privkey ne '')) {
13974:                 $cipher = Crypt::CBC->new({'key'     => $privkey,
13975:                                           'cipher'  => 'DES'});
13976:             }
13977:         }
13978:     }
13979:     return ($cipher,$privnum);
13980: }
13981: 
13982: sub get_lti_id {
13983:     my ($domain,$consumer) = @_;
13984:     # get lock on lti db
13985:     my $lockhash = {
13986:                       lock => $env{'user.name'}.
13987:                               ':'.$env{'user.domain'},
13988:                    };
13989:     my $tries = 0;
13990:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
13991:     my ($id,$error);
13992: 
13993:     while (($gotlock ne 'ok') && ($tries<10)) {
13994:         $tries ++;
13995:         sleep (0.1);
13996:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
13997:     }
13998:     if ($gotlock eq 'ok') {
13999:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
14000:         if ($currids{'lock'}) {
14001:             delete($currids{'lock'});
14002:             if (keys(%currids)) {
14003:                 my @curr = sort { $a <=> $b } keys(%currids);
14004:                 if ($curr[-1] =~ /^\d+$/) {
14005:                     $id = 1 + $curr[-1];
14006:                 }
14007:             } else {
14008:                 $id = 1;
14009:             }
14010:             if ($id) {
14011:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
14012:                     $error = 'nostore';
14013:                 }
14014:             } else {
14015:                 $error = 'nonumber';
14016:             }
14017:         }
14018:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
14019:     } else {
14020:         $error = 'nolock';
14021:     }
14022:     return ($id,$error);
14023: }
14024: 
14025: sub modify_autoenroll {
14026:     my ($dom,$lastactref,%domconfig) = @_;
14027:     my ($resulttext,%changes);
14028:     my %currautoenroll;
14029:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
14030:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
14031:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
14032:         }
14033:     }
14034:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
14035:     my %title = ( run => 'Auto-enrollment active',
14036:                   sender => 'Sender for notification messages',
14037:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
14038:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
14039:     my @offon = ('off','on');
14040:     my $sender_uname = $env{'form.sender_uname'};
14041:     my $sender_domain = $env{'form.sender_domain'};
14042:     if ($sender_domain eq '') {
14043:         $sender_uname = '';
14044:     } elsif ($sender_uname eq '') {
14045:         $sender_domain = '';
14046:     }
14047:     my $coowners = $env{'form.autoassign_coowners'};
14048:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
14049:     $autofailsafe =~ s{^\s+|\s+$}{}g;
14050:     if ($autofailsafe =~ /\D/) {
14051:         undef($autofailsafe);
14052:     }
14053:     my $failsafe = $env{'form.autoenroll_failsafe'};
14054:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
14055:         $failsafe = 'off';
14056:         undef($autofailsafe);
14057:     }
14058:     my %autoenrollhash =  (
14059:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
14060:                                        'sender_uname' => $sender_uname,
14061:                                        'sender_domain' => $sender_domain,
14062:                                        'co-owners' => $coowners,
14063:                                        'autofailsafe' => $autofailsafe,
14064:                                        'failsafe' => $failsafe,
14065:                                 }
14066:                      );
14067:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
14068:                                              $dom);
14069:     if ($putresult eq 'ok') {
14070:         if (exists($currautoenroll{'run'})) {
14071:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
14072:                  $changes{'run'} = 1;
14073:              }
14074:         } elsif ($autorun) {
14075:             if ($env{'form.autoenroll_run'} ne '1') {
14076:                  $changes{'run'} = 1;
14077:             }
14078:         }
14079:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
14080:             $changes{'sender'} = 1;
14081:         }
14082:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
14083:             $changes{'sender'} = 1;
14084:         }
14085:         if ($currautoenroll{'co-owners'} ne '') {
14086:             if ($currautoenroll{'co-owners'} ne $coowners) {
14087:                 $changes{'coowners'} = 1;
14088:             }
14089:         } elsif ($coowners) {
14090:             $changes{'coowners'} = 1;
14091:         }
14092:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
14093:             $changes{'autofailsafe'} = 1;
14094:         }
14095:         if ($currautoenroll{'failsafe'} ne $failsafe) {
14096:             $changes{'failsafe'} = 1;
14097:         }
14098:         if (keys(%changes) > 0) {
14099:             $resulttext = &mt('Changes made:').'<ul>';
14100:             if ($changes{'run'}) {
14101:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
14102:             }
14103:             if ($changes{'sender'}) {
14104:                 if ($sender_uname eq '' || $sender_domain eq '') {
14105:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
14106:                 } else {
14107:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
14108:                 }
14109:             }
14110:             if ($changes{'coowners'}) {
14111:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
14112:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
14113:                 if (ref($lastactref) eq 'HASH') {
14114:                     $lastactref->{'domainconfig'} = 1;
14115:                 }
14116:             }
14117:             if ($changes{'autofailsafe'}) {
14118:                 if ($autofailsafe ne '') {
14119:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
14120:                 } else {
14121:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
14122:                 }
14123:             }
14124:             if ($changes{'failsafe'}) {
14125:                 if ($failsafe eq 'off') {
14126:                     unless ($changes{'autofailsafe'}) {
14127:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
14128:                     }
14129:                 } elsif ($failsafe eq 'zero') {
14130:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
14131:                 } else {
14132:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
14133:                 }
14134:             }
14135:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
14136:                 &Apache::lonnet::get_domain_defaults($dom,1);
14137:                 if (ref($lastactref) eq 'HASH') {
14138:                     $lastactref->{'domdefaults'} = 1;
14139:                 }
14140:             }
14141:             $resulttext .= '</ul>';
14142:         } else {
14143:             $resulttext = &mt('No changes made to auto-enrollment settings');
14144:         }
14145:     } else {
14146:         $resulttext = '<span class="LC_error">'.
14147: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14148:     }
14149:     return $resulttext;
14150: }
14151: 
14152: sub modify_autoupdate {
14153:     my ($dom,%domconfig) = @_;
14154:     my ($resulttext,%currautoupdate,%fields,%changes);
14155:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
14156:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
14157:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
14158:         }
14159:     }
14160:     my @offon = ('off','on');
14161:     my %title = &Apache::lonlocal::texthash (
14162:                     run        => 'Auto-update:',
14163:                     classlists => 'Updates to user information in classlists?',
14164:                     unexpired  => 'Skip updates for users without active or future roles?',
14165:                     lastactive => 'Skip updates for inactive users?',
14166:                 );
14167:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14168:     my %fieldtitles = &Apache::lonlocal::texthash (
14169:                         id => 'Student/Employee ID',
14170:                         permanentemail => 'E-mail address',
14171:                         lastname => 'Last Name',
14172:                         firstname => 'First Name',
14173:                         middlename => 'Middle Name',
14174:                         generation => 'Generation',
14175:                       );
14176:     $othertitle = &mt('All users');
14177:     if (keys(%{$usertypes}) >  0) {
14178:         $othertitle = &mt('Other users');
14179:     }
14180:     foreach my $key (keys(%env)) {
14181:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
14182:             my ($usertype,$item) = ($1,$2);
14183:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
14184:                 if ($usertype eq 'default') {   
14185:                     push(@{$fields{$1}},$2);
14186:                 } elsif (ref($types) eq 'ARRAY') {
14187:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
14188:                         push(@{$fields{$1}},$2);
14189:                     }
14190:                 }
14191:             }
14192:         }
14193:     }
14194:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
14195:     @lockablenames = sort(@lockablenames);
14196:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
14197:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
14198:         if (@changed) {
14199:             $changes{'lockablenames'} = 1;
14200:         }
14201:     } else {
14202:         if (@lockablenames) {
14203:             $changes{'lockablenames'} = 1;
14204:         }
14205:     }
14206:     my %updatehash = (
14207:                       autoupdate => { run => $env{'form.autoupdate_run'},
14208:                                       classlists => $env{'form.classlists'},
14209:                                       unexpired  => $env{'form.unexpired'},
14210:                                       fields => {%fields},
14211:                                       lockablenames => \@lockablenames,
14212:                                     }
14213:                      );
14214:     my $lastactivedays;
14215:     if ($env{'form.lastactive'}) {
14216:         $lastactivedays = $env{'form.lastactivedays'};
14217:         $lastactivedays =~ s/^\s+|\s+$//g;
14218:         unless ($lastactivedays =~ /^\d+$/) {
14219:             undef($lastactivedays);
14220:             $env{'form.lastactive'} = 0;
14221:         }
14222:     }
14223:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
14224:     foreach my $key (keys(%currautoupdate)) {
14225:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
14226:             if (exists($updatehash{autoupdate}{$key})) {
14227:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
14228:                     $changes{$key} = 1;
14229:                 }
14230:             }
14231:         } elsif ($key eq 'fields') {
14232:             if (ref($currautoupdate{$key}) eq 'HASH') {
14233:                 foreach my $item (@{$types},'default') {
14234:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
14235:                         my $change = 0;
14236:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
14237:                             if (!exists($fields{$item})) {
14238:                                 $change = 1;
14239:                                 last;
14240:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
14241:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
14242:                                     $change = 1;
14243:                                     last;
14244:                                 }
14245:                             }
14246:                         }
14247:                         if ($change) {
14248:                             push(@{$changes{$key}},$item);
14249:                         }
14250:                     } 
14251:                 }
14252:             }
14253:         } elsif ($key eq 'lockablenames') {
14254:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
14255:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
14256:                 if (@changed) {
14257:                     $changes{'lockablenames'} = 1;
14258:                 }
14259:             } else {
14260:                 if (@lockablenames) {
14261:                     $changes{'lockablenames'} = 1;
14262:                 }
14263:             }
14264:         }
14265:     }
14266:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
14267:         if (@lockablenames) {
14268:             $changes{'lockablenames'} = 1;
14269:         }
14270:     }
14271:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
14272:         if ($updatehash{'autoupdate'}{'unexpired'}) {
14273:             $changes{'unexpired'} = 1;
14274:         }
14275:     }
14276:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
14277:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
14278:             $changes{'lastactive'} = 1;
14279:         }
14280:     }
14281:     foreach my $item (@{$types},'default') {
14282:         if (defined($fields{$item})) {
14283:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
14284:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
14285:                     my $change = 0;
14286:                     if (ref($fields{$item}) eq 'ARRAY') {
14287:                         foreach my $type (@{$fields{$item}}) {
14288:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
14289:                                 $change = 1;
14290:                                 last;
14291:                             }
14292:                         }
14293:                     }
14294:                     if ($change) {
14295:                         push(@{$changes{'fields'}},$item);
14296:                     }
14297:                 } else {
14298:                     push(@{$changes{'fields'}},$item);
14299:                 }
14300:             } else {
14301:                 push(@{$changes{'fields'}},$item);
14302:             }
14303:         }
14304:     }
14305:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
14306:                                              $dom);
14307:     if ($putresult eq 'ok') {
14308:         if (keys(%changes) > 0) {
14309:             $resulttext = &mt('Changes made:').'<ul>';
14310:             foreach my $key (sort(keys(%changes))) {
14311:                 if ($key eq 'lockablenames') {
14312:                     $resulttext .= '<li>';
14313:                     if (@lockablenames) {
14314:                         $usertypes->{'default'} = $othertitle;
14315:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
14316:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
14317:                     } else {
14318:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
14319:                     }
14320:                     $resulttext .= '</li>';
14321:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
14322:                     foreach my $item (@{$changes{$key}}) {
14323:                         my @newvalues;
14324:                         foreach my $type (@{$fields{$item}}) {
14325:                             push(@newvalues,$fieldtitles{$type});
14326:                         }
14327:                         my $newvaluestr;
14328:                         if (@newvalues > 0) {
14329:                             $newvaluestr = join(', ',@newvalues);
14330:                         } else {
14331:                             $newvaluestr = &mt('none');
14332:                         }
14333:                         if ($item eq 'default') {
14334:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
14335:                         } else {
14336:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
14337:                         }
14338:                     }
14339:                 } else {
14340:                     my $newvalue;
14341:                     if ($key eq 'run') {
14342:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
14343:                     } elsif ($key eq 'lastactive') {
14344:                         $newvalue = $offon[$env{'form.lastactive'}];
14345:                         unless ($lastactivedays eq '') {
14346:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
14347:                         }
14348:                     } else {
14349:                         $newvalue = $offon[$env{'form.'.$key}];
14350:                     }
14351:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
14352:                 }
14353:             }
14354:             $resulttext .= '</ul>';
14355:         } else {
14356:             $resulttext = &mt('No changes made to autoupdates');
14357:         }
14358:     } else {
14359:         $resulttext = '<span class="LC_error">'.
14360: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14361:     }
14362:     return $resulttext;
14363: }
14364: 
14365: sub modify_autocreate {
14366:     my ($dom,%domconfig) = @_;
14367:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
14368:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
14369:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
14370:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
14371:         }
14372:     }
14373:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
14374:                  req => 'Auto-creation of validated requests for official courses',
14375:                  xmldc => 'Identity of course creator of courses from XML files',
14376:                );
14377:     my @types = ('xml','req');
14378:     foreach my $item (@types) {
14379:         $newvals{$item} = $env{'form.autocreate_'.$item};
14380:         $newvals{$item} =~ s/\D//g;
14381:         $newvals{$item} = 0 if ($newvals{$item} eq '');
14382:     }
14383:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
14384:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
14385:     unless (exists($domcoords{$newvals{'xmldc'}})) {
14386:         $newvals{'xmldc'} = '';
14387:     } 
14388:     %autocreatehash =  (
14389:                         autocreate => { xml => $newvals{'xml'},
14390:                                         req => $newvals{'req'},
14391:                                       }
14392:                        );
14393:     if ($newvals{'xmldc'} ne '') {
14394:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
14395:     }
14396:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
14397:                                              $dom);
14398:     if ($putresult eq 'ok') {
14399:         my @items = @types;
14400:         if ($newvals{'xml'}) {
14401:             push(@items,'xmldc');
14402:         }
14403:         foreach my $item (@items) {
14404:             if (exists($currautocreate{$item})) {
14405:                 if ($currautocreate{$item} ne $newvals{$item}) {
14406:                     $changes{$item} = 1;
14407:                 }
14408:             } elsif ($newvals{$item}) {
14409:                 $changes{$item} = 1;
14410:             }
14411:         }
14412:         if (keys(%changes) > 0) {
14413:             my @offon = ('off','on'); 
14414:             $resulttext = &mt('Changes made:').'<ul>';
14415:             foreach my $item (@types) {
14416:                 if ($changes{$item}) {
14417:                     my $newtxt = $offon[$newvals{$item}];
14418:                     $resulttext .= '<li>'.
14419:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
14420:                                        '<b>','</b>').
14421:                                    '</li>';
14422:                 }
14423:             }
14424:             if ($changes{'xmldc'}) {
14425:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
14426:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
14427:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
14428:             }
14429:             $resulttext .= '</ul>';
14430:         } else {
14431:             $resulttext = &mt('No changes made to auto-creation settings');
14432:         }
14433:     } else {
14434:         $resulttext = '<span class="LC_error">'.
14435:             &mt('An error occurred: [_1]',$putresult).'</span>';
14436:     }
14437:     return $resulttext;
14438: }
14439: 
14440: sub modify_directorysrch {
14441:     my ($dom,$lastactref,%domconfig) = @_;
14442:     my ($resulttext,%changes);
14443:     my %currdirsrch;
14444:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
14445:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
14446:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
14447:         }
14448:     }
14449:     my %title = ( available => 'Institutional directory search available',
14450:                   localonly => 'Other domains can search institution',
14451:                   lcavailable => 'LON-CAPA directory search available',
14452:                   lclocalonly => 'Other domains can search LON-CAPA domain',
14453:                   searchby => 'Search types',
14454:                   searchtypes => 'Search latitude');
14455:     my @offon = ('off','on');
14456:     my @otherdoms = ('Yes','No');
14457: 
14458:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
14459:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
14460:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
14461: 
14462:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14463:     if (keys(%{$usertypes}) == 0) {
14464:         @cansearch = ('default');
14465:     } else {
14466:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
14467:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
14468:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
14469:                     push(@{$changes{'cansearch'}},$type);
14470:                 }
14471:             }
14472:             foreach my $type (@cansearch) {
14473:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
14474:                     push(@{$changes{'cansearch'}},$type);
14475:                 }
14476:             }
14477:         } else {
14478:             push(@{$changes{'cansearch'}},@cansearch);
14479:         }
14480:     }
14481: 
14482:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
14483:         foreach my $by (@{$currdirsrch{'searchby'}}) {
14484:             if (!grep(/^\Q$by\E$/,@searchby)) {
14485:                 push(@{$changes{'searchby'}},$by);
14486:             }
14487:         }
14488:         foreach my $by (@searchby) {
14489:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
14490:                 push(@{$changes{'searchby'}},$by);
14491:             }
14492:         }
14493:     } else {
14494:         push(@{$changes{'searchby'}},@searchby);
14495:     }
14496: 
14497:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
14498:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
14499:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
14500:                 push(@{$changes{'searchtypes'}},$type);
14501:             }
14502:         }
14503:         foreach my $type (@searchtypes) {
14504:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
14505:                 push(@{$changes{'searchtypes'}},$type);
14506:             }
14507:         }
14508:     } else {
14509:         if (exists($currdirsrch{'searchtypes'})) {
14510:             foreach my $type (@searchtypes) {  
14511:                 if ($type ne $currdirsrch{'searchtypes'}) { 
14512:                     push(@{$changes{'searchtypes'}},$type);
14513:                 }
14514:             }
14515:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
14516:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
14517:             }   
14518:         } else {
14519:             push(@{$changes{'searchtypes'}},@searchtypes); 
14520:         }
14521:     }
14522: 
14523:     my %dirsrch_hash =  (
14524:             directorysrch => { available => $env{'form.dirsrch_available'},
14525:                                cansearch => \@cansearch,
14526:                                localonly => $env{'form.dirsrch_instlocalonly'},
14527:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
14528:                                lcavailable => $env{'form.dirsrch_domavailable'},
14529:                                searchby => \@searchby,
14530:                                searchtypes => \@searchtypes,
14531:                              }
14532:             );
14533:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
14534:                                              $dom);
14535:     if ($putresult eq 'ok') {
14536:         if (exists($currdirsrch{'available'})) {
14537:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
14538:                  $changes{'available'} = 1;
14539:              }
14540:         } else {
14541:             if ($env{'form.dirsrch_available'} eq '1') {
14542:                 $changes{'available'} = 1;
14543:             }
14544:         }
14545:         if (exists($currdirsrch{'lcavailable'})) {
14546:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
14547:                 $changes{'lcavailable'} = 1;
14548:             }
14549:         } else {
14550:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
14551:                 $changes{'lcavailable'} = 1;
14552:             }
14553:         }
14554:         if (exists($currdirsrch{'localonly'})) {
14555:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
14556:                 $changes{'localonly'} = 1;
14557:             }
14558:         } else {
14559:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
14560:                 $changes{'localonly'} = 1;
14561:             }
14562:         }
14563:         if (exists($currdirsrch{'lclocalonly'})) {
14564:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
14565:                 $changes{'lclocalonly'} = 1;
14566:             }
14567:         } else {
14568:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
14569:                 $changes{'lclocalonly'} = 1;
14570:             }
14571:         }
14572:         if (keys(%changes) > 0) {
14573:             $resulttext = &mt('Changes made:').'<ul>';
14574:             if ($changes{'available'}) {
14575:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
14576:             }
14577:             if ($changes{'lcavailable'}) {
14578:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
14579:             }
14580:             if ($changes{'localonly'}) {
14581:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
14582:             }
14583:             if ($changes{'lclocalonly'}) {
14584:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
14585:             }
14586:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
14587:                 my $chgtext;
14588:                 if (ref($usertypes) eq 'HASH') {
14589:                     if (keys(%{$usertypes}) > 0) {
14590:                         foreach my $type (@{$types}) {
14591:                             if (grep(/^\Q$type\E$/,@cansearch)) {
14592:                                 $chgtext .= $usertypes->{$type}.'; ';
14593:                             }
14594:                         }
14595:                         if (grep(/^default$/,@cansearch)) {
14596:                             $chgtext .= $othertitle;
14597:                         } else {
14598:                             $chgtext =~ s/\; $//;
14599:                         }
14600:                         $resulttext .=
14601:                             '<li>'.
14602:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
14603:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
14604:                             '</li>';
14605:                     }
14606:                 }
14607:             }
14608:             if (ref($changes{'searchby'}) eq 'ARRAY') {
14609:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
14610:                 my $chgtext;
14611:                 foreach my $type (@{$titleorder}) {
14612:                     if (grep(/^\Q$type\E$/,@searchby)) {
14613:                         if (defined($searchtitles->{$type})) {
14614:                             $chgtext .= $searchtitles->{$type}.'; ';
14615:                         }
14616:                     }
14617:                 }
14618:                 $chgtext =~ s/\; $//;
14619:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
14620:             }
14621:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
14622:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
14623:                 my $chgtext;
14624:                 foreach my $type (@{$srchtypeorder}) {
14625:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
14626:                         if (defined($srchtypes_desc->{$type})) {
14627:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
14628:                         }
14629:                     }
14630:                 }
14631:                 $chgtext =~ s/\; $//;
14632:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
14633:             }
14634:             $resulttext .= '</ul>';
14635:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
14636:             if (ref($lastactref) eq 'HASH') {
14637:                 $lastactref->{'directorysrch'} = 1;
14638:             }
14639:         } else {
14640:             $resulttext = &mt('No changes made to directory search settings');
14641:         }
14642:     } else {
14643:         $resulttext = '<span class="LC_error">'.
14644:                       &mt('An error occurred: [_1]',$putresult).'</span>';
14645:     }
14646:     return $resulttext;
14647: }
14648: 
14649: sub modify_contacts {
14650:     my ($dom,$lastactref,%domconfig) = @_;
14651:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
14652:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14653:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
14654:             $currsetting{$key} = $domconfig{'contacts'}{$key};
14655:         }
14656:     }
14657:     my (%others,%to,%bcc,%includestr,%includeloc);
14658:     my @contacts = ('supportemail','adminemail');
14659:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
14660:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
14661:     my @toggles = ('reporterrors','reportupdates','reportstatus');
14662:     my @lonstatus = ('threshold','sysmail','weights','excluded');
14663:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
14664:     foreach my $type (@mailings) {
14665:         @{$newsetting{$type}} = 
14666:             &Apache::loncommon::get_env_multiple('form.'.$type);
14667:         foreach my $item (@contacts) {
14668:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
14669:                 $contacts_hash{contacts}{$type}{$item} = 1;
14670:             } else {
14671:                 $contacts_hash{contacts}{$type}{$item} = 0;
14672:             }
14673:         }
14674:         $others{$type} = $env{'form.'.$type.'_others'};
14675:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
14676:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14677:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
14678:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
14679:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
14680:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
14681:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
14682:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
14683:             }
14684:         }
14685:     }
14686:     foreach my $item (@contacts) {
14687:         $to{$item} = $env{'form.'.$item};
14688:         $contacts_hash{'contacts'}{$item} = $to{$item};
14689:     }
14690:     foreach my $item (@toggles) {
14691:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
14692:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
14693:         }
14694:     }
14695:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
14696:     foreach my $item (@lonstatus) {
14697:         if ($item eq 'excluded') {
14698:             my (%serverhomes,@excluded);
14699:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
14700:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
14701:             if (@possexcluded) {
14702:                 foreach my $id (sort(@possexcluded)) {
14703:                     if ($serverhomes{$id}) {
14704:                         push(@excluded,$id);
14705:                     }
14706:                 }
14707:             }
14708:             if (@excluded) {
14709:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
14710:             }
14711:         } elsif ($item eq 'weights') {
14712:             foreach my $type ('E','W','N','U') {
14713:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
14714:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
14715:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
14716:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
14717:                             $env{'form.error'.$item.'_'.$type};
14718:                     }
14719:                 }
14720:             }
14721:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
14722:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
14723:             if ($env{'form.error'.$item} =~ /^\d+$/) {
14724:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
14725:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
14726:                 }
14727:             }
14728:         }
14729:     }
14730:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
14731:         foreach my $field (@{$fields}) {
14732:             if (ref($possoptions->{$field}) eq 'ARRAY') {
14733:                 my $value = $env{'form.helpform_'.$field};
14734:                 $value =~ s/^\s+|\s+$//g;
14735:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
14736:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
14737:                     if ($field eq 'screenshot') {
14738:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
14739:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
14740:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
14741:                         }
14742:                     }
14743:                 }
14744:             }
14745:         }
14746:     }
14747:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14748:     my (@statuses,%usertypeshash,@overrides);
14749:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
14750:         @statuses = @{$types};
14751:         if (ref($usertypes) eq 'HASH') {
14752:             %usertypeshash = %{$usertypes};
14753:         }
14754:     }
14755:     if (@statuses) {
14756:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
14757:         foreach my $type (@possoverrides) {
14758:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
14759:                 push(@overrides,$type);
14760:             }
14761:         }
14762:         if (@overrides) {
14763:             foreach my $type (@overrides) {
14764:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
14765:                 foreach my $item (@contacts) {
14766:                     if (grep(/^\Q$item\E$/,@standard)) {
14767:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
14768:                         $newsetting{'override_'.$type}{$item} = 1;
14769:                     } else {
14770:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
14771:                         $newsetting{'override_'.$type}{$item} = 0;
14772:                     }
14773:                 }
14774:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
14775:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
14776:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
14777:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
14778:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
14779:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
14780:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
14781:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
14782:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
14783:                 }
14784:             }
14785:         }
14786:     }
14787:     if (keys(%currsetting) > 0) {
14788:         foreach my $item (@contacts) {
14789:             if ($to{$item} ne $currsetting{$item}) {
14790:                 $changes{$item} = 1;
14791:             }
14792:         }
14793:         foreach my $type (@mailings) {
14794:             foreach my $item (@contacts) {
14795:                 if (ref($currsetting{$type}) eq 'HASH') {
14796:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
14797:                         push(@{$changes{$type}},$item);
14798:                     }
14799:                 } else {
14800:                     push(@{$changes{$type}},@{$newsetting{$type}});
14801:                 }
14802:             }
14803:             if ($others{$type} ne $currsetting{$type}{'others'}) {
14804:                 push(@{$changes{$type}},'others');
14805:             }
14806:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14807:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
14808:                     push(@{$changes{$type}},'bcc'); 
14809:                 }
14810:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
14811:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
14812:                     push(@{$changes{$type}},'include');
14813:                 }
14814:             }
14815:         }
14816:         if (ref($fields) eq 'ARRAY') {
14817:             if (ref($currsetting{'helpform'}) eq 'HASH') {
14818:                 foreach my $field (@{$fields}) {
14819:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
14820:                         push(@{$changes{'helpform'}},$field);
14821:                     }
14822:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
14823:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
14824:                             push(@{$changes{'helpform'}},'maxsize');
14825:                         }
14826:                     }
14827:                 }
14828:             } else {
14829:                 foreach my $field (@{$fields}) {
14830:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
14831:                         push(@{$changes{'helpform'}},$field);
14832:                     }
14833:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
14834:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
14835:                             push(@{$changes{'helpform'}},'maxsize');
14836:                         }
14837:                     }
14838:                 }
14839:             }
14840:         }
14841:         if (@statuses) {
14842:             if (ref($currsetting{'overrides'}) eq 'HASH') {
14843:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
14844:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
14845:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
14846:                             foreach my $item (@contacts,'bcc','others','include') {
14847:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) {
14848:                                     push(@{$changes{'overrides'}},$key);
14849:                                     last;
14850:                                 }
14851:                             }
14852:                         } else {
14853:                             push(@{$changes{'overrides'}},$key);
14854:                         }
14855:                     }
14856:                 }
14857:                 foreach my $key (@overrides) {
14858:                     unless (exists($currsetting{'overrides'}{$key})) {
14859:                         push(@{$changes{'overrides'}},$key);
14860:                     }
14861:                 }
14862:             } else {
14863:                 foreach my $key (@overrides) {
14864:                     push(@{$changes{'overrides'}},$key);
14865:                 }
14866:             }
14867:         }
14868:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
14869:             foreach my $key ('excluded','weights','threshold','sysmail') {
14870:                 if ($key eq 'excluded') {
14871:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
14872:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
14873:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
14874:                             (@{$currsetting{'lonstatus'}{$key}})) {
14875:                             my @diffs =
14876:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
14877:                                                                    $currsetting{'lonstatus'}{$key});
14878:                             if (@diffs) {
14879:                                 push(@{$changes{'lonstatus'}},$key);
14880:                             }
14881:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
14882:                             push(@{$changes{'lonstatus'}},$key);
14883:                         }
14884:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
14885:                              (@{$currsetting{'lonstatus'}{$key}})) {
14886:                         push(@{$changes{'lonstatus'}},$key);
14887:                     }
14888:                 } elsif ($key eq 'weights') {
14889:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
14890:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
14891:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
14892:                             foreach my $type ('E','W','N','U') {
14893:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
14894:                                         $currsetting{'lonstatus'}{$key}{$type}) {
14895:                                     push(@{$changes{'lonstatus'}},$key);
14896:                                     last;
14897:                                 }
14898:                             }
14899:                         } else {
14900:                             foreach my $type ('E','W','N','U') {
14901:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
14902:                                     push(@{$changes{'lonstatus'}},$key);
14903:                                     last;
14904:                                 }
14905:                             }
14906:                         }
14907:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
14908:                         foreach my $type ('E','W','N','U') {
14909:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
14910:                                 push(@{$changes{'lonstatus'}},$key);
14911:                                 last;
14912:                             }
14913:                         }
14914:                     }
14915:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
14916:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
14917:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
14918:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
14919:                                 push(@{$changes{'lonstatus'}},$key);
14920:                             }
14921:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
14922:                             push(@{$changes{'lonstatus'}},$key);
14923:                         }
14924:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
14925:                         push(@{$changes{'lonstatus'}},$key);
14926:                     }
14927:                 }
14928:             }
14929:         } else {
14930:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
14931:                 foreach my $key ('excluded','weights','threshold','sysmail') {
14932:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
14933:                         push(@{$changes{'lonstatus'}},$key);
14934:                     }
14935:                 }
14936:             }
14937:         }
14938:     } else {
14939:         my %default;
14940:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
14941:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
14942:         $default{'errormail'} = 'adminemail';
14943:         $default{'packagesmail'} = 'adminemail';
14944:         $default{'helpdeskmail'} = 'supportemail';
14945:         $default{'otherdomsmail'} = 'supportemail';
14946:         $default{'lonstatusmail'} = 'adminemail';
14947:         $default{'requestsmail'} = 'adminemail';
14948:         $default{'updatesmail'} = 'adminemail';
14949:         $default{'hostipmail'} = 'adminemail';
14950:         foreach my $item (@contacts) {
14951:            if ($to{$item} ne $default{$item}) {
14952:                $changes{$item} = 1;
14953:            }
14954:         }
14955:         foreach my $type (@mailings) {
14956:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
14957:                 push(@{$changes{$type}},@{$newsetting{$type}});
14958:             }
14959:             if ($others{$type} ne '') {
14960:                 push(@{$changes{$type}},'others');
14961:             }
14962:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14963:                 if ($bcc{$type} ne '') {
14964:                     push(@{$changes{$type}},'bcc');
14965:                 }
14966:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
14967:                     push(@{$changes{$type}},'include');
14968:                 }
14969:             }
14970:         }
14971:         if (ref($fields) eq 'ARRAY') {
14972:             foreach my $field (@{$fields}) {
14973:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
14974:                     push(@{$changes{'helpform'}},$field);
14975:                 }
14976:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
14977:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
14978:                         push(@{$changes{'helpform'}},'maxsize');
14979:                     }
14980:                 }
14981:             }
14982:         }
14983:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
14984:             foreach my $key ('excluded','weights','threshold','sysmail') {
14985:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
14986:                     push(@{$changes{'lonstatus'}},$key);
14987:                 }
14988:             }
14989:         }
14990:     }
14991:     foreach my $item (@toggles) {
14992:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
14993:             $changes{$item} = 1;
14994:         } elsif ((!$env{'form.'.$item}) &&
14995:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
14996:             $changes{$item} = 1;
14997:         }
14998:     }
14999:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
15000:                                              $dom);
15001:     if ($putresult eq 'ok') {
15002:         if (keys(%changes) > 0) {
15003:             &Apache::loncommon::devalidate_domconfig_cache($dom);
15004:             if (ref($lastactref) eq 'HASH') {
15005:                 $lastactref->{'domainconfig'} = 1;
15006:             }
15007:             my ($titles,$short_titles)  = &contact_titles();
15008:             $resulttext = &mt('Changes made:').'<ul>';
15009:             foreach my $item (@contacts) {
15010:                 if ($changes{$item}) {
15011:                     $resulttext .= '<li>'.$titles->{$item}.
15012:                                     &mt(' set to: ').
15013:                                     '<span class="LC_cusr_emph">'.
15014:                                     $to{$item}.'</span></li>';
15015:                 }
15016:             }
15017:             foreach my $type (@mailings) {
15018:                 if (ref($changes{$type}) eq 'ARRAY') {
15019:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15020:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
15021:                     } else {
15022:                         $resulttext .= '<li>'.$titles->{$type}.': ';
15023:                     }
15024:                     my @text;
15025:                     foreach my $item (@{$newsetting{$type}}) {
15026:                         push(@text,$short_titles->{$item});
15027:                     }
15028:                     if ($others{$type} ne '') {
15029:                         push(@text,$others{$type});
15030:                     }
15031:                     if (@text) {
15032:                         $resulttext .= '<span class="LC_cusr_emph">'.
15033:                                        join(', ',@text).'</span>';
15034:                     }
15035:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15036:                         if ($bcc{$type} ne '') {
15037:                             my $bcctext;
15038:                             if (@text) {
15039:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
15040:                             } else {
15041:                                 $bcctext = '(Bcc)';
15042:                             }
15043:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
15044:                         } elsif (!@text) {
15045:                             $resulttext .= &mt('No one');
15046:                         }
15047:                         if ($includestr{$type} ne '') {
15048:                             if ($includeloc{$type} eq 'b') {
15049:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
15050:                             } elsif ($includeloc{$type} eq 's') {
15051:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
15052:                             }
15053:                         }
15054:                     } elsif (!@text) {
15055:                         $resulttext .= &mt('No recipients');
15056:                     }
15057:                     $resulttext .= '</li>';
15058:                 }
15059:             }
15060:             if (ref($changes{'overrides'}) eq 'ARRAY') {
15061:                 my @deletions;
15062:                 foreach my $type (@{$changes{'overrides'}}) {
15063:                     if ($usertypeshash{$type}) {
15064:                         if (grep(/^\Q$type\E/,@overrides)) {
15065:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
15066:                                                       $usertypeshash{$type}).'<ul><li>';
15067:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
15068:                                 my @text;
15069:                                 foreach my $item (@contacts) {
15070:                                     if ($newsetting{'override_'.$type}{$item}) {
15071:                                         push(@text,$short_titles->{$item});
15072:                                     }
15073:                                 }
15074:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
15075:                                     push(@text,$newsetting{'override_'.$type}{'others'});
15076:                                 }
15077: 
15078:                                 if (@text) {
15079:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
15080:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
15081:                                 }
15082:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
15083:                                     my $bcctext;
15084:                                     if (@text) {
15085:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
15086:                                     } else {
15087:                                         $bcctext = '(Bcc)';
15088:                                     }
15089:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
15090:                                 } elsif (!@text) {
15091:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
15092:                                 }
15093:                                 $resulttext .= '</li>';
15094:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
15095:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
15096:                                     if ($loc eq 'b') {
15097:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
15098:                                     } elsif ($loc eq 's') {
15099:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
15100:                                     }
15101:                                 }
15102:                             }
15103:                             $resulttext .= '</li></ul></li>';
15104:                         } else {
15105:                             push(@deletions,$usertypeshash{$type});
15106:                         }
15107:                     }
15108:                 }
15109:                 if (@deletions) {
15110:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
15111:                                               join(', ',@deletions)).'</li>';
15112:                 }
15113:             }
15114:             my @offon = ('off','on');
15115:             my $corelink = &core_link_msu();
15116:             if ($changes{'reporterrors'}) {
15117:                 $resulttext .= '<li>'.
15118:                                &mt('E-mail error reports to [_1] set to "'.
15119:                                    $offon[$env{'form.reporterrors'}].'".',
15120:                                    $corelink).
15121:                                '</li>';
15122:             }
15123:             if ($changes{'reportupdates'}) {
15124:                 $resulttext .= '<li>'.
15125:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
15126:                                     $offon[$env{'form.reportupdates'}].'".',
15127:                                     $corelink).
15128:                                 '</li>';
15129:             }
15130:             if ($changes{'reportstatus'}) {
15131:                 $resulttext .= '<li>'.
15132:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
15133:                                     $offon[$env{'form.reportstatus'}].'".',
15134:                                     $corelink).
15135:                                 '</li>';
15136:             }
15137:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
15138:                 $resulttext .= '<li>'.
15139:                                &mt('Nightly status check e-mail settings').':<ul>';
15140:                 my (%defval,%use_def,%shown);
15141:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
15142:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
15143:                 $defval{'weights'} =
15144:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
15145:                 $defval{'excluded'} = &mt('None');
15146:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
15147:                     foreach my $item ('threshold','sysmail','weights','excluded') {
15148:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
15149:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
15150:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
15151:                             } elsif ($item eq 'weights') {
15152:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
15153:                                     foreach my $type ('E','W','N','U') {
15154:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
15155:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
15156:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
15157:                                         } else {
15158:                                             $shown{$item} .= $lonstatus_defs->{$type};
15159:                                         }
15160:                                         $shown{$item} .= ', ';
15161:                                     }
15162:                                     $shown{$item} =~ s/, $//;
15163:                                 } else {
15164:                                     $shown{$item} = $defval{$item};
15165:                                 }
15166:                             } elsif ($item eq 'excluded') {
15167:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
15168:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
15169:                                 } else {
15170:                                     $shown{$item} = $defval{$item};
15171:                                 }
15172:                             }
15173:                         } else {
15174:                             $shown{$item} = $defval{$item};
15175:                         }
15176:                     }
15177:                 } else {
15178:                     foreach my $item ('threshold','weights','excluded','sysmail') {
15179:                         $shown{$item} = $defval{$item};
15180:                     }
15181:                 }
15182:                 foreach my $item ('threshold','weights','excluded','sysmail') {
15183:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
15184:                                           $shown{$item}).'</li>';
15185:                 }
15186:                 $resulttext .= '</ul></li>';
15187:             }
15188:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
15189:                 my (@optional,@required,@unused,$maxsizechg);
15190:                 foreach my $field (@{$changes{'helpform'}}) {
15191:                     if ($field eq 'maxsize') {
15192:                         $maxsizechg = 1;
15193:                         next;
15194:                     }
15195:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
15196:                         push(@optional,$field);
15197:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
15198:                         push(@unused,$field);
15199:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
15200:                         push(@required,$field);
15201:                     }
15202:                 }
15203:                 if (@optional) {
15204:                     $resulttext .= '<li>'.
15205:                                    &mt('Help form fields changed to "Optional": [_1].',
15206:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
15207:                                    '</li>';
15208:                 }
15209:                 if (@required) {
15210:                     $resulttext .= '<li>'.
15211:                                    &mt('Help form fields changed to "Required": [_1].',
15212:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
15213:                                    '</li>';
15214:                 }
15215:                 if (@unused) {
15216:                     $resulttext .= '<li>'.
15217:                                    &mt('Help form fields changed to "Not shown": [_1].',
15218:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
15219:                                    '</li>';
15220:                 }
15221:                 if ($maxsizechg) {
15222:                     $resulttext .= '<li>'.
15223:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
15224:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
15225:                                    '</li>';
15226:                 }
15227:             }
15228:             $resulttext .= '</ul>';
15229:         } else {
15230:             $resulttext = &mt('No changes made to contacts and form settings');
15231:         }
15232:     } else {
15233:         $resulttext = '<span class="LC_error">'.
15234:             &mt('An error occurred: [_1]',$putresult).'</span>';
15235:     }
15236:     return $resulttext;
15237: }
15238: 
15239: sub modify_passwords {
15240:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
15241:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
15242:         $updatedefaults,$updateconf);
15243:     my $customfn = 'resetpw.html';
15244:     if (ref($domconfig{'passwords'}) eq 'HASH') {
15245:         %current = %{$domconfig{'passwords'}};
15246:     }
15247:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15248:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15249:     if (ref($types) eq 'ARRAY') {
15250:         @oktypes = @{$types};
15251:     }
15252:     push(@oktypes,'default');
15253: 
15254:     my %titles = &Apache::lonlocal::texthash (
15255:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
15256:         intauth_check  => 'Check bcrypt cost if authenticated',
15257:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
15258:         permanent      => 'Permanent e-mail address',
15259:         critical       => 'Critical notification address',
15260:         notify         => 'Notification address',
15261:         min            => 'Minimum password length',
15262:         max            => 'Maximum password length',
15263:         chars          => 'Required characters',
15264:         numsaved       => 'Number of previous passwords to save',
15265:         reset          => 'Resetting Forgotten Password',
15266:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
15267:         rules          => 'Rules for LON-CAPA Passwords',
15268:         crsownerchg    => 'Course Owner Changing Student Passwords',
15269:         username       => 'Username',
15270:         email          => 'E-mail address',
15271:     );
15272: 
15273: #
15274: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
15275: #
15276:     my (%curr_defaults,%save_defaults);
15277:     if (ref($domconfig{'defaults'}) eq 'HASH') {
15278:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
15279:             if ($key =~ /^intauth_(cost|check|switch)$/) {
15280:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
15281:             } else {
15282:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
15283:             }
15284:         }
15285:     }
15286:     my %staticdefaults = (
15287:         'resetlink'      => 2,
15288:         'resetcase'      => \@oktypes,
15289:         'resetprelink'   => 'both',
15290:         'resetemail'     => ['critical','notify','permanent'],
15291:         'intauth_cost'   => 10,
15292:         'intauth_check'  => 0,
15293:         'intauth_switch' => 0,
15294:     );
15295:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
15296:     foreach my $type (@oktypes) {
15297:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
15298:     }
15299:     my $linklife = $env{'form.passwords_link'};
15300:     $linklife =~ s/^\s+|\s+$//g;
15301:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
15302:         $newvalues{'resetlink'} = $linklife;
15303:         if ($current{'resetlink'}) {
15304:             if ($current{'resetlink'} ne $linklife) {
15305:                 $changes{'reset'} = 1;
15306:             }
15307:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
15308:             if ($staticdefaults{'resetlink'} ne $linklife) {
15309:                 $changes{'reset'} = 1;
15310:             }
15311:         }
15312:     } elsif ($current{'resetlink'}) {
15313:         $changes{'reset'} = 1;
15314:     }
15315:     my @casesens;
15316:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
15317:     foreach my $case (sort(@posscase)) {
15318:         if (grep(/^\Q$case\E$/,@oktypes)) {
15319:             push(@casesens,$case);
15320:         }
15321:     }
15322:     $newvalues{'resetcase'} = \@casesens;
15323:     if (ref($current{'resetcase'}) eq 'ARRAY') {
15324:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
15325:         if (@diffs > 0) {
15326:             $changes{'reset'} = 1;
15327:         }
15328:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
15329:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
15330:         if (@diffs > 0) {
15331:             $changes{'reset'} = 1;
15332:         }
15333:     }
15334:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
15335:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
15336:         if (exists($current{'resetprelink'})) {
15337:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
15338:                 $changes{'reset'} = 1;
15339:             }
15340:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
15341:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
15342:                 $changes{'reset'} = 1;
15343:             }
15344:         }
15345:     } elsif ($current{'resetprelink'}) {
15346:         $changes{'reset'} = 1;
15347:     }
15348:     foreach my $type (@oktypes) {
15349:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
15350:         my @postlink;
15351:         foreach my $item (sort(@possplink)) {
15352:             if ($item =~ /^(email|username)$/) {
15353:                 push(@postlink,$item);
15354:             }
15355:         }
15356:         $newvalues{'resetpostlink'}{$type} = \@postlink;
15357:         unless ($changes{'reset'}) {
15358:             if (ref($current{'resetpostlink'}) eq 'HASH') {
15359:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
15360:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
15361:                     if (@diffs > 0) {
15362:                         $changes{'reset'} = 1;
15363:                     }
15364:                 } else {
15365:                     $changes{'reset'} = 1;
15366:                 }
15367:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
15368:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
15369:                 if (@diffs > 0) {
15370:                     $changes{'reset'} = 1;
15371:                 }
15372:             }
15373:         }
15374:     }
15375:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
15376:     my @resetemail;
15377:     foreach my $item (sort(@possemailsrc)) {
15378:         if ($item =~ /^(permanent|critical|notify)$/) {
15379:             push(@resetemail,$item);
15380:         }
15381:     }
15382:     $newvalues{'resetemail'} = \@resetemail;
15383:     unless ($changes{'reset'}) {
15384:         if (ref($current{'resetemail'}) eq 'ARRAY') {
15385:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
15386:             if (@diffs > 0) {
15387:                 $changes{'reset'} = 1;
15388:             }
15389:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
15390:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
15391:             if (@diffs > 0) {
15392:                 $changes{'reset'} = 1;
15393:             }
15394:         }
15395:     }
15396:     if ($env{'form.passwords_stdtext'} == 0) {
15397:         $newvalues{'resetremove'} = 1;
15398:         unless ($current{'resetremove'}) {
15399:             $changes{'reset'} = 1;
15400:         }
15401:     } elsif ($current{'resetremove'}) {
15402:         $changes{'reset'} = 1;
15403:     }
15404:     if ($env{'form.passwords_customfile.filename'} ne '') {
15405:         my $servadm = $r->dir_config('lonAdmEMail');
15406:         my ($configuserok,$author_ok,$switchserver) =
15407:             &config_check($dom,$confname,$servadm);
15408:         my $error;
15409:         if ($configuserok eq 'ok') {
15410:             if ($switchserver) {
15411:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
15412:             } else {
15413:                 if ($author_ok eq 'ok') {
15414:                     my $modified = [];
15415:                     my ($result,$customurl) =
15416:                         &Apache::lonconfigsettings::publishlogo($r,'upload','passwords_customfile',$dom,
15417:                                                                 $confname,'customtext/resetpw','','',$customfn,
15418:                                                                 $modified);
15419:                     if ($result eq 'ok') {
15420:                         $newvalues{'resetcustom'} = $customurl;
15421:                         $changes{'reset'} = 1;
15422:                         &update_modify_urls($r,$modified);
15423:                     } else {
15424:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
15425:                     }
15426:                 } else {
15427:                     $error = &mt("Upload of [_1] failed because an author role could not be assigned to a Domain Configuration user ([_2]) in domain: [_3].  Error was: [_4].",$customfn,$confname,$dom,$author_ok);
15428:                 }
15429:             }
15430:         } else {
15431:             $error = &mt("Upload of [_1] failed because a Domain Configuration user ([_2]) could not be created in domain: [_3].  Error was: [_4].",$customfn,$confname,$dom,$configuserok);
15432:         }
15433:         if ($error) {
15434:             &Apache::lonnet::logthis($error);
15435:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15436:         }
15437:     } elsif ($current{'resetcustom'}) {
15438:         if ($env{'form.passwords_custom_del'}) {
15439:             $changes{'reset'} = 1;
15440:         } else {
15441:             $newvalues{'resetcustom'} = $current{'resetcustom'};
15442:         }
15443:     }
15444:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
15445:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
15446:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
15447:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
15448:             $changes{'intauth'} = 1;
15449:         }
15450:     } else {
15451:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
15452:     }
15453:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
15454:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
15455:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
15456:             $changes{'intauth'} = 1;
15457:         }
15458:     } else {
15459:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
15460:     }
15461:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
15462:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
15463:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
15464:             $changes{'intauth'} = 1;
15465:         }
15466:     } else {
15467:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
15468:     }
15469:     foreach my $item ('cost','check','switch') {
15470:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
15471:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
15472:             $updatedefaults = 1;
15473:         }
15474:     }
15475:     &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
15476:     my %crsownerchg = (
15477:                         by => [],
15478:                         for => [],
15479:                       );
15480:     foreach my $item ('by','for') {
15481:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
15482:         foreach my $type (sort(@posstypes)) {
15483:             if (grep(/^\Q$type\E$/,@oktypes)) {
15484:                 push(@{$crsownerchg{$item}},$type);
15485:             }
15486:         }
15487:     }
15488:     $newvalues{'crsownerchg'} = \%crsownerchg;
15489:     if (ref($current{'crsownerchg'}) eq 'HASH') {
15490:         foreach my $item ('by','for') {
15491:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
15492:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
15493:                 if (@diffs > 0) {
15494:                     $changes{'crsownerchg'} = 1;
15495:                     last;
15496:                 }
15497:             }
15498:         }
15499:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
15500:         foreach my $item ('by','for') {
15501:             if (@{$crsownerchg{$item}} > 0) {
15502:                 $changes{'crsownerchg'} = 1;
15503:                 last;
15504:             }
15505:         }
15506:     }
15507: 
15508:     my %confighash = (
15509:                         defaults  => \%save_defaults,
15510:                         passwords => \%newvalues,
15511:                      );
15512:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
15513: 
15514:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
15515:     if ($putresult eq 'ok') {
15516:         if (keys(%changes) > 0) {
15517:             $resulttext = &mt('Changes made: ').'<ul>';
15518:             foreach my $key ('reset','intauth','rules','crsownerchg') {
15519:                 if ($changes{$key}) {
15520:                     unless ($key eq 'intauth') {
15521:                         $updateconf = 1;
15522:                     }
15523:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
15524:                     if ($key eq 'reset') {
15525:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
15526:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
15527:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
15528:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
15529:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
15530:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
15531:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
15532:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
15533:                             }
15534:                         } else {
15535:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
15536:                         }
15537:                         if ($confighash{'passwords'}{'resetlink'}) {
15538:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
15539:                         } else {
15540:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
15541:                                                   &mt('Will default to 2 hours').'</li>';
15542:                         }
15543:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
15544:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
15545:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
15546:                             } else {
15547:                                 my $casesens;
15548:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
15549:                                     if ($type eq 'default') {
15550:                                         $casesens .= $othertitle.', ';
15551:                                     } elsif ($usertypes->{$type} ne '') {
15552:                                         $casesens .= $usertypes->{$type}.', ';
15553:                                     }
15554:                                 }
15555:                                 $casesens =~ s/\Q, \E$//;
15556:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
15557:                             }
15558:                         } else {
15559:                             $resulttext .= '<li>'.&mt('Case-sensitivity not set for "Forgot Password" web form').' '.&mt('Will default to case-sensitive for username and/or e-mail address for all').'</li>';
15560:                         }
15561:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
15562:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
15563:                         } else {
15564:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
15565:                         }
15566:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
15567:                             my $output;
15568:                             if (ref($types) eq 'ARRAY') {
15569:                                 foreach my $type (@{$types}) {
15570:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
15571:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
15572:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
15573:                                         } else {
15574:                                             $output .= $usertypes->{$type}.' -- '.
15575:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
15576:                                         }
15577:                                     }
15578:                                 }
15579:                             }
15580:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
15581:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
15582:                                     $output .= $othertitle.' -- '.&mt('none');
15583:                                 } else {
15584:                                     $output .= $othertitle.' -- '.
15585:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
15586:                                 }
15587:                             }
15588:                             if ($output) {
15589:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
15590:                             } else {
15591:                                 $resulttext .= '<li>'.&mt('Information required for new password form not set.').' '.&mt('Will default to requiring both the username and an e-mail address').'</li>';
15592:                             }
15593:                         } else {
15594:                             $resulttext .= '<li>'.&mt('Information required for new password form not set.').' '.&mt('Will default to requiring both the username and an e-mail address').'</li>';
15595:                         }
15596:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
15597:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
15598:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
15599:                             } else {
15600:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
15601:                             }
15602:                         } else {
15603:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
15604:                         }
15605:                         if ($confighash{'passwords'}{'resetremove'}) {
15606:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
15607:                         } else {
15608:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
15609:                         }
15610:                         if ($confighash{'passwords'}{'resetcustom'}) {
15611:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
15612:                                                                             &mt('custom text'),600,500,undef,undef,
15613:                                                                             undef,undef,'background-color:#ffffff');
15614:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
15615:                         } else {
15616:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
15617:                         }
15618:                     } elsif ($key eq 'intauth') {
15619:                         foreach my $item ('cost','switch','check') {
15620:                             my $value = $save_defaults{$key.'_'.$item};
15621:                             if ($item eq 'switch') {
15622:                                 my %optiondesc = &Apache::lonlocal::texthash (
15623:                                                      0 => 'No',
15624:                                                      1 => 'Yes',
15625:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
15626:                                                  );
15627:                                 if ($value =~ /^(0|1|2)$/) {
15628:                                     $value = $optiondesc{$value};
15629:                                 } else {
15630:                                     $value = &mt('none -- defaults to No');
15631:                                 }
15632:                             } elsif ($item eq 'check') {
15633:                                 my %optiondesc = &Apache::lonlocal::texthash (
15634:                                                      0 => 'No',
15635:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
15636:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
15637:                                                  );
15638:                                 if ($value =~ /^(0|1|2)$/) {
15639:                                     $value = $optiondesc{$value};
15640:                                 } else {
15641:                                     $value = &mt('none -- defaults to No');
15642:                                 }
15643:                             }
15644:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
15645:                         }
15646:                     } elsif ($key eq 'rules') {
15647:                         foreach my $rule ('min','max','numsaved') {
15648:                             if ($confighash{'passwords'}{$rule} eq '') {
15649:                                 if ($rule eq 'min') {
15650:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
15651:                                                    ' '.&mt('Default of [_1] will be used',
15652:                                                            $Apache::lonnet::passwdmin).'</li>';
15653:                                 } else {
15654:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
15655:                                 }
15656:                             } else {
15657:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
15658:                             }
15659:                         }
15660:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
15661:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
15662:                                 my %rulenames = &Apache::lonlocal::texthash(
15663:                                                      uc => 'At least one upper case letter',
15664:                                                      lc => 'At least one lower case letter',
15665:                                                      num => 'At least one number',
15666:                                                      spec => 'At least one non-alphanumeric',
15667:                                                    );
15668:                                 my $needed = '<ul><li>'.
15669:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
15670:                                              '</li></ul>';
15671:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
15672:                             } else {
15673:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
15674:                             }
15675:                         } else {
15676:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
15677:                         }
15678:                     } elsif ($key eq 'crsownerchg') {
15679:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
15680:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
15681:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
15682:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
15683:                             } else {
15684:                                 my %crsownerstr;
15685:                                 foreach my $item ('by','for') {
15686:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
15687:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
15688:                                             if ($type eq 'default') {
15689:                                                 $crsownerstr{$item} .= $othertitle.', ';
15690:                                             } elsif ($usertypes->{$type} ne '') {
15691:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
15692:                                             }
15693:                                         }
15694:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
15695:                                     }
15696:                                 }
15697:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
15698:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
15699:                             }
15700:                         } else {
15701:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
15702:                         }
15703:                     }
15704:                     $resulttext .= '</ul></li>';
15705:                 }
15706:             }
15707:             $resulttext .= '</ul>';
15708:         } else {
15709:             $resulttext = &mt('No changes made to password settings');
15710:         }
15711:         my $cachetime = 24*60*60;
15712:         if ($updatedefaults) {
15713:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15714:             if (ref($lastactref) eq 'HASH') {
15715:                 $lastactref->{'domdefaults'} = 1;
15716:             }
15717:         }
15718:         if ($updateconf) {
15719:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
15720:             if (ref($lastactref) eq 'HASH') {
15721:                 $lastactref->{'passwdconf'} = 1;
15722:             }
15723:         }
15724:     } else {
15725:         $resulttext = '<span class="LC_error">'.
15726:             &mt('An error occurred: [_1]',$putresult).'</span>';
15727:     }
15728:     if ($errors) {
15729:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
15730:                        $errors.'</ul></p>';
15731:     }
15732:     return $resulttext;
15733: }
15734: 
15735: sub password_rule_changes {
15736:     my ($prefix,$newvalues,$current,$changes) = @_;
15737:     return unless ((ref($newvalues) eq 'HASH') &&
15738:                    (ref($current) eq 'HASH') &&
15739:                    (ref($changes) eq 'HASH'));
15740:     my (@rules,%staticdefaults);
15741:     if ($prefix eq 'passwords') {
15742:         @rules = ('min','max','numsaved');
15743:     } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
15744:         @rules = ('min','max');
15745:     }
15746:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
15747:     foreach my $rule (@rules) {
15748:         $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
15749:         my $ruleok;
15750:         if ($rule eq 'min') {
15751:             if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
15752:                 if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
15753:                     $ruleok = 1;
15754:                 }
15755:             }
15756:         } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
15757:                  ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
15758:             $ruleok = 1;
15759:         }
15760:         if ($ruleok) {
15761:             $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
15762:             if (exists($current->{$rule})) {
15763:                 if ($newvalues->{$rule} ne $current->{$rule}) {
15764:                     $changes->{'rules'} = 1;
15765:                 }
15766:             } elsif ($rule eq 'min') {
15767:                 if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
15768:                     $changes->{'rules'} = 1;
15769:                 }
15770:             } else {
15771:                 $changes->{'rules'} = 1;
15772:             }
15773:         } elsif (exists($current->{$rule})) {
15774:             $changes->{'rules'} = 1;
15775:         }
15776:     }
15777:     my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
15778:     my @chars;
15779:     foreach my $item (sort(@posschars)) {
15780:         if ($item =~ /^(uc|lc|num|spec)$/) {
15781:             push(@chars,$item);
15782:         }
15783:     }
15784:     $newvalues->{'chars'} = \@chars;
15785:     unless ($changes->{'rules'}) {
15786:         if (ref($current->{'chars'}) eq 'ARRAY') {
15787:             my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
15788:             if (@diffs > 0) {
15789:                 $changes->{'rules'} = 1;
15790:             }
15791:         } else {
15792:             if (@chars > 0) {
15793:                 $changes->{'rules'} = 1;
15794:             }
15795:         }
15796:     }
15797:     return;
15798: }
15799: 
15800: sub modify_usercreation {
15801:     my ($dom,%domconfig) = @_;
15802:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
15803:     my $warningmsg;
15804:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
15805:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
15806:             if ($key eq 'cancreate') {
15807:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
15808:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
15809:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
15810:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15811:                         } else {
15812:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15813:                         }
15814:                     }
15815:                 }
15816:             } elsif ($key eq 'email_rule') {
15817:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
15818:             } else {
15819:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
15820:             }
15821:         }
15822:     }
15823:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
15824:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
15825:     my @contexts = ('author','course','requestcrs');
15826:     foreach my $item(@contexts) {
15827:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
15828:     }
15829:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15830:         foreach my $item (@contexts) {
15831:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
15832:                 push(@{$changes{'cancreate'}},$item);
15833:             }
15834:         }
15835:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
15836:         foreach my $item (@contexts) {
15837:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
15838:                 if ($cancreate{$item} ne 'any') {
15839:                     push(@{$changes{'cancreate'}},$item);
15840:                 }
15841:             } else {
15842:                 if ($cancreate{$item} ne 'none') {
15843:                     push(@{$changes{'cancreate'}},$item);
15844:                 }
15845:             }
15846:         }
15847:     } else {
15848:         foreach my $item (@contexts)  {
15849:             push(@{$changes{'cancreate'}},$item);
15850:         }
15851:     }
15852: 
15853:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
15854:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
15855:             if (!grep(/^\Q$type\E$/,@username_rule)) {
15856:                 push(@{$changes{'username_rule'}},$type);
15857:             }
15858:         }
15859:         foreach my $type (@username_rule) {
15860:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
15861:                 push(@{$changes{'username_rule'}},$type);
15862:             }
15863:         }
15864:     } else {
15865:         push(@{$changes{'username_rule'}},@username_rule);
15866:     }
15867: 
15868:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
15869:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
15870:             if (!grep(/^\Q$type\E$/,@id_rule)) {
15871:                 push(@{$changes{'id_rule'}},$type);
15872:             }
15873:         }
15874:         foreach my $type (@id_rule) {
15875:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
15876:                 push(@{$changes{'id_rule'}},$type);
15877:             }
15878:         }
15879:     } else {
15880:         push(@{$changes{'id_rule'}},@id_rule);
15881:     }
15882: 
15883:     my @authen_contexts = ('author','course','domain');
15884:     my @authtypes = ('int','krb4','krb5','loc','lti');
15885:     my %authhash;
15886:     foreach my $item (@authen_contexts) {
15887:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
15888:         foreach my $auth (@authtypes) {
15889:             if (grep(/^\Q$auth\E$/,@authallowed)) {
15890:                 $authhash{$item}{$auth} = 1;
15891:             } else {
15892:                 $authhash{$item}{$auth} = 0;
15893:             }
15894:         }
15895:     }
15896:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
15897:         foreach my $item (@authen_contexts) {
15898:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
15899:                 foreach my $auth (@authtypes) {
15900:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
15901:                         push(@{$changes{'authtypes'}},$item);
15902:                         last;
15903:                     }
15904:                 }
15905:             }
15906:         }
15907:     } else {
15908:         foreach my $item (@authen_contexts) {
15909:             push(@{$changes{'authtypes'}},$item);
15910:         }
15911:     }
15912: 
15913:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
15914:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
15915:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
15916:     $save_usercreate{'id_rule'} = \@id_rule;
15917:     $save_usercreate{'username_rule'} = \@username_rule,
15918:     $save_usercreate{'authtypes'} = \%authhash;
15919: 
15920:     my %usercreation_hash =  (
15921:         usercreation     => \%save_usercreate,
15922:     );
15923: 
15924:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
15925:                                              $dom);
15926: 
15927:     if ($putresult eq 'ok') {
15928:         if (keys(%changes) > 0) {
15929:             $resulttext = &mt('Changes made:').'<ul>';
15930:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
15931:                 my %lt = &usercreation_types();
15932:                 foreach my $type (@{$changes{'cancreate'}}) {
15933:                     my $chgtext = $lt{$type}.', ';
15934:                     if ($cancreate{$type} eq 'none') {
15935:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
15936:                     } elsif ($cancreate{$type} eq 'any') {
15937:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
15938:                     } elsif ($cancreate{$type} eq 'official') {
15939:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
15940:                     } elsif ($cancreate{$type} eq 'unofficial') {
15941:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
15942:                     }
15943:                     $resulttext .= '<li>'.$chgtext.'</li>';
15944:                 }
15945:             }
15946:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
15947:                 my ($rules,$ruleorder) = 
15948:                     &Apache::lonnet::inst_userrules($dom,'username');
15949:                 my $chgtext = '<ul>';
15950:                 foreach my $type (@username_rule) {
15951:                     if (ref($rules->{$type}) eq 'HASH') {
15952:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
15953:                     }
15954:                 }
15955:                 $chgtext .= '</ul>';
15956:                 if (@username_rule > 0) {
15957:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
15958:                 } else {
15959:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
15960:                 }
15961:             }
15962:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
15963:                 my ($idrules,$idruleorder) = 
15964:                     &Apache::lonnet::inst_userrules($dom,'id');
15965:                 my $chgtext = '<ul>';
15966:                 foreach my $type (@id_rule) {
15967:                     if (ref($idrules->{$type}) eq 'HASH') {
15968:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
15969:                     }
15970:                 }
15971:                 $chgtext .= '</ul>';
15972:                 if (@id_rule > 0) {
15973:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
15974:                 } else {
15975:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
15976:                 }
15977:             }
15978:             my %authname = &authtype_names();
15979:             my %context_title = &context_names();
15980:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
15981:                 my $chgtext = '<ul>';
15982:                 foreach my $type (@{$changes{'authtypes'}}) {
15983:                     my @allowed;
15984:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
15985:                     foreach my $auth (@authtypes) {
15986:                         if ($authhash{$type}{$auth}) {
15987:                             push(@allowed,$authname{$auth});
15988:                         }
15989:                     }
15990:                     if (@allowed > 0) {
15991:                         $chgtext .= join(', ',@allowed).'</li>';
15992:                     } else {
15993:                         $chgtext .= &mt('none').'</li>';
15994:                     }
15995:                 }
15996:                 $chgtext .= '</ul>';
15997:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
15998:                 $resulttext .= '</li>';
15999:             }
16000:             $resulttext .= '</ul>';
16001:         } else {
16002:             $resulttext = &mt('No changes made to user creation settings');
16003:         }
16004:     } else {
16005:         $resulttext = '<span class="LC_error">'.
16006:             &mt('An error occurred: [_1]',$putresult).'</span>';
16007:     }
16008:     if ($warningmsg ne '') {
16009:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
16010:     }
16011:     return $resulttext;
16012: }
16013: 
16014: sub modify_selfcreation {
16015:     my ($dom,$lastactref,%domconfig) = @_;
16016:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
16017:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
16018:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16019:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
16020:     if (ref($typesref) eq 'ARRAY') {
16021:         @types = @{$typesref};
16022:     }
16023:     if (ref($usertypesref) eq 'HASH') {
16024:         %usertypes = %{$usertypesref};
16025:     }
16026:     $usertypes{'default'} = $othertitle;
16027: #
16028: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
16029: #
16030:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
16031:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
16032:             if ($key eq 'cancreate') {
16033:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
16034:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
16035:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
16036:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
16037:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
16038:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
16039:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
16040:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
16041:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
16042:                         } else {
16043:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
16044:                         }
16045:                     }
16046:                 }
16047:             } elsif ($key eq 'email_rule') {
16048:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
16049:             } else {
16050:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
16051:             }
16052:         }
16053:     }
16054: #
16055: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
16056: #
16057:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
16058:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
16059:             if ($key eq 'selfcreate') {
16060:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
16061:             } else {
16062:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
16063:             }
16064:         }
16065:     }
16066: #
16067: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
16068: #
16069:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
16070:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
16071:             if ($key eq 'inststatusguest') {
16072:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
16073:             } else {
16074:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
16075:             }
16076:         }
16077:     }
16078: 
16079:     my @contexts = ('selfcreate');
16080:     @{$cancreate{'selfcreate'}} = ();
16081:     %{$cancreate{'emailusername'}} = ();
16082:     if (@types) {
16083:         @{$cancreate{'statustocreate'}} = ();
16084:     }
16085:     %{$cancreate{'selfcreateprocessing'}} = ();
16086:     %{$cancreate{'shibenv'}} = ();
16087:     %{$cancreate{'emailverified'}} = ();
16088:     %{$cancreate{'emailoptions'}} = ();
16089:     %{$cancreate{'emaildomain'}} = ();
16090:     my %selfcreatetypes = (
16091:                              sso   => 'users authenticated by institutional single sign on',
16092:                              login => 'users authenticated by institutional log-in',
16093:                              email => 'users verified by e-mail',
16094:                           );
16095: #
16096: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
16097: # is permitted.
16098: #
16099:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
16100: 
16101:     my (@statuses,%email_rule);
16102:     foreach my $item ('login','sso','email') {
16103:         if ($item eq 'email') {
16104:             if ($env{'form.cancreate_email'}) {
16105:                 if (@types) {
16106:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
16107:                     foreach my $status (@poss_statuses) {
16108:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
16109:                             push(@statuses,$status);
16110:                         }
16111:                     }
16112:                     $save_inststatus{'inststatusguest'} = \@statuses;
16113:                 } else {
16114:                     push(@statuses,'default');
16115:                 }
16116:                 if (@statuses) {
16117:                     my %curr_rule;
16118:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
16119:                         foreach my $type (@statuses) {
16120:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
16121:                         }
16122:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
16123:                         foreach my $type (@statuses) {
16124:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
16125:                         }
16126:                     }
16127:                     push(@{$cancreate{'selfcreate'}},'email');
16128:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
16129:                     my %curremaildom;
16130:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
16131:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
16132:                     }
16133:                     foreach my $type (@statuses) {
16134:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
16135:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
16136:                         }
16137:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
16138:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
16139:                         }
16140:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
16141: #
16142: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
16143: #
16144:                             my $chosen = $1;
16145:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
16146:                                 my $emaildom;
16147:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
16148:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type};
16149:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
16150:                                     if (ref($curremaildom{$type}) eq 'HASH') {
16151:                                         if (exists($curremaildom{$type}{$chosen})) {
16152:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
16153:                                                 push(@{$changes{'cancreate'}},'emaildomain');
16154:                                             }
16155:                                         } elsif ($emaildom ne '') {
16156:                                             push(@{$changes{'cancreate'}},'emaildomain');
16157:                                         }
16158:                                     } elsif ($emaildom ne '') {
16159:                                         push(@{$changes{'cancreate'}},'emaildomain');
16160:                                     }
16161:                                 }
16162:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
16163:                             } elsif ($chosen eq 'custom') {
16164:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
16165:                                 $email_rule{$type} = [];
16166:                                 if (ref($emailrules) eq 'HASH') {
16167:                                     foreach my $rule (@possemail_rules) {
16168:                                         if (exists($emailrules->{$rule})) {
16169:                                             push(@{$email_rule{$type}},$rule);
16170:                                         }
16171:                                     }
16172:                                 }
16173:                                 if (@{$email_rule{$type}}) {
16174:                                     $cancreate{'emailoptions'}{$type} = 'custom';
16175:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
16176:                                         if (@{$curr_rule{$type}} > 0) {
16177:                                             foreach my $rule (@{$curr_rule{$type}}) {
16178:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
16179:                                                     push(@{$changes{'email_rule'}},$type);
16180:                                                 }
16181:                                             }
16182:                                         }
16183:                                         foreach my $type (@{$email_rule{$type}}) {
16184:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
16185:                                                 push(@{$changes{'email_rule'}},$type);
16186:                                             }
16187:                                         }
16188:                                     } else {
16189:                                         push(@{$changes{'email_rule'}},$type);
16190:                                     }
16191:                                 }
16192:                             } else {
16193:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
16194:                             }
16195:                         }
16196:                     }
16197:                     if (@types) {
16198:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
16199:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
16200:                             if (@changed) {
16201:                                 push(@{$changes{'inststatus'}},'inststatusguest');
16202:                             }
16203:                         } else {
16204:                             push(@{$changes{'inststatus'}},'inststatusguest');
16205:                         }
16206:                     }
16207:                 } else {
16208:                     delete($env{'form.cancreate_email'});
16209:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
16210:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
16211:                             push(@{$changes{'inststatus'}},'inststatusguest');
16212:                         }
16213:                     }
16214:                 }
16215:             } else {
16216:                 $save_inststatus{'inststatusguest'} = [];
16217:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
16218:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
16219:                         push(@{$changes{'inststatus'}},'inststatusguest');
16220:                     }
16221:                 }
16222:             }
16223:         } else {
16224:             if ($env{'form.cancreate_'.$item}) {
16225:                 push(@{$cancreate{'selfcreate'}},$item);
16226:             }
16227:         }
16228:     }
16229:     my (%userinfo,%savecaptcha);
16230:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
16231: #
16232: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
16233: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
16234: #
16235: 
16236:     if ($env{'form.cancreate_email'}) {
16237:         push(@contexts,'emailusername');
16238:         if (@statuses) {
16239:             foreach my $type (@statuses) {
16240:                 if (ref($infofields) eq 'ARRAY') {
16241:                     foreach my $field (@{$infofields}) {
16242:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
16243:                             $cancreate{'emailusername'}{$type}{$field} = $1;
16244:                         }
16245:                     }
16246:                 }
16247:             }
16248:         }
16249: #
16250: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
16251: # queued requests for self-creation of account verified by e-mail.
16252: #
16253: 
16254:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
16255:         @approvalnotify = sort(@approvalnotify);
16256:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
16257:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
16258:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
16259:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
16260:                     push(@{$changes{'cancreate'}},'notify');
16261:                 }
16262:             } else {
16263:                 if ($cancreate{'notify'}{'approval'}) {
16264:                     push(@{$changes{'cancreate'}},'notify');
16265:                 }
16266:             }
16267:         } elsif ($cancreate{'notify'}{'approval'}) {
16268:             push(@{$changes{'cancreate'}},'notify');
16269:         }
16270: 
16271:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
16272:     }
16273: #  
16274: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
16275: # institutional log-in.
16276: #
16277:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
16278:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
16279:                ($domdefaults{'auth_def'} eq 'localauth'))) {
16280:             $warningmsg = &mt('Although account creation has been set to be available for institutional logins, currently default authentication in this domain has not been set to support this.').' '.
16281:                           &mt('You need to set the default authentication type to Kerberos 4 or 5 (with a Kerberos domain specified), or to Local authentication, if the localauth module has been customized in your domain to authenticate institutional logins.');
16282:         }
16283:     }
16284:     my @fields = ('lastname','firstname','middlename','generation',
16285:                   'permanentemail','id');
16286:     my @shibfields = (@fields,'inststatus');
16287:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
16288: #
16289: # Where usernames may created for institutional log-in and/or institutional single sign on:
16290: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
16291: # may self-create accounts 
16292: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
16293: # which the user may supply, if institutional data is unavailable.
16294: #
16295:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
16296:         if (@types) {
16297:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
16298:             push(@contexts,'statustocreate');
16299:             foreach my $type (@types) {
16300:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
16301:                 foreach my $field (@fields) {
16302:                     if (grep(/^\Q$field\E$/,@modifiable)) {
16303:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
16304:                     } else {
16305:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
16306:                     }
16307:                 }
16308:             }
16309:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
16310:                 foreach my $type (@types) {
16311:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
16312:                         foreach my $field (@fields) {
16313:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
16314:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
16315:                                 push(@{$changes{'selfcreate'}},$type);
16316:                                 last;
16317:                             }
16318:                         }
16319:                     }
16320:                 }
16321:             } else {
16322:                 foreach my $type (@types) {
16323:                     push(@{$changes{'selfcreate'}},$type);
16324:                 }
16325:             }
16326:         }
16327:         foreach my $field (@shibfields) {
16328:             if ($env{'form.shibenv_'.$field} ne '') {
16329:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
16330:             }
16331:         }
16332:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
16333:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
16334:                 foreach my $field (@shibfields) {
16335:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
16336:                         push(@{$changes{'cancreate'}},'shibenv');
16337:                     }
16338:                 }
16339:             } else {
16340:                 foreach my $field (@shibfields) {
16341:                     if ($env{'form.shibenv_'.$field}) {
16342:                         push(@{$changes{'cancreate'}},'shibenv');
16343:                         last;
16344:                     }
16345:                 }
16346:             }
16347:         }
16348:     }
16349:     foreach my $item (@contexts) {
16350:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
16351:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
16352:                 if (ref($cancreate{$item}) eq 'ARRAY') {
16353:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
16354:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16355:                             push(@{$changes{'cancreate'}},$item);
16356:                         }
16357:                     }
16358:                 }
16359:             }
16360:             if (ref($cancreate{$item}) eq 'ARRAY') {
16361:                 foreach my $type (@{$cancreate{$item}}) {
16362:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
16363:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16364:                             push(@{$changes{'cancreate'}},$item);
16365:                         }
16366:                     }
16367:                 }
16368:             }
16369:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
16370:             if (ref($cancreate{$item}) eq 'HASH') {
16371:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
16372:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
16373:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
16374:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
16375:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16376:                                     push(@{$changes{'cancreate'}},$item);
16377:                                 }
16378:                             }
16379:                         }
16380:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
16381:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
16382:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16383:                                 push(@{$changes{'cancreate'}},$item);
16384:                             }
16385:                         }
16386:                     }
16387:                 }
16388:                 foreach my $type (keys(%{$cancreate{$item}})) {
16389:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
16390:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
16391:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
16392:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
16393:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16394:                                         push(@{$changes{'cancreate'}},$item);
16395:                                     }
16396:                                 }
16397:                             } else {
16398:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16399:                                     push(@{$changes{'cancreate'}},$item);
16400:                                 }
16401:                             }
16402:                         }
16403:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
16404:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
16405:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16406:                                 push(@{$changes{'cancreate'}},$item);
16407:                             }
16408:                         }
16409:                     }
16410:                 }
16411:             }
16412:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
16413:             if (ref($cancreate{$item}) eq 'ARRAY') {
16414:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
16415:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16416:                         push(@{$changes{'cancreate'}},$item);
16417:                     }
16418:                 }
16419:             }
16420:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
16421:             if (ref($cancreate{$item}) eq 'HASH') {
16422:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16423:                     push(@{$changes{'cancreate'}},$item);
16424:                 }
16425:             }
16426:         } elsif ($item eq 'emailusername') {
16427:             if (ref($cancreate{$item}) eq 'HASH') {
16428:                 foreach my $type (keys(%{$cancreate{$item}})) {
16429:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
16430:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
16431:                             if ($cancreate{$item}{$type}{$field}) {
16432:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
16433:                                     push(@{$changes{'cancreate'}},$item);
16434:                                 }
16435:                                 last;
16436:                             }
16437:                         }
16438:                     }
16439:                 }
16440:             }
16441:         }
16442:     }
16443: #
16444: # Populate %save_usercreate hash with updates to self-creation configuration.
16445: #
16446:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
16447:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
16448:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
16449:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
16450:     if (ref($cancreate{'notify'}) eq 'HASH') {
16451:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
16452:     }
16453:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
16454:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
16455:     }
16456:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
16457:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
16458:     }
16459:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
16460:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
16461:     }
16462:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
16463:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
16464:     }
16465:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
16466:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
16467:     }
16468:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
16469:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
16470:     }
16471:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
16472:     $save_usercreate{'email_rule'} = \%email_rule;
16473: 
16474:     my %userconfig_hash = (
16475:             usercreation     => \%save_usercreate,
16476:             usermodification => \%save_usermodify,
16477:             inststatus       => \%save_inststatus,
16478:     );
16479: 
16480:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
16481:                                              $dom);
16482: #
16483: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
16484: #
16485:     if ($putresult eq 'ok') {
16486:         if (keys(%changes) > 0) {
16487:             $resulttext = &mt('Changes made:').'<ul>';
16488:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
16489:                 my %lt = &selfcreation_types();
16490:                 foreach my $type (@{$changes{'cancreate'}}) {
16491:                     my $chgtext = '';
16492:                     if ($type eq 'selfcreate') {
16493:                         if (@{$cancreate{$type}} == 0) {
16494:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
16495:                         } else {
16496:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
16497:                                         '<ul>';
16498:                             foreach my $case (@{$cancreate{$type}}) {
16499:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
16500:                             }
16501:                             $chgtext .= '</ul>';
16502:                             if (ref($cancreate{$type}) eq 'ARRAY') {
16503:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
16504:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
16505:                                         if (@{$cancreate{'statustocreate'}} == 0) {
16506:                                             $chgtext .= '<span class="LC_warning">'.
16507:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
16508:                                                         '</span><br />';
16509:                                         }
16510:                                     }
16511:                                 }
16512:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
16513:                                     if (!@statuses) {
16514:                                         $chgtext .= '<span class="LC_warning">'.
16515:                                                     &mt("However, e-mail verification is currently set to 'unavailable' for all user types (including 'other'), so self-creation of accounts is not possible for non-institutional log-in.").
16516:                                                     '</span><br />';
16517: 
16518:                                     }
16519:                                 }
16520:                             }
16521:                         }
16522:                     } elsif ($type eq 'shibenv') {
16523:                         if (keys(%{$cancreate{$type}}) == 0) {
16524:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
16525:                         } else {
16526:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
16527:                                         '<ul>';
16528:                             foreach my $field (@shibfields) {
16529:                                 next if ($cancreate{$type}{$field} eq '');
16530:                                 if ($field eq 'inststatus') {
16531:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
16532:                                 } else {
16533:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
16534:                                 }
16535:                             }
16536:                             $chgtext .= '</ul>';
16537:                         }
16538:                     } elsif ($type eq 'statustocreate') {
16539:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
16540:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
16541:                             if (@{$cancreate{'selfcreate'}} > 0) {
16542:                                 if (@{$cancreate{'statustocreate'}} == 0) {
16543:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
16544:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
16545:                                         $chgtext .= '<br />'.
16546:                                                     '<span class="LC_warning">'.
16547:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
16548:                                                     '</span>';
16549:                                     }
16550:                                 } elsif (keys(%usertypes) > 0) {
16551:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
16552:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
16553:                                     } else {
16554:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
16555:                                     }
16556:                                     $chgtext .= '<ul>';
16557:                                     foreach my $case (@{$cancreate{$type}}) {
16558:                                         if ($case eq 'default') {
16559:                                             $chgtext .= '<li>'.$othertitle.'</li>';
16560:                                         } else {
16561:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
16562:                                         }
16563:                                     }
16564:                                     $chgtext .= '</ul>';
16565:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
16566:                                         $chgtext .= '<span class="LC_warning">'.
16567:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
16568:                                                     '</span>';
16569:                                     }
16570:                                 }
16571:                             } else {
16572:                                 if (@{$cancreate{$type}} == 0) {
16573:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
16574:                                 } else {
16575:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
16576:                                 }
16577:                             }
16578:                             $chgtext .= '<br />';
16579:                         }
16580:                     } elsif ($type eq 'selfcreateprocessing') {
16581:                         my %choices = &Apache::lonlocal::texthash (
16582:                                                                     automatic => 'Automatic approval',
16583:                                                                     approval  => 'Queued for approval',
16584:                                                                   );
16585:                         if (@types) {
16586:                             if (@statuses) {
16587:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:').
16588:                                             '<ul>';
16589:                                 foreach my $status (@statuses) {
16590:                                     if ($status eq 'default') {
16591:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
16592:                                     } else {
16593:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
16594:                                     }
16595:                                 }
16596:                                 $chgtext .= '</ul>';
16597:                             }
16598:                         } else {
16599:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
16600:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
16601:                         }
16602:                     } elsif ($type eq 'emailverified') {
16603:                         my %options = &Apache::lonlocal::texthash (
16604:                                                                     all   => 'Same as e-mail',
16605:                                                                     first => 'Omit @domain',
16606:                                                                     free  => 'Free to choose',
16607:                                                                   );
16608:                         if (@types) {
16609:                             if (@statuses) {
16610:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
16611:                                             '<ul>';
16612:                                 foreach my $status (@statuses) {
16613:                                     if ($status eq 'default') {
16614:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
16615:                                     } else {
16616:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
16617:                                     }
16618:                                 }
16619:                                 $chgtext .= '</ul>';
16620:                             }
16621:                         } else {
16622:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
16623:                                             $options{$cancreate{'emailverified'}{'default'}});
16624:                         }
16625:                     } elsif ($type eq 'emailoptions') {
16626:                         my %options = &Apache::lonlocal::texthash (
16627:                                                                     any     => 'Any e-mail',
16628:                                                                     inst    => 'Institutional only',
16629:                                                                     noninst => 'Non-institutional only',
16630:                                                                     custom  => 'Custom restrictions',
16631:                                                                   );
16632:                         if (@types) {
16633:                             if (@statuses) {
16634:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
16635:                                             '<ul>';
16636:                                 foreach my $status (@statuses) {
16637:                                     if ($type eq 'default') {
16638:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
16639:                                     } else {
16640:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
16641:                                     }
16642:                                 }
16643:                                 $chgtext .= '</ul>';
16644:                             }
16645:                         } else {
16646:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
16647:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
16648:                             } else {
16649:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
16650:                                                 $options{$cancreate{'emailoptions'}{'default'}});
16651:                             }
16652:                         }
16653:                     } elsif ($type eq 'emaildomain') {
16654:                         my $output;
16655:                         if (@statuses) {
16656:                             foreach my $type (@statuses) {
16657:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
16658:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
16659:                                         if ($type eq 'default') {
16660:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
16661:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
16662:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
16663:                                             } else {
16664:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
16665:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
16666:                                             }
16667:                                         } else {
16668:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
16669:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
16670:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
16671:                                             } else {
16672:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
16673:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
16674:                                             }
16675:                                         }
16676:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
16677:                                         if ($type eq 'default') {
16678:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
16679:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
16680:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
16681:                                             } else {
16682:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
16683:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
16684:                                             }
16685:                                         } else {
16686:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
16687:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
16688:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
16689:                                             } else {
16690:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
16691:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
16692:                                             }
16693:                                         }
16694:                                     }
16695:                                 }
16696:                             }
16697:                         }
16698:                         if ($output ne '') {
16699:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
16700:                                         '<ul>'.$output.'</ul>';
16701:                         }
16702:                     } elsif ($type eq 'captcha') {
16703:                         if ($savecaptcha{$type} eq 'notused') {
16704:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
16705:                         } else {
16706:                             my %captchas = &captcha_phrases();
16707:                             if ($captchas{$savecaptcha{$type}}) {
16708:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
16709:                             } else {
16710:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
16711:                             }
16712:                         }
16713:                     } elsif ($type eq 'recaptchakeys') {
16714:                         my ($privkey,$pubkey);
16715:                         if (ref($savecaptcha{$type}) eq 'HASH') {
16716:                             $pubkey = $savecaptcha{$type}{'public'};
16717:                             $privkey = $savecaptcha{$type}{'private'};
16718:                         }
16719:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
16720:                         if (!$pubkey) {
16721:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
16722:                         } else {
16723:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
16724:                         }
16725:                         if (!$privkey) {
16726:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
16727:                         } else {
16728:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
16729:                         }
16730:                         $chgtext .= '</ul>';
16731:                     } elsif ($type eq 'recaptchaversion') {
16732:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
16733:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
16734:                         }
16735:                     } elsif ($type eq 'emailusername') {
16736:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
16737:                             if (@statuses) {
16738:                                 foreach my $type (@statuses) {
16739:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
16740:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
16741:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
16742:                                                     '<ul>';
16743:                                             foreach my $field (@{$infofields}) {
16744:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
16745:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
16746:                                                 }
16747:                                             }
16748:                                             $chgtext .= '</ul>';
16749:                                         } else {
16750:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
16751:                                         }
16752:                                     } else {
16753:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
16754:                                     }
16755:                                 }
16756:                             }
16757:                         }
16758:                     } elsif ($type eq 'notify') {
16759:                         my $numapprove = 0;
16760:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
16761:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
16762:                                 if ($cancreate{'notify'}{'approval'}) {
16763:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
16764:                                     $numapprove ++;
16765:                                 }
16766:                             }
16767:                         }
16768:                         unless ($numapprove) {
16769:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
16770:                         }
16771:                     }
16772:                     if ($chgtext) {
16773:                         $resulttext .= '<li>'.$chgtext.'</li>';
16774:                     }
16775:                 }
16776:             }
16777:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
16778:                 my ($emailrules,$emailruleorder) =
16779:                     &Apache::lonnet::inst_userrules($dom,'email');
16780:                 foreach my $type (@{$changes{'email_rule'}}) {
16781:                     if (ref($email_rule{$type}) eq 'ARRAY') {
16782:                         my $chgtext = '<ul>';
16783:                         foreach my $rule (@{$email_rule{$type}}) {
16784:                             if (ref($emailrules->{$rule}) eq 'HASH') {
16785:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
16786:                             }
16787:                         }
16788:                         $chgtext .= '</ul>';
16789:                         my $typename;
16790:                         if (@types) {
16791:                             if ($type eq 'default') {
16792:                                 $typename = $othertitle;
16793:                             } else {
16794:                                 $typename = $usertypes{$type};
16795:                             }
16796:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
16797:                         }
16798:                         if (@{$email_rule{$type}} > 0) {
16799:                             $resulttext .= '<li>'.
16800:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
16801:                                                $usertypes{$type}).
16802:                                            $chgtext.
16803:                                            '</li>';
16804:                         } else {
16805:                             $resulttext .= '<li>'.
16806:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
16807:                                            '</li>'.
16808:                                            &mt('(Affiliation: [_1])',$typename);
16809:                         }
16810:                     }
16811:                 }
16812:             }
16813:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
16814:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
16815:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
16816:                         my $chgtext = '<ul>';
16817:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
16818:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
16819:                         }
16820:                         $chgtext .= '</ul>';
16821:                         $resulttext .= '<li>'.
16822:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
16823:                                           $chgtext.
16824:                                        '</li>';
16825:                     } else {
16826:                         $resulttext .= '<li>'.
16827:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
16828:                                        '</li>';
16829:                     }
16830:                 }
16831:             }
16832:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
16833:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
16834:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
16835:                 foreach my $type (@{$changes{'selfcreate'}}) {
16836:                     my $typename = $type;
16837:                     if (keys(%usertypes) > 0) {
16838:                         if ($usertypes{$type} ne '') {
16839:                             $typename = $usertypes{$type};
16840:                         }
16841:                     }
16842:                     my @modifiable;
16843:                     $resulttext .= '<li>'.
16844:                                     &mt('Self-creation of account by users with status: [_1]',
16845:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
16846:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
16847:                     foreach my $field (@fields) {
16848:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
16849:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
16850:                         }
16851:                     }
16852:                     if (@modifiable > 0) {
16853:                         $resulttext .= join(', ',@modifiable);
16854:                     } else {
16855:                         $resulttext .= &mt('none');
16856:                     }
16857:                     $resulttext .= '</li>';
16858:                 }
16859:                 $resulttext .= '</ul></li>';
16860:             }
16861:             $resulttext .= '</ul>';
16862:             my $cachetime = 24*60*60;
16863:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
16864:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16865:             if (ref($lastactref) eq 'HASH') {
16866:                 $lastactref->{'domdefaults'} = 1;
16867:             }
16868:         } else {
16869:             $resulttext = &mt('No changes made to self-creation settings');
16870:         }
16871:     } else {
16872:         $resulttext = '<span class="LC_error">'.
16873:             &mt('An error occurred: [_1]',$putresult).'</span>';
16874:     }
16875:     if ($warningmsg ne '') {
16876:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
16877:     }
16878:     return $resulttext;
16879: }
16880: 
16881: sub process_captcha {
16882:     my ($container,$changes,$newsettings,$currsettings) = @_;
16883:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
16884:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
16885:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
16886:         $newsettings->{'captcha'} = 'original';
16887:     }
16888:     my %current;
16889:     if (ref($currsettings) eq 'HASH') {
16890:         %current = %{$currsettings};
16891:     }
16892:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
16893:         if ($container eq 'cancreate') {
16894:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16895:                 push(@{$changes->{'cancreate'}},'captcha');
16896:             } elsif (!defined($changes->{'cancreate'})) {
16897:                 $changes->{'cancreate'} = ['captcha'];
16898:             }
16899:         } elsif ($container eq 'passwords') {
16900:             $changes->{'reset'} = 1;
16901:         } else {
16902:             $changes->{'captcha'} = 1;
16903:         }
16904:     }
16905:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
16906:     if ($newsettings->{'captcha'} eq 'recaptcha') {
16907:         $newpub = $env{'form.'.$container.'_recaptchapub'};
16908:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
16909:         $newpub =~ s/[^\w\-]//g;
16910:         $newpriv =~ s/[^\w\-]//g;
16911:         $newsettings->{'recaptchakeys'} = {
16912:                                              public  => $newpub,
16913:                                              private => $newpriv,
16914:                                           };
16915:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
16916:         $newversion =~ s/\D//g;
16917:         if ($newversion ne '2') {
16918:             $newversion = 1;
16919:         }
16920:         $newsettings->{'recaptchaversion'} = $newversion;
16921:     }
16922:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
16923:         $currpub = $current{'recaptchakeys'}{'public'};
16924:         $currpriv = $current{'recaptchakeys'}{'private'};
16925:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
16926:             $newsettings->{'recaptchakeys'} = {
16927:                                                  public  => '',
16928:                                                  private => '',
16929:                                               }
16930:         }
16931:     }
16932:     if ($current{'captcha'} eq 'recaptcha') {
16933:         $currversion = $current{'recaptchaversion'};
16934:         if ($currversion ne '2') {
16935:             $currversion = 1;
16936:         }
16937:     }
16938:     if ($currversion ne $newversion) {
16939:         if ($container eq 'cancreate') {
16940:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16941:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
16942:             } elsif (!defined($changes->{'cancreate'})) {
16943:                 $changes->{'cancreate'} = ['recaptchaversion'];
16944:             }
16945:         } elsif ($container eq 'passwords') {
16946:             $changes->{'reset'} = 1;
16947:         } else {
16948:             $changes->{'recaptchaversion'} = 1;
16949:         }
16950:     }
16951:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
16952:         if ($container eq 'cancreate') {
16953:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16954:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
16955:             } elsif (!defined($changes->{'cancreate'})) {
16956:                 $changes->{'cancreate'} = ['recaptchakeys'];
16957:             }
16958:         } elsif ($container eq 'passwords') {
16959:             $changes->{'reset'} = 1;
16960:         } else {
16961:             $changes->{'recaptchakeys'} = 1;
16962:         }
16963:     }
16964:     return;
16965: }
16966: 
16967: sub modify_usermodification {
16968:     my ($dom,%domconfig) = @_;
16969:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
16970:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
16971:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
16972:             if ($key eq 'selfcreate') {
16973:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
16974:             } else {  
16975:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
16976:             }
16977:         }
16978:     }
16979:     my @contexts = ('author','course');
16980:     my %context_title = (
16981:                            author => 'In author context',
16982:                            course => 'In course context',
16983:                         );
16984:     my @fields = ('lastname','firstname','middlename','generation',
16985:                   'permanentemail','id');
16986:     my %roles = (
16987:                   author => ['ca','aa'],
16988:                   course => ['st','ep','ta','in','cr'],
16989:                 );
16990:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
16991:     foreach my $context (@contexts) {
16992:         foreach my $role (@{$roles{$context}}) {
16993:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
16994:             foreach my $item (@fields) {
16995:                 if (grep(/^\Q$item\E$/,@modifiable)) {
16996:                     $modifyhash{$context}{$role}{$item} = 1;
16997:                 } else {
16998:                     $modifyhash{$context}{$role}{$item} = 0;
16999:                 }
17000:             }
17001:         }
17002:         if (ref($curr_usermodification{$context}) eq 'HASH') {
17003:             foreach my $role (@{$roles{$context}}) {
17004:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
17005:                     foreach my $field (@fields) {
17006:                         if ($modifyhash{$context}{$role}{$field} ne 
17007:                                 $curr_usermodification{$context}{$role}{$field}) {
17008:                             push(@{$changes{$context}},$role);
17009:                             last;
17010:                         }
17011:                     }
17012:                 }
17013:             }
17014:         } else {
17015:             foreach my $context (@contexts) {
17016:                 foreach my $role (@{$roles{$context}}) {
17017:                     push(@{$changes{$context}},$role);
17018:                 }
17019:             }
17020:         }
17021:     }
17022:     my %usermodification_hash =  (
17023:                                    usermodification => \%modifyhash,
17024:                                  );
17025:     my $putresult = &Apache::lonnet::put_dom('configuration',
17026:                                              \%usermodification_hash,$dom);
17027:     if ($putresult eq 'ok') {
17028:         if (keys(%changes) > 0) {
17029:             $resulttext = &mt('Changes made: ').'<ul>';
17030:             foreach my $context (@contexts) {
17031:                 if (ref($changes{$context}) eq 'ARRAY') {
17032:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
17033:                     if (ref($changes{$context}) eq 'ARRAY') {
17034:                         foreach my $role (@{$changes{$context}}) {
17035:                             my $rolename;
17036:                             if ($role eq 'cr') {
17037:                                 $rolename = &mt('Custom');
17038:                             } else {
17039:                                 $rolename = &Apache::lonnet::plaintext($role);
17040:                             }
17041:                             my @modifiable;
17042:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
17043:                             foreach my $field (@fields) {
17044:                                 if ($modifyhash{$context}{$role}{$field}) {
17045:                                     push(@modifiable,$fieldtitles{$field});
17046:                                 }
17047:                             }
17048:                             if (@modifiable > 0) {
17049:                                 $resulttext .= join(', ',@modifiable);
17050:                             } else {
17051:                                 $resulttext .= &mt('none'); 
17052:                             }
17053:                             $resulttext .= '</li>';
17054:                         }
17055:                         $resulttext .= '</ul></li>';
17056:                     }
17057:                 }
17058:             }
17059:             $resulttext .= '</ul>';
17060:         } else {
17061:             $resulttext = &mt('No changes made to user modification settings');
17062:         }
17063:     } else {
17064:         $resulttext = '<span class="LC_error">'.
17065:             &mt('An error occurred: [_1]',$putresult).'</span>';
17066:     }
17067:     return $resulttext;
17068: }
17069: 
17070: sub modify_defaults {
17071:     my ($dom,$lastactref,%domconfig) = @_;
17072:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
17073:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17074:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
17075:                  'portal_def');
17076:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
17077:     foreach my $item (@items) {
17078:         $newvalues{$item} = $env{'form.'.$item};
17079:         if ($item eq 'auth_def') {
17080:             if ($newvalues{$item} ne '') {
17081:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
17082:                     push(@errors,$item);
17083:                 }
17084:             }
17085:         } elsif ($item eq 'lang_def') {
17086:             if ($newvalues{$item} ne '') {
17087:                 if ($newvalues{$item} =~ /^(\w+)/) {
17088:                     my $langcode = $1;
17089:                     if ($langcode ne 'x_chef') {
17090:                         if (code2language($langcode) eq '') {
17091:                             push(@errors,$item);
17092:                         }
17093:                     }
17094:                 } else {
17095:                     push(@errors,$item);
17096:                 }
17097:             }
17098:         } elsif ($item eq 'timezone_def') {
17099:             if ($newvalues{$item} ne '') {
17100:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
17101:                     push(@errors,$item);   
17102:                 }
17103:             }
17104:         } elsif ($item eq 'datelocale_def') {
17105:             if ($newvalues{$item} ne '') {
17106:                 my @datelocale_ids = DateTime::Locale->ids();
17107:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
17108:                     push(@errors,$item);
17109:                 }
17110:             }
17111:         } elsif ($item eq 'portal_def') {
17112:             if ($newvalues{$item} ne '') {
17113:                 if ($newvalues{$item} =~ /^https?\:\/\/(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])\/?$/) {
17114:                     foreach my $field ('email','web') {
17115:                         if ($env{'form.'.$item.'_'.$field}) {
17116:                             $newvalues{$item.'_'.$field} = $env{'form.'.$item.'_'.$field};
17117:                         }
17118:                     }
17119:                 } else {
17120:                     push(@errors,$item);
17121:                 }
17122:             }
17123:         }
17124:         if (grep(/^\Q$item\E$/,@errors)) {
17125:             $newvalues{$item} = $domdefaults{$item};
17126:             if ($item eq 'portal_def') {
17127:                 if ($domdefaults{$item}) {
17128:                     foreach my $field ('email','web') {
17129:                         if (exists($domdefaults{$item.'_'.$field})) {
17130:                             $newvalues{$item.'_'.$field} = $domdefaults{$item.'_'.$field};
17131:                         }
17132:                     }
17133:                 }
17134:             }
17135:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
17136:             $changes{$item} = 1;
17137:         }
17138:         if ($item eq 'portal_def') {
17139:             unless (grep(/^\Q$item\E$/,@errors)) {
17140:                 if ($newvalues{$item} eq '') {
17141:                     foreach my $field ('email','web') {
17142:                         if (exists($domdefaults{$item.'_'.$field})) {
17143:                             delete($domdefaults{$item.'_'.$field});
17144:                         }
17145:                     }
17146:                 } else {
17147:                     unless ($changes{$item}) {
17148:                         foreach my $field ('email','web') {
17149:                             if ($domdefaults{$item.'_'.$field} ne $newvalues{$item.'_'.$field}) {
17150:                                 $changes{$item} = 1;
17151:                                 last;
17152:                             }
17153:                         }
17154:                     }
17155:                     foreach my $field ('email','web') {
17156:                         if ($newvalues{$item.'_'.$field}) {
17157:                             $domdefaults{$item.'_'.$field} = $newvalues{$item.'_'.$field};
17158:                         } elsif (exists($domdefaults{$item.'_'.$field})) {
17159:                             delete($domdefaults{$item.'_'.$field});
17160:                         }
17161:                     }
17162:                 }
17163:             }
17164:         }
17165:         $domdefaults{$item} = $newvalues{$item};
17166:     }
17167:     my %staticdefaults = (
17168:                            'intauth_cost'   => 10,
17169:                            'intauth_check'  => 0,
17170:                            'intauth_switch' => 0,
17171:                          );
17172:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
17173:         if (exists($domdefaults{$item})) {
17174:             $newvalues{$item} = $domdefaults{$item};
17175:         } else {
17176:             $newvalues{$item} = $staticdefaults{$item};
17177:         }
17178:     }
17179:     my ($unamemaprules,$ruleorder);
17180:     my @possunamemaprules = &Apache::loncommon::get_env_multiple('form.unamemap_rule');
17181:     if (@possunamemaprules) {
17182:         ($unamemaprules,$ruleorder) =
17183:             &Apache::lonnet::inst_userrules($dom,'unamemap');
17184:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
17185:             if (@{$ruleorder} > 0) {
17186:                 my %possrules;
17187:                 map { $possrules{$_} = 1; } @possunamemaprules;
17188:                 foreach my $rule (@{$ruleorder}) {
17189:                     if ($possrules{$rule}) {
17190:                         push(@{$newvalues{'unamemap_rule'}},$rule);
17191:                     }
17192:                 }
17193:             }
17194:         }
17195:     }
17196:     if (ref($domdefaults{'unamemap_rule'}) eq 'ARRAY') {
17197:         if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
17198:             my @rulediffs = &Apache::loncommon::compare_arrays($domdefaults{'unamemap_rule'},
17199:                                                                $newvalues{'unamemap_rule'});
17200:             if (@rulediffs) {
17201:                 $changes{'unamemap_rule'} = 1;
17202:                 $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
17203:             }
17204:         } elsif (@{$domdefaults{'unamemap_rule'}} > 0) {
17205:             $changes{'unamemap_rule'} = 1;
17206:             delete($domdefaults{'unamemap_rule'});
17207:         }
17208:     } elsif (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
17209:         if (@{$newvalues{'unamemap_rule'}} > 0) {
17210:             $changes{'unamemap_rule'} = 1;
17211:             $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
17212:         }
17213:     }
17214:     my %defaults_hash = (
17215:                          defaults => \%newvalues,
17216:                         );
17217:     my $title = &defaults_titles();
17218: 
17219:     my $currinststatus;
17220:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
17221:         $currinststatus = $domconfig{'inststatus'};
17222:     } else {
17223:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17224:         $currinststatus = {
17225:                              inststatustypes => $usertypes,
17226:                              inststatusorder => $types,
17227:                              inststatusguest => [],
17228:                           };
17229:     }
17230:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
17231:     my @allpos;
17232:     my %alltypes;
17233:     my @inststatusguest;
17234:     if (ref($currinststatus) eq 'HASH') {
17235:         if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
17236:             foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
17237:                 unless (grep(/^\Q$type\E$/,@todelete)) {
17238:                     push(@inststatusguest,$type);
17239:                 }
17240:             }
17241:         }
17242:     }
17243:     my ($currtitles,$currorder);
17244:     if (ref($currinststatus) eq 'HASH') {
17245:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
17246:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
17247:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
17248:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
17249:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
17250:                     }
17251:                 }
17252:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
17253:                     my $position = $env{'form.inststatus_pos_'.$type};
17254:                     $position =~ s/\D+//g;
17255:                     $allpos[$position] = $type;
17256:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
17257:                     $alltypes{$type} =~ s/`//g;
17258:                 }
17259:             }
17260:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
17261:             $currtitles =~ s/,$//;
17262:         }
17263:     }
17264:     if ($env{'form.addinststatus'}) {
17265:         my $newtype = $env{'form.addinststatus'};
17266:         $newtype =~ s/\W//g;
17267:         unless (exists($alltypes{$newtype})) {
17268:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
17269:             $alltypes{$newtype} =~ s/`//g; 
17270:             my $position = $env{'form.addinststatus_pos'};
17271:             $position =~ s/\D+//g;
17272:             if ($position ne '') {
17273:                 $allpos[$position] = $newtype;
17274:             }
17275:         }
17276:     }
17277:     my @orderedstatus;
17278:     foreach my $type (@allpos) {
17279:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
17280:             push(@orderedstatus,$type);
17281:         }
17282:     }
17283:     foreach my $type (keys(%alltypes)) {
17284:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
17285:             delete($alltypes{$type});
17286:         }
17287:     }
17288:     $defaults_hash{'inststatus'} = {
17289:                                      inststatustypes => \%alltypes,
17290:                                      inststatusorder => \@orderedstatus,
17291:                                      inststatusguest => \@inststatusguest,
17292:                                    };
17293:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
17294:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
17295:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
17296:         }
17297:     }
17298:     if ($currorder ne join(',',@orderedstatus)) {
17299:         $changes{'inststatus'}{'inststatusorder'} = 1;
17300:     }
17301:     my $newtitles;
17302:     foreach my $item (@orderedstatus) {
17303:         $newtitles .= $alltypes{$item}.',';
17304:     }
17305:     $newtitles =~ s/,$//;
17306:     if ($currtitles ne $newtitles) {
17307:         $changes{'inststatus'}{'inststatustypes'} = 1;
17308:     }
17309:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
17310:                                              $dom);
17311:     if ($putresult eq 'ok') {
17312:         if (keys(%changes) > 0) {
17313:             $resulttext = &mt('Changes made:').'<ul>';
17314:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
17315:             my $mailmsgtext = "Changes made to domain settings in a LON-CAPA installation - domain: $dom (running version: $version) - dns_domain.tab needs to be updated with the following changes, to support legacy 2.4, 2.5 and 2.6 versions of LON-CAPA.\n\n";
17316:             foreach my $item (sort(keys(%changes))) {
17317:                 if ($item eq 'inststatus') {
17318:                     if (ref($changes{'inststatus'}) eq 'HASH') {
17319:                         if (@orderedstatus) {
17320:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
17321:                             foreach my $type (@orderedstatus) { 
17322:                                 $resulttext .= $alltypes{$type}.', ';
17323:                             }
17324:                             $resulttext =~ s/, $//;
17325:                             $resulttext .= '</li>';
17326:                         } else {
17327:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>';
17328:                         }
17329:                     }
17330:                 } elsif ($item eq 'unamemap_rule') {
17331:                     if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
17332:                         my @rulenames;
17333:                         if (ref($unamemaprules) eq 'HASH') {
17334:                             foreach my $rule (@{$newvalues{'unamemap_rule'}}) {
17335:                                 if (ref($unamemaprules->{$rule}) eq 'HASH') {
17336:                                     push(@rulenames,$unamemaprules->{$rule}->{'name'});
17337:                                 }
17338:                             }
17339:                         }
17340:                         if (@rulenames) {
17341:                             $resulttext .= '<li>'.&mt('Mapping for missing usernames includes: [_1]',
17342:                                                      '<ul><li>'.join('</li><li>',@rulenames).'</li></ul>').
17343:                                            '</li>';
17344:                         } else {
17345:                             $resulttext .= '<li>'.&mt('No mapping for missing usernames via standard log-in').'</li>';
17346:                         }
17347:                     } else {
17348:                         $resulttext .= '<li>'.&mt('Mapping for missing usernames via standard log-in deleted').'</li>';
17349:                     }
17350:                 } else {
17351:                     my $value = $env{'form.'.$item};
17352:                     if ($value eq '') {
17353:                         $value = &mt('none');
17354:                     } elsif ($item eq 'auth_def') {
17355:                         my %authnames = &authtype_names();
17356:                         my %shortauth = (
17357:                                           internal   => 'int',
17358:                                           krb4       => 'krb4',
17359:                                           krb5       => 'krb5',
17360:                                           localauth  => 'loc',
17361:                                           lti        => 'lti',
17362:                         );
17363:                         $value = $authnames{$shortauth{$value}};
17364:                     }
17365:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
17366:                     $mailmsgtext .= "$title->{$item} set to $value\n";
17367:                     if ($item eq 'portal_def') {
17368:                         if ($env{'form.'.$item} ne '') {
17369:                             foreach my $field ('email','web') {
17370:                                 $value = $env{'form.'.$item.'_'.$field};
17371:                                 if ($value) {
17372:                                     $value = &mt('Yes');
17373:                                 } else {
17374:                                     $value = &mt('No');
17375:                                 }
17376:                                 $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$field},$value).'</li>';
17377:                             }
17378:                         }
17379:                     }
17380:                 }
17381:             }
17382:             $resulttext .= '</ul>';
17383:             $mailmsgtext .= "\n";
17384:             my $cachetime = 24*60*60;
17385:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17386:             if (ref($lastactref) eq 'HASH') {
17387:                 $lastactref->{'domdefaults'} = 1;
17388:             }
17389:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
17390:                 my $notify = 1;
17391:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
17392:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
17393:                         $notify = 0;
17394:                     }
17395:                 }
17396:                 if ($notify) {
17397:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
17398:                                                "LON-CAPA Domain Settings Change - $dom",
17399:                                                $mailmsgtext);
17400:                 }
17401:             }
17402:         } else {
17403:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
17404:         }
17405:     } else {
17406:         $resulttext = '<span class="LC_error">'.
17407:             &mt('An error occurred: [_1]',$putresult).'</span>';
17408:     }
17409:     if (@errors > 0) {
17410:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
17411:         foreach my $item (@errors) {
17412:             $resulttext .= ' "'.$title->{$item}.'",';
17413:         }
17414:         $resulttext =~ s/,$//;
17415:     }
17416:     return $resulttext;
17417: }
17418: 
17419: sub modify_scantron {
17420:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
17421:     my ($resulttext,%confhash,%changes,$errors);
17422:     my $custom = 'custom.tab';
17423:     my $default = 'default.tab';
17424:     my $servadm = $r->dir_config('lonAdmEMail');
17425:     my ($configuserok,$author_ok,$switchserver) =
17426:         &config_check($dom,$confname,$servadm);
17427:     if ($env{'form.scantronformat.filename'} ne '') {
17428:         my $error;
17429:         if ($configuserok eq 'ok') {
17430:             if ($switchserver) {
17431:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
17432:             } else {
17433:                 if ($author_ok eq 'ok') {
17434:                     my $modified = [];
17435:                     my ($result,$scantronurl) =
17436:                         &Apache::lonconfigsettings::publishlogo($r,'upload','scantronformat',$dom,
17437:                                                                 $confname,'scantron','','',$custom,
17438:                                                                 $modified);
17439:                     if ($result eq 'ok') {
17440:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
17441:                         $changes{'scantronformat'} = 1;
17442:                         &update_modify_urls($r,$modified);
17443:                     } else {
17444:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
17445:                     }
17446:                 } else {
17447:                     $error = &mt("Upload of [_1] failed because an author role could not be assigned to a Domain Configuration user ([_2]) in domain: [_3].  Error was: [_4].",$custom,$confname,$dom,$author_ok);
17448:                 }
17449:             }
17450:         } else {
17451:             $error = &mt("Upload of [_1] failed because a Domain Configuration user ([_2]) could not be created in domain: [_3].  Error was: [_4].",$custom,$confname,$dom,$configuserok);
17452:         }
17453:         if ($error) {
17454:             &Apache::lonnet::logthis($error);
17455:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
17456:         }
17457:     }
17458:     if (ref($domconfig{'scantron'}) eq 'HASH') {
17459:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
17460:             if ($env{'form.scantronformat_del'}) {
17461:                 $confhash{'scantron'}{'scantronformat'} = '';
17462:                 $changes{'scantronformat'} = 1;
17463:             } else {
17464:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
17465:             }
17466:         }
17467:     }
17468:     my @options = ('hdr','pad','rem');
17469:     my @fields = &scantroncsv_fields();
17470:     my %titles = &scantronconfig_titles();
17471:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
17472:     my ($newdat,$currdat,%newcol,%currcol);
17473:     if (grep(/^dat$/,@formats)) {
17474:         $confhash{'scantron'}{config}{dat} = 1;
17475:         $newdat = 1;
17476:     } else {
17477:         $newdat = 0;
17478:     }
17479:     if (grep(/^csv$/,@formats)) {
17480:         my %bynum;
17481:         foreach my $field (@fields) {
17482:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
17483:                 my $posscol = $1;
17484:                 if (($posscol < 20) && (!$bynum{$posscol})) {
17485:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
17486:                     $bynum{$posscol} = $field;
17487:                     $newcol{$field} = $posscol;
17488:                 }
17489:             }
17490:         }
17491:         if (keys(%newcol)) {
17492:             foreach my $option (@options) {
17493:                 if ($env{'form.scantroncsv_'.$option}) {
17494:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
17495:                 }
17496:             }
17497:         }
17498:     }
17499:     $currdat = 1;
17500:     if (ref($domconfig{'scantron'}) eq 'HASH') {
17501:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
17502:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
17503:                 $currdat = 0;
17504:             }
17505:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
17506:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
17507:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
17508:                 }
17509:             }
17510:         }
17511:     }
17512:     if ($currdat != $newdat) {
17513:         $changes{'config'} = 1;
17514:     } else {
17515:         foreach my $field (@fields) {
17516:             if ($currcol{$field} ne '') {
17517:                 if ($currcol{$field} ne $newcol{$field}) {
17518:                     $changes{'config'} = 1;
17519:                     last;
17520:                 }
17521:             } elsif ($newcol{$field} ne '') {
17522:                 $changes{'config'} = 1;
17523:                 last;
17524:             }
17525:         }
17526:     }
17527:     if (keys(%confhash) > 0) {
17528:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
17529:                                                  $dom);
17530:         if ($putresult eq 'ok') {
17531:             if (keys(%changes) > 0) {
17532:                 if (ref($confhash{'scantron'}) eq 'HASH') {
17533:                     $resulttext = &mt('Changes made:').'<ul>';
17534:                     if ($changes{'scantronformat'}) {
17535:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
17536:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
17537:                         } else {
17538:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
17539:                         }
17540:                     }
17541:                     if ($changes{'config'}) {
17542:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
17543:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
17544:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
17545:                             }
17546:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
17547:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
17548:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
17549:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
17550:                                         foreach my $field (@fields) {
17551:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
17552:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
17553:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
17554:                                             }
17555:                                         }
17556:                                         $resulttext .= '</ul></li>';
17557:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
17558:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
17559:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
17560:                                                 foreach my $option (@options) {
17561:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
17562:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
17563:                                                     }
17564:                                                 }
17565:                                                 $resulttext .= '</ul></li>';
17566:                                             }
17567:                                         }
17568:                                     }
17569:                                 }
17570:                             }
17571:                         } else {
17572:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
17573:                         }
17574:                     }
17575:                     $resulttext .= '</ul>';
17576:                 } else {
17577:                     $resulttext = &mt('Changes made to bubblesheet format file.');
17578:                 }
17579:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
17580:                 if (ref($lastactref) eq 'HASH') {
17581:                     $lastactref->{'domainconfig'} = 1;
17582:                 }
17583:             } else {
17584:                 $resulttext = &mt('No changes made to bubblesheet format settings');
17585:             }
17586:         } else {
17587:             $resulttext = '<span class="LC_error">'.
17588:                 &mt('An error occurred: [_1]',$putresult).'</span>';
17589:         }
17590:     } else {
17591:         $resulttext = &mt('No changes made to bubblesheet format settings');
17592:     }
17593:     if ($errors) {
17594:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
17595:                        $errors.'</ul></p>';
17596:     }
17597:     return $resulttext;
17598: }
17599: 
17600: sub modify_coursecategories {
17601:     my ($dom,$lastactref,%domconfig) = @_;
17602:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
17603:         $cathash);
17604:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
17605:     my @catitems = ('unauth','auth');
17606:     my @cattypes = ('std','domonly','codesrch','none');
17607:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
17608:         $cathash = $domconfig{'coursecategories'}{'cats'};
17609:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
17610:             $changes{'togglecats'} = 1;
17611:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
17612:         }
17613:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
17614:             $changes{'categorize'} = 1;
17615:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
17616:         }
17617:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
17618:             $changes{'togglecatscomm'} = 1;
17619:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
17620:         }
17621:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
17622:             $changes{'categorizecomm'} = 1;
17623:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
17624:         }
17625:         foreach my $item (@catitems) {
17626:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
17627:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
17628:                     $changes{$item} = 1;
17629:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
17630:                 }
17631:             }
17632:         }
17633:     } else {
17634:         $changes{'togglecats'} = 1;
17635:         $changes{'categorize'} = 1;
17636:         $changes{'togglecatscomm'} = 1;
17637:         $changes{'categorizecomm'} = 1;
17638:         $domconfig{'coursecategories'} = {
17639:                                              togglecats => $env{'form.togglecats'},
17640:                                              categorize => $env{'form.categorize'},
17641:                                              togglecatscomm => $env{'form.togglecatscomm'},
17642:                                              categorizecomm => $env{'form.categorizecomm'},
17643:                                          };
17644:         foreach my $item (@catitems) {
17645:             if ($env{'form.coursecat_'.$item} ne 'std') {
17646:                 $changes{$item} = 1;
17647:             }
17648:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
17649:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
17650:             }
17651:         }
17652:     }
17653:     if (ref($cathash) eq 'HASH') {
17654:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
17655:             push (@deletecategory,'instcode::0');
17656:         }
17657:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
17658:             push(@deletecategory,'communities::0');
17659:         }
17660:     }
17661:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
17662:     if (ref($cathash) eq 'HASH') {
17663:         if (@deletecategory > 0) {
17664:             #FIXME Need to remove category from all courses using a deleted category 
17665:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
17666:             foreach my $item (@deletecategory) {
17667:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
17668:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
17669:                     $deletions{$item} = 1;
17670:                     &recurse_cat_deletes($item,$cathash,\%deletions);
17671:                 }
17672:             }
17673:         }
17674:         foreach my $item (keys(%{$cathash})) {
17675:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
17676:             if ($cathash->{$item} ne $env{'form.'.$item}) {
17677:                 $reorderings{$item} = 1;
17678:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
17679:             }
17680:             if ($env{'form.addcategory_name_'.$item} ne '') {
17681:                 my $newcat = $env{'form.addcategory_name_'.$item};
17682:                 my $newdepth = $depth+1;
17683:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
17684:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
17685:                 $adds{$newitem} = 1; 
17686:             }
17687:             if ($env{'form.subcat_'.$item} ne '') {
17688:                 my $newcat = $env{'form.subcat_'.$item};
17689:                 my $newdepth = $depth+1;
17690:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
17691:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
17692:                 $adds{$newitem} = 1;
17693:             }
17694:         }
17695:     }
17696:     if ($env{'form.instcode'} eq '1') {
17697:         if (ref($cathash) eq 'HASH') {
17698:             my $newitem = 'instcode::0';
17699:             if ($cathash->{$newitem} eq '') {  
17700:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
17701:                 $adds{$newitem} = 1;
17702:             }
17703:         } else {
17704:             my $newitem = 'instcode::0';
17705:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
17706:             $adds{$newitem} = 1;
17707:         }
17708:     }
17709:     if ($env{'form.communities'} eq '1') {
17710:         if (ref($cathash) eq 'HASH') {
17711:             my $newitem = 'communities::0';
17712:             if ($cathash->{$newitem} eq '') {
17713:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
17714:                 $adds{$newitem} = 1;
17715:             }
17716:         } else {
17717:             my $newitem = 'communities::0';
17718:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
17719:             $adds{$newitem} = 1;
17720:         }
17721:     }
17722:     if ($env{'form.addcategory_name'} ne '') {
17723:         if (($env{'form.addcategory_name'} ne 'instcode') &&
17724:             ($env{'form.addcategory_name'} ne 'communities')) {
17725:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
17726:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
17727:             $adds{$newitem} = 1;
17728:         }
17729:     }
17730:     my $putresult;
17731:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
17732:         if (keys(%deletions) > 0) {
17733:             foreach my $key (keys(%deletions)) {
17734:                 if ($predelallitems{$key} ne '') {
17735:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
17736:                 }
17737:             }
17738:         }
17739:         my (@chkcats,@chktrails,%chkallitems);
17740:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
17741:         if (ref($chkcats[0]) eq 'ARRAY') {
17742:             my $depth = 0;
17743:             my $chg = 0;
17744:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
17745:                 my $name = $chkcats[0][$i];
17746:                 my $item;
17747:                 if ($name eq '') {
17748:                     $chg ++;
17749:                 } else {
17750:                     $item = &escape($name).'::0';
17751:                     if ($chg) {
17752:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
17753:                     }
17754:                     $depth ++; 
17755:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
17756:                     $depth --;
17757:                 }
17758:             }
17759:         }
17760:     }
17761:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
17762:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
17763:         if ($putresult eq 'ok') {
17764:             my %title = (
17765:                          togglecats     => 'Show/Hide a course in catalog',
17766:                          categorize     => 'Assign a category to a course',
17767:                          togglecatscomm => 'Show/Hide a community in catalog',
17768:                          categorizecomm => 'Assign a category to a community',
17769:                         );
17770:             my %level = (
17771:                          dom  => 'set in Domain ("Modify Course/Community")',
17772:                          crs  => 'set in Course ("Course Configuration")',
17773:                          comm => 'set in Community ("Community Configuration")',
17774:                          none     => 'No catalog',
17775:                          std      => 'Standard catalog',
17776:                          domonly  => 'Domain-only catalog',
17777:                          codesrch => 'Code search form',
17778:                         );
17779:             $resulttext = &mt('Changes made:').'<ul>';
17780:             if ($changes{'togglecats'}) {
17781:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
17782:             }
17783:             if ($changes{'categorize'}) {
17784:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
17785:             }
17786:             if ($changes{'togglecatscomm'}) {
17787:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
17788:             }
17789:             if ($changes{'categorizecomm'}) {
17790:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
17791:             }
17792:             if ($changes{'unauth'}) {
17793:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
17794:             }
17795:             if ($changes{'auth'}) {
17796:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
17797:             }
17798:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
17799:                 my $cathash;
17800:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
17801:                     $cathash = $domconfig{'coursecategories'}{'cats'};
17802:                 } else {
17803:                     $cathash = {};
17804:                 } 
17805:                 my (@cats,@trails,%allitems);
17806:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
17807:                 if (keys(%deletions) > 0) {
17808:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
17809:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
17810:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
17811:                     }
17812:                     $resulttext .= '</ul></li>';
17813:                 }
17814:                 if (keys(%reorderings) > 0) {
17815:                     my %sort_by_trail;
17816:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
17817:                     foreach my $key (keys(%reorderings)) {
17818:                         if ($allitems{$key} ne '') {
17819:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
17820:                         }
17821:                     }
17822:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
17823:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
17824:                     }
17825:                     $resulttext .= '</ul></li>';
17826:                 }
17827:                 if (keys(%adds) > 0) {
17828:                     my %sort_by_trail;
17829:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
17830:                     foreach my $key (keys(%adds)) {
17831:                         if ($allitems{$key} ne '') {
17832:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
17833:                         }
17834:                     }
17835:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
17836:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
17837:                     }
17838:                     $resulttext .= '</ul></li>';
17839:                 }
17840:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
17841:                 if (ref($lastactref) eq 'HASH') {
17842:                     $lastactref->{'cats'} = 1;
17843:                 }
17844:             }
17845:             $resulttext .= '</ul>';
17846:             if ($changes{'unauth'} || $changes{'auth'}) {
17847:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
17848:                 if ($changes{'auth'}) {
17849:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
17850:                 }
17851:                 if ($changes{'unauth'}) {
17852:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
17853:                 }
17854:                 my $cachetime = 24*60*60;
17855:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17856:                 if (ref($lastactref) eq 'HASH') {
17857:                     $lastactref->{'domdefaults'} = 1;
17858:                 }
17859:             }
17860:         } else {
17861:             $resulttext = '<span class="LC_error">'.
17862:                           &mt('An error occurred: [_1]',$putresult).'</span>';
17863:         }
17864:     } else {
17865:         $resulttext = &mt('No changes made to course and community categories');
17866:     }
17867:     return $resulttext;
17868: }
17869: 
17870: sub modify_serverstatuses {
17871:     my ($dom,%domconfig) = @_;
17872:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
17873:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
17874:         %currserverstatus = %{$domconfig{'serverstatuses'}};
17875:     }
17876:     my @pages = &serverstatus_pages();
17877:     foreach my $type (@pages) {
17878:         $newserverstatus{$type}{'namedusers'} = '';
17879:         $newserverstatus{$type}{'machines'} = '';
17880:         if (defined($env{'form.'.$type.'_namedusers'})) {
17881:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
17882:             my @okusers;
17883:             foreach my $user (@users) {
17884:                 my ($uname,$udom) = split(/:/,$user);
17885:                 if (($udom =~ /^$match_domain$/) &&   
17886:                     (&Apache::lonnet::domain($udom)) &&
17887:                     ($uname =~ /^$match_username$/)) {
17888:                     if (!grep(/^\Q$user\E/,@okusers)) {
17889:                         push(@okusers,$user);
17890:                     }
17891:                 }
17892:             }
17893:             if (@okusers > 0) {
17894:                  @okusers = sort(@okusers);
17895:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
17896:             }
17897:         }
17898:         if (defined($env{'form.'.$type.'_machines'})) {
17899:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
17900:             my @okmachines;
17901:             foreach my $ip (@machines) {
17902:                 my @parts = split(/\./,$ip);
17903:                 next if (@parts < 4);
17904:                 my $badip = 0;
17905:                 for (my $i=0; $i<4; $i++) {
17906:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
17907:                         $badip = 1;
17908:                         last;
17909:                     }
17910:                 }
17911:                 if (!$badip) {
17912:                     push(@okmachines,$ip);     
17913:                 }
17914:             }
17915:             @okmachines = sort(@okmachines);
17916:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
17917:         }
17918:     }
17919:     my %serverstatushash =  (
17920:                                 serverstatuses => \%newserverstatus,
17921:                             );
17922:     foreach my $type (@pages) {
17923:         foreach my $setting ('namedusers','machines') {
17924:             my (@current,@new);
17925:             if (ref($currserverstatus{$type}) eq 'HASH') {
17926:                 if ($currserverstatus{$type}{$setting} ne '') { 
17927:                     @current = split(/,/,$currserverstatus{$type}{$setting});
17928:                 }
17929:             }
17930:             if ($newserverstatus{$type}{$setting} ne '') {
17931:                 @new = split(/,/,$newserverstatus{$type}{$setting});
17932:             }
17933:             if (@current > 0) {
17934:                 if (@new > 0) {
17935:                     foreach my $item (@current) {
17936:                         if (!grep(/^\Q$item\E$/,@new)) {
17937:                             $changes{$type}{$setting} = 1;
17938:                             last;
17939:                         }
17940:                     }
17941:                     foreach my $item (@new) {
17942:                         if (!grep(/^\Q$item\E$/,@current)) {
17943:                             $changes{$type}{$setting} = 1;
17944:                             last;
17945:                         }
17946:                     }
17947:                 } else {
17948:                     $changes{$type}{$setting} = 1;
17949:                 }
17950:             } elsif (@new > 0) {
17951:                 $changes{$type}{$setting} = 1;
17952:             }
17953:         }
17954:     }
17955:     if (keys(%changes) > 0) {
17956:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
17957:         my $putresult = &Apache::lonnet::put_dom('configuration',
17958:                                                  \%serverstatushash,$dom);
17959:         if ($putresult eq 'ok') {
17960:             $resulttext .= &mt('Changes made:').'<ul>';
17961:             foreach my $type (@pages) {
17962:                 if (ref($changes{$type}) eq 'HASH') {
17963:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
17964:                     if ($changes{$type}{'namedusers'}) {
17965:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
17966:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
17967:                         } else {
17968:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
17969:                         }
17970:                     }
17971:                     if ($changes{$type}{'machines'}) {
17972:                         if ($newserverstatus{$type}{'machines'} eq '') {
17973:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
17974:                         } else {
17975:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
17976:                         }
17977: 
17978:                     }
17979:                     $resulttext .= '</ul></li>';
17980:                 }
17981:             }
17982:             $resulttext .= '</ul>';
17983:         } else {
17984:             $resulttext = '<span class="LC_error">'.
17985:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
17986: 
17987:         }
17988:     } else {
17989:         $resulttext = &mt('No changes made to access to server status pages');
17990:     }
17991:     return $resulttext;
17992: }
17993: 
17994: sub modify_helpsettings {
17995:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
17996:     my ($resulttext,$errors,%changes,%helphash);
17997:     my %defaultchecked = ('submitbugs' => 'on');
17998:     my @offon = ('off','on');
17999:     my @toggles = ('submitbugs');
18000:     my %current = ('submitbugs' => '',
18001:                    'adhoc'      => {},
18002:                   );
18003:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
18004:         %current = %{$domconfig{'helpsettings'}};
18005:     }
18006:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18007:     foreach my $item (@toggles) {
18008:         if ($defaultchecked{$item} eq 'on') { 
18009:             if ($current{$item} eq '') {
18010:                 if ($env{'form.'.$item} eq '0') {
18011:                     $changes{$item} = 1;
18012:                 }
18013:             } elsif ($current{$item} ne $env{'form.'.$item}) {
18014:                 $changes{$item} = 1;
18015:             }
18016:         } elsif ($defaultchecked{$item} eq 'off') {
18017:             if ($current{$item} eq '') {
18018:                 if ($env{'form.'.$item} eq '1') {
18019:                     $changes{$item} = 1;
18020:                 }
18021:             } elsif ($current{$item} ne $env{'form.'.$item}) {
18022:                 $changes{$item} = 1;
18023:             }
18024:         }
18025:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
18026:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
18027:         }
18028:     }
18029:     my $maxnum = $env{'form.helproles_maxnum'};
18030:     my $confname = $dom.'-domainconfig';
18031:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
18032:     my (@allpos,%newsettings,%changedprivs,$newrole);
18033:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18034:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
18035:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
18036:     my %lt = &Apache::lonlocal::texthash(
18037:                     s      => 'system',
18038:                     d      => 'domain',
18039:                     order  => 'Display order',
18040:                     access => 'Role usage',
18041:                     all    => 'All with domain helpdesk or helpdesk assistant role',
18042:                     dh     => 'All with domain helpdesk role',
18043:                     da     => 'All with domain helpdesk assistant role',
18044:                     none   => 'None',
18045:                     status => 'Determined based on institutional status',
18046:                     inc    => 'Include all, but exclude specific personnel',
18047:                     exc    => 'Exclude all, but include specific personnel',
18048:     );
18049:     for (my $num=0; $num<=$maxnum; $num++) {
18050:         my ($prefix,$identifier,$rolename,%curr);
18051:         if ($num == $maxnum) {
18052:             next unless ($env{'form.newcusthelp'} == $maxnum);
18053:             $identifier = 'custhelp'.$num;
18054:             $prefix = 'helproles_'.$num;
18055:             $rolename = $env{'form.custhelpname'.$num};
18056:             $rolename=~s/[^A-Za-z0-9]//gs;
18057:             next if ($rolename eq '');
18058:             next if (exists($existing{'rolesdef_'.$rolename}));
18059:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
18060:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
18061:                                                      $newprivs{'c'},$confname,$dom);
18062:             if ($result ne 'ok') {
18063:                 $errors .= '<li><span class="LC_error">'.
18064:                            &mt('An error occurred storing the new custom role: [_1]',
18065:                            $result).'</span></li>';
18066:                 next;
18067:             } else {
18068:                 $changedprivs{$rolename} = \%newprivs;
18069:                 $newrole = $rolename;
18070:             }
18071:         } else {
18072:             $prefix = 'helproles_'.$num;
18073:             $rolename = $env{'form.'.$prefix};
18074:             next if ($rolename eq '');
18075:             next unless (exists($existing{'rolesdef_'.$rolename}));
18076:             $identifier = 'custhelp'.$num;
18077:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
18078:             my %currprivs;
18079:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
18080:                 split(/\_/,$existing{'rolesdef_'.$rolename});
18081:             foreach my $level ('c','d','s') {
18082:                 if ($newprivs{$level} ne $currprivs{$level}) {
18083:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
18084:                                                              $newprivs{'c'},$confname,$dom);
18085:                     if ($result ne 'ok') {
18086:                         $errors .= '<li><span class="LC_error">'.
18087:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
18088:                                        $rolename,$result).'</span></li>';
18089:                     } else {
18090:                         $changedprivs{$rolename} = \%newprivs;
18091:                     }
18092:                     last;
18093:                 }
18094:             }
18095:             if (ref($current{'adhoc'}) eq 'HASH') {
18096:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
18097:                     %curr = %{$current{'adhoc'}{$rolename}};
18098:                 }
18099:             }
18100:         }
18101:         my $newpos = $env{'form.'.$prefix.'_pos'};
18102:         $newpos =~ s/\D+//g;
18103:         $allpos[$newpos] = $rolename;
18104:         my $newdesc = $env{'form.'.$prefix.'_desc'};
18105:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
18106:         if ($curr{'desc'}) {
18107:             if ($curr{'desc'} ne $newdesc) {
18108:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
18109:                 $newsettings{$rolename}{'desc'} = $newdesc;
18110:             }
18111:         } elsif ($newdesc ne '') {
18112:             $changes{'customrole'}{$rolename}{'desc'} = 1;
18113:             $newsettings{$rolename}{'desc'} = $newdesc;
18114:         }
18115:         my $access = $env{'form.'.$prefix.'_access'};
18116:         if (grep(/^\Q$access\E$/,@accesstypes)) {
18117:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
18118:             if ($access eq 'status') {
18119:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
18120:                 if (scalar(@statuses) == 0) {
18121:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
18122:                 } else {
18123:                     my (@shownstatus,$numtypes);
18124:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
18125:                     if (ref($types) eq 'ARRAY') {
18126:                         $numtypes = scalar(@{$types});
18127:                         foreach my $type (sort(@statuses)) {
18128:                             if ($type eq 'default') {
18129:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
18130:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
18131:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
18132:                                 push(@shownstatus,$usertypes->{$type});
18133:                             }
18134:                         }
18135:                     }
18136:                     if (grep(/^default$/,@statuses)) {
18137:                         push(@shownstatus,$othertitle);
18138:                     }
18139:                     if (scalar(@shownstatus) == 1+$numtypes) {
18140:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
18141:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
18142:                     } else {
18143:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
18144:                         if (ref($curr{'status'}) eq 'ARRAY') {
18145:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
18146:                             if (@diffs) {
18147:                                 $changes{'customrole'}{$rolename}{$access} = 1;
18148:                             }
18149:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
18150:                             $changes{'customrole'}{$rolename}{$access} = 1;
18151:                         }
18152:                     }
18153:                 }
18154:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
18155:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
18156:                 my @newspecstaff;
18157:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
18158:                 foreach my $person (sort(@personnel)) {
18159:                     if ($domhelpdesk{$person}) {
18160:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
18161:                     }
18162:                 }
18163:                 if (ref($curr{$access}) eq 'ARRAY') {
18164:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
18165:                     if (@diffs) {
18166:                         $changes{'customrole'}{$rolename}{$access} = 1;
18167:                     }
18168:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
18169:                     $changes{'customrole'}{$rolename}{$access} = 1;
18170:                 }
18171:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
18172:                     my ($uname,$udom) = split(/:/,$person);
18173:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
18174:                 }
18175:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
18176:             }
18177:         } else {
18178:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
18179:         }
18180:         unless ($curr{'access'} eq $access) {
18181:             $changes{'customrole'}{$rolename}{'access'} = 1;
18182:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
18183:         }
18184:     }
18185:     if (@allpos > 0) {
18186:         my $idx = 0;
18187:         foreach my $rolename (@allpos) {
18188:             if ($rolename ne '') {
18189:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
18190:                 if (ref($current{'adhoc'}) eq 'HASH') {
18191:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
18192:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
18193:                             $changes{'customrole'}{$rolename}{'order'} = 1;
18194:                             $newsettings{$rolename}{'order'} = $idx+1;
18195:                         }
18196:                     }
18197:                 }
18198:                 $idx ++;
18199:             }
18200:         }
18201:     }
18202:     my $putresult;
18203:     if (keys(%changes) > 0) {
18204:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
18205:         if ($putresult eq 'ok') {
18206:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
18207:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
18208:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
18209:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
18210:                 }
18211:             }
18212:             my $cachetime = 24*60*60;
18213:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18214:             if (ref($lastactref) eq 'HASH') {
18215:                 $lastactref->{'domdefaults'} = 1;
18216:             }
18217:         } else {
18218:             $errors .= '<li><span class="LC_error">'.
18219:                        &mt('An error occurred storing the settings: [_1]',
18220:                            $putresult).'</span></li>';
18221:         }
18222:     }
18223:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
18224:         $resulttext = &mt('Changes made:').'<ul>';
18225:         my (%shownprivs,@levelorder);
18226:         @levelorder = ('c','d','s');
18227:         if ((keys(%changes)) && ($putresult eq 'ok')) {
18228:             foreach my $item (sort(keys(%changes))) {
18229:                 if ($item eq 'submitbugs') {
18230:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
18231:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
18232:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
18233:                 } elsif ($item eq 'customrole') {
18234:                     if (ref($changes{'customrole'}) eq 'HASH') {
18235:                         my @keyorder = ('order','desc','access','status','exc','inc');
18236:                         my %keytext = &Apache::lonlocal::texthash(
18237:                                                                    order  => 'Order',
18238:                                                                    desc   => 'Role description',
18239:                                                                    access => 'Role usage',
18240:                                                                    status => 'Allowed institutional types',
18241:                                                                    exc    => 'Allowed personnel',
18242:                                                                    inc    => 'Disallowed personnel',
18243:                         );
18244:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
18245:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
18246:                                 if ($role eq $newrole) {
18247:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
18248:                                                               $role).'<ul>';
18249:                                 } else {
18250:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
18251:                                                               $role).'<ul>';
18252:                                 }
18253:                                 foreach my $key (@keyorder) {
18254:                                     if ($changes{'customrole'}{$role}{$key}) {
18255:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
18256:                                                                   $keytext{$key},$newsettings{$role}{$key}).
18257:                                                        '</li>';
18258:                                     }
18259:                                 }
18260:                                 if (ref($changedprivs{$role}) eq 'HASH') {
18261:                                     $shownprivs{$role} = 1;
18262:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
18263:                                     foreach my $level (@levelorder) {
18264:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
18265:                                             next if ($item eq '');
18266:                                             my ($priv) = split(/\&/,$item,2);
18267:                                             if (&Apache::lonnet::plaintext($priv)) {
18268:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
18269:                                                 unless ($level eq 'c') {
18270:                                                     $resulttext .= ' ('.$lt{$level}.')';
18271:                                                 }
18272:                                                 $resulttext .= '</li>';
18273:                                             }
18274:                                         }
18275:                                     }
18276:                                     $resulttext .= '</ul>';
18277:                                 }
18278:                                 $resulttext .= '</ul></li>';
18279:                             }
18280:                         }
18281:                     }
18282:                 }
18283:             }
18284:         }
18285:         if (keys(%changedprivs)) {
18286:             foreach my $role (sort(keys(%changedprivs))) {
18287:                 unless ($shownprivs{$role}) {
18288:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
18289:                                               $role).'<ul>'.
18290:                                    '<li>'.&mt('Privileges set to :').'<ul>';
18291:                     foreach my $level (@levelorder) {
18292:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
18293:                             next if ($item eq '');
18294:                             my ($priv) = split(/\&/,$item,2);
18295:                             if (&Apache::lonnet::plaintext($priv)) {
18296:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
18297:                                 unless ($level eq 'c') {
18298:                                     $resulttext .= ' ('.$lt{$level}.')';
18299:                                 }
18300:                                 $resulttext .= '</li>';
18301:                             }
18302:                         }
18303:                     }
18304:                     $resulttext .= '</ul></li></ul></li>';
18305:                 }
18306:             }
18307:         }
18308:         $resulttext .= '</ul>';
18309:     } else {
18310:         $resulttext = &mt('No changes made to help settings');
18311:     }
18312:     if ($errors) {
18313:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
18314:                                     $errors.'</ul>';
18315:     }
18316:     return $resulttext;
18317: }
18318: 
18319: sub modify_coursedefaults {
18320:     my ($dom,$lastactref,%domconfig) = @_;
18321:     my ($resulttext,$errors,%changes,%defaultshash);
18322:     my %defaultchecked = (
18323:                            'uselcmath'       => 'on',
18324:                            'usejsme'         => 'on',
18325:                            'inline_chem'     => 'on',
18326:                            'ltiauth'         => 'off',
18327:                          );
18328:     my @toggles = ('uselcmath','usejsme','inline_chem','ltiauth');
18329:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
18330:                    'uploadquota_community','uploadquota_textbook','mysqltables_official',
18331:                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
18332:     my @types = ('official','unofficial','community','textbook');
18333:     my %staticdefaults = (
18334:                            anonsurvey_threshold => 10,
18335:                            uploadquota          => 500,
18336:                            postsubmit           => 60,
18337:                            mysqltables          => 172800,
18338:                            domexttool           => 1,
18339:                          );
18340:     my %texoptions = (
18341:                         MathJax  => 'MathJax',
18342:                         mimetex  => &mt('Convert to Images'),
18343:                         tth      => &mt('TeX to HTML'),
18344:                      );
18345:     $defaultshash{'coursedefaults'} = {};
18346: 
18347:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
18348:         if ($domconfig{'coursedefaults'} eq '') {
18349:             $domconfig{'coursedefaults'} = {};
18350:         }
18351:     }
18352: 
18353:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
18354:         foreach my $item (@toggles) {
18355:             if ($defaultchecked{$item} eq 'on') {
18356:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
18357:                     ($env{'form.'.$item} eq '0')) {
18358:                     $changes{$item} = 1;
18359:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
18360:                     $changes{$item} = 1;
18361:                 }
18362:             } elsif ($defaultchecked{$item} eq 'off') {
18363:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
18364:                     ($env{'form.'.$item} eq '1')) {
18365:                     $changes{$item} = 1;
18366:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
18367:                     $changes{$item} = 1;
18368:                 }
18369:             }
18370:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
18371:         }
18372:         foreach my $item (@numbers) {
18373:             my ($currdef,$newdef);
18374:             $newdef = $env{'form.'.$item};
18375:             if ($item eq 'anonsurvey_threshold') {
18376:                 $currdef = $domconfig{'coursedefaults'}{$item};
18377:                 $newdef =~ s/\D//g;
18378:                 if ($newdef eq '' || $newdef < 1) {
18379:                     $newdef = 1;
18380:                 }
18381:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
18382:             } else {
18383:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
18384:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
18385:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
18386:                 }
18387:                 $newdef =~ s/[^\w.\-]//g;
18388:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
18389:             }
18390:             if ($currdef ne $newdef) {
18391:                 if ($item eq 'anonsurvey_threshold') {
18392:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
18393:                         $changes{$item} = 1;
18394:                     }
18395:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
18396:                     my $setting = $1;
18397:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
18398:                         $changes{$setting} = 1;
18399:                     }
18400:                 }
18401:             }
18402:         }
18403:         my $texengine;
18404:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
18405:             $texengine = $env{'form.texengine'};
18406:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
18407:             if ($currdef eq '') {
18408:                 unless ($texengine eq $Apache::lonnet::deftex) {
18409:                     $changes{'texengine'} = 1;
18410:                 }
18411:             } elsif ($currdef ne $texengine) {
18412:                 $changes{'texengine'} = 1;
18413:             }
18414:         }
18415:         if ($texengine ne '') {
18416:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
18417:         }
18418:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
18419:         my @currclonecode;
18420:         if (ref($currclone) eq 'HASH') {
18421:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
18422:                 @currclonecode = @{$currclone->{'instcode'}};
18423:             }
18424:         }
18425:         my $newclone;
18426:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
18427:             $newclone = $env{'form.canclone'};
18428:         }
18429:         if ($newclone eq 'instcode') {
18430:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
18431:             my (%codedefaults,@code_order,@clonecode);
18432:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
18433:                                                     \@code_order);
18434:             foreach my $item (@code_order) {
18435:                 if (grep(/^\Q$item\E$/,@newcodes)) {
18436:                     push(@clonecode,$item);
18437:                 }
18438:             }
18439:             if (@clonecode) {
18440:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
18441:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
18442:                 if (@diffs) {
18443:                     $changes{'canclone'} = 1;
18444:                 }
18445:             } else {
18446:                 $newclone eq '';
18447:             }
18448:         } elsif ($newclone ne '') {
18449:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
18450:         }
18451:         if ($newclone ne $currclone) {
18452:             $changes{'canclone'} = 1;
18453:         }
18454:         my %credits;
18455:         foreach my $type (@types) {
18456:             unless ($type eq 'community') {
18457:                 $credits{$type} = $env{'form.'.$type.'_credits'};
18458:                 $credits{$type} =~ s/[^\d.]+//g;
18459:             }
18460:         }
18461:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
18462:             ($env{'form.coursecredits'} eq '1')) {
18463:             $changes{'coursecredits'} = 1;
18464:             foreach my $type (keys(%credits)) {
18465:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
18466:             }
18467:         } else {
18468:             if ($env{'form.coursecredits'} eq '1') {
18469:                 foreach my $type (@types) {
18470:                     unless ($type eq 'community') {
18471:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
18472:                             $changes{'coursecredits'} = 1;
18473:                         }
18474:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
18475:                     }
18476:                 }
18477:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
18478:                 foreach my $type (@types) {
18479:                     unless ($type eq 'community') {
18480:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
18481:                             $changes{'coursecredits'} = 1;
18482:                             last;
18483:                         }
18484:                     }
18485:                 }
18486:             }
18487:         }
18488:         if ($env{'form.postsubmit'} eq '1') {
18489:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
18490:             my %currtimeout;
18491:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
18492:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
18493:                     $changes{'postsubmit'} = 1;
18494:                 }
18495:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
18496:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
18497:                 }
18498:             } else {
18499:                 $changes{'postsubmit'} = 1;
18500:             }
18501:             foreach my $type (@types) {
18502:                 my $timeout = $env{'form.'.$type.'_timeout'};
18503:                 $timeout =~ s/\D//g;
18504:                 if ($timeout == $staticdefaults{'postsubmit'}) {
18505:                     $timeout = '';
18506:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
18507:                     $timeout = '0';
18508:                 }
18509:                 unless ($timeout eq '') {
18510:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
18511:                 }
18512:                 if (exists($currtimeout{$type})) {
18513:                     if ($timeout ne $currtimeout{$type}) {
18514:                         $changes{'postsubmit'} = 1;
18515:                     }
18516:                 } elsif ($timeout ne '') {
18517:                     $changes{'postsubmit'} = 1;
18518:                 }
18519:             }
18520:         } else {
18521:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
18522:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
18523:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
18524:                     $changes{'postsubmit'} = 1;
18525:                 }
18526:             } else {
18527:                 $changes{'postsubmit'} = 1;
18528:             }
18529:         }
18530:         my (%newdomexttool,%newexttool,%olddomexttool,%oldexttool);
18531:         map { $newdomexttool{$_} = 1; } &Apache::loncommon::get_env_multiple('form.domexttool');
18532:         map { $newexttool{$_} = 1; } &Apache::loncommon::get_env_multiple('form.exttool');
18533:         if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
18534:             %olddomexttool = %{$domconfig{'coursedefaults'}{'domexttool'}};
18535:         } else {
18536:            foreach my $type (@types) {
18537:                if ($staticdefaults{'domexttool'}) {
18538:                    $olddomexttool{$type} = 1;
18539:                } else {
18540:                    $olddomexttool{$type} = 0;
18541:                }
18542:             }
18543:         }
18544:         if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
18545:             %oldexttool = %{$domconfig{'coursedefaults'}{'exttool'}};
18546:         } else {
18547:             foreach my $type (@types) {
18548:                if ($staticdefaults{'exttool'}) {
18549:                    $oldexttool{$type} = 1;
18550:                } else {
18551:                    $oldexttool{$type} = 0;
18552:                }
18553:             }
18554:         }
18555:         foreach my $type (@types) {
18556:             unless ($newdomexttool{$type}) {
18557:                 $newdomexttool{$type} = 0;
18558:             }
18559:             unless ($newexttool{$type}) {
18560:                 $newexttool{$type} = 0;
18561:             }
18562:             if ($newdomexttool{$type} != $olddomexttool{$type}) {
18563:                 $changes{'domexttool'} = 1;
18564:             }
18565:             if ($newexttool{$type} != $oldexttool{$type}) {
18566:                 $changes{'exttool'} = 1;
18567:             }
18568:         }
18569:         $defaultshash{'coursedefaults'}{'domexttool'} = \%newdomexttool;
18570:         $defaultshash{'coursedefaults'}{'exttool'} = \%newexttool;
18571:     }
18572:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18573:                                              $dom);
18574:     if ($putresult eq 'ok') {
18575:         if (keys(%changes) > 0) {
18576:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18577:             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
18578:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
18579:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
18580:                 ($changes{'inline_chem'}) || ($changes{'ltiauth'}) || ($changes{'domexttool'}) ||
18581:                 ($changes{'exttool'})) {
18582:                 foreach my $item ('uselcmath','usejsme','inline_chem','texengine','ltiauth') {
18583:                     if ($changes{$item}) {
18584:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
18585:                     }
18586:                 }
18587:                 if ($changes{'coursecredits'}) {
18588:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
18589:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
18590:                             $domdefaults{$type.'credits'} =
18591:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
18592:                         }
18593:                     }
18594:                 }
18595:                 if ($changes{'postsubmit'}) {
18596:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
18597:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
18598:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
18599:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
18600:                                 $domdefaults{$type.'postsubtimeout'} =
18601:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
18602:                             }
18603:                         }
18604:                     }
18605:                 }
18606:                 if ($changes{'uploadquota'}) {
18607:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
18608:                         foreach my $type (@types) {
18609:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
18610:                         }
18611:                     }
18612:                 }
18613:                 if ($changes{'canclone'}) {
18614:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
18615:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
18616:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
18617:                             if (@clonecodes) {
18618:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
18619:                             }
18620:                         }
18621:                     } else {
18622:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
18623:                     }
18624:                 }
18625:                 if ($changes{'domexttool'}) {
18626:                     if (ref($defaultshash{'coursedefaults'}{'domexttool'}) eq 'HASH') {
18627:                         foreach my $type (@types) {
18628:                             $domdefaults{$type.'domexttool'}=$defaultshash{'coursedefaults'}{'domexttool'}{$type};
18629:                         }
18630:                     }
18631:                 }
18632:                 if ($changes{'exttool'}) {
18633:                     if (ref($defaultshash{'coursedefaults'}{'exttool'}) eq 'HASH') {
18634:                         foreach my $type (@types) {
18635:                             $domdefaults{$type.'exttool'}=$defaultshash{'coursedefaults'}{'exttool'}{$type};
18636:                         }
18637:                     }
18638:                 }
18639:                 my $cachetime = 24*60*60;
18640:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18641:                 if (ref($lastactref) eq 'HASH') {
18642:                     $lastactref->{'domdefaults'} = 1;
18643:                 }
18644:             }
18645:             $resulttext = &mt('Changes made:').'<ul>';
18646:             foreach my $item (sort(keys(%changes))) {
18647:                 if ($item eq 'uselcmath') {
18648:                     if ($env{'form.'.$item} eq '1') {
18649:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
18650:                     } else {
18651:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
18652:                     }
18653:                 } elsif ($item eq 'usejsme') {
18654:                     if ($env{'form.'.$item} eq '1') {
18655:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
18656:                     } else {
18657:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
18658:                     }
18659:                 } elsif ($item eq 'inline_chem') {
18660:                     if ($env{'form.'.$item} eq '1') {
18661:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
18662:                     } else {
18663:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
18664:                     }
18665:                 } elsif ($item eq 'texengine') {
18666:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
18667:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
18668:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
18669:                     }
18670:                 } elsif ($item eq 'anonsurvey_threshold') {
18671:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
18672:                 } elsif ($item eq 'uploadquota') {
18673:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
18674:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
18675:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
18676:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
18677:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
18678:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
18679:                                        '</ul>'.
18680:                                        '</li>';
18681:                     } else {
18682:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
18683:                     }
18684:                 } elsif ($item eq 'mysqltables') {
18685:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
18686:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
18687:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
18688:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
18689:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
18690:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
18691:                                        '</ul>'.
18692:                                        '</li>';
18693:                     } else {
18694:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
18695:                     }
18696:                 } elsif ($item eq 'postsubmit') {
18697:                     if ($domdefaults{'postsubmit'} eq 'off') {
18698:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
18699:                     } else {
18700:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
18701:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
18702:                             $resulttext .= &mt('durations:').'<ul>';
18703:                             foreach my $type (@types) {
18704:                                 $resulttext .= '<li>';
18705:                                 my $timeout;
18706:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
18707:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
18708:                                 }
18709:                                 my $display;
18710:                                 if ($timeout eq '0') {
18711:                                     $display = &mt('unlimited');
18712:                                 } elsif ($timeout eq '') {
18713:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
18714:                                 } else {
18715:                                     $display = &mt('[quant,_1,second]',$timeout);
18716:                                 }
18717:                                 if ($type eq 'community') {
18718:                                     $resulttext .= &mt('Communities');
18719:                                 } elsif ($type eq 'official') {
18720:                                     $resulttext .= &mt('Official courses');
18721:                                 } elsif ($type eq 'unofficial') {
18722:                                     $resulttext .= &mt('Unofficial courses');
18723:                                 } elsif ($type eq 'textbook') {
18724:                                     $resulttext .= &mt('Textbook courses');
18725:                                 }
18726:                                 $resulttext .= ' -- '.$display.'</li>';
18727:                             }
18728:                             $resulttext .= '</ul>';
18729:                         }
18730:                         $resulttext .= '</li>';
18731:                     }
18732:                 } elsif ($item eq 'coursecredits') {
18733:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
18734:                         if (($domdefaults{'officialcredits'} eq '') &&
18735:                             ($domdefaults{'unofficialcredits'} eq '') &&
18736:                             ($domdefaults{'textbookcredits'} eq '')) {
18737:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
18738:                         } else {
18739:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
18740:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
18741:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
18742:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
18743:                                            '</ul>'.
18744:                                            '</li>';
18745:                         }
18746:                     } else {
18747:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
18748:                     }
18749:                 } elsif ($item eq 'canclone') {
18750:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
18751:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
18752:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
18753:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
18754:                         }
18755:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
18756:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
18757:                     } else {
18758:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
18759:                     }
18760:                 } elsif ($item eq 'ltiauth') {
18761:                     if ($env{'form.'.$item} eq '1') {
18762:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
18763:                     } else {
18764:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
18765:                     }
18766:                 } elsif ($item eq 'domexttool') {
18767:                     my @noyes = (&mt('no'),&mt('yes'));
18768:                     if (ref($defaultshash{'coursedefaults'}{'domexttool'}) eq 'HASH') {
18769:                         $resulttext .= '<li>'.&mt('External Tools defined in the domain may be used as follows:').'<ul>'.
18770:                                        '<li>'.&mt('Official courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'official'}].'</b>').'</li>'.
18771:                                        '<li>'.&mt('Unofficial courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'unofficial'}].'</b>').'</li>'.
18772:                                        '<li>'.&mt('Textbook courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'textbook'}].'</b>').'</li>'.
18773:                                        '<li>'.&mt('Placement tests: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'placement'}].'</b>').'</li>'.
18774:                                        '<li>'.&mt('Communities: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'community'}].'</b>').'</li>'.
18775:                                        '</ul>'.
18776:                                        '</li>';
18777:                     } else {
18778:                         $resulttext .= '<li>'.&mt('External Tools defined in the domain may be used in all course types, by default').'</li>';
18779:                     }
18780:                 } elsif ($item eq 'exttool') {
18781:                     my @noyes = (&mt('no'),&mt('yes'));
18782:                     if (ref($defaultshash{'coursedefaults'}{'exttool'}) eq 'HASH') {
18783:                         $resulttext .= '<li>'.&mt('External Tools can be defined and configured in course containers as follows:').'<ul>'.
18784:                                        '<li>'.&mt('Official courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'official'}].'</b>').'</li>'.
18785:                                        '<li>'.&mt('Unofficial courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'unofficial'}].'</b>').'</li>'.
18786:                                        '<li>'.&mt('Textbook courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'textbook'}].'</b>').'</li>'.
18787:                                        '<li>'.&mt('Placement tests: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'placement'}].'</b>').'</li>'.
18788:                                        '<li>'.&mt('Communities: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'community'}].'</b>').'</li>'.
18789:                                        '</ul>'.
18790:                                        '</li>';
18791:                     } else {
18792:                         $resulttext .= '<li>'.&mt('External Tools can not be defined in any course types, by default').'</li>';
18793:                     }
18794:                 }
18795:             }
18796:             $resulttext .= '</ul>';
18797:         } else {
18798:             $resulttext = &mt('No changes made to course defaults');
18799:         }
18800:     } else {
18801:         $resulttext = '<span class="LC_error">'.
18802:             &mt('An error occurred: [_1]',$putresult).'</span>';
18803:     }
18804:     return $resulttext;
18805: }
18806: 
18807: sub modify_selfenrollment {
18808:     my ($dom,$lastactref,%domconfig) = @_;
18809:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
18810:     my @types = ('official','unofficial','community','textbook');
18811:     my %titles = &tool_titles();
18812:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
18813:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
18814:     $ordered{'default'} = ['types','registered','approval','limit'];
18815: 
18816:     my (%roles,%shown,%toplevel);
18817:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
18818: 
18819:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
18820:         if ($domconfig{'selfenrollment'} eq '') {
18821:             $domconfig{'selfenrollment'} = {};
18822:         }
18823:     }
18824:     %toplevel = (
18825:                   admin      => 'Configuration Rights',
18826:                   default    => 'Default settings',
18827:                   validation => 'Validation of self-enrollment requests',
18828:                 );
18829:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
18830: 
18831:     if (ref($ordered{'admin'}) eq 'ARRAY') {
18832:         foreach my $item (@{$ordered{'admin'}}) {
18833:             foreach my $type (@types) {
18834:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
18835:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
18836:                 } else {
18837:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
18838:                 }
18839:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
18840:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
18841:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
18842:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
18843:                             push(@{$changes{'admin'}{$type}},$item);
18844:                         }
18845:                     } else {
18846:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
18847:                             push(@{$changes{'admin'}{$type}},$item);
18848:                         }
18849:                     }
18850:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
18851:                     push(@{$changes{'admin'}{$type}},$item);
18852:                 }
18853:             }
18854:         }
18855:     }
18856: 
18857:     foreach my $item (@{$ordered{'default'}}) {
18858:         foreach my $type (@types) {
18859:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
18860:             if ($item eq 'types') {
18861:                 unless (($value eq 'all') || ($value eq 'dom')) {
18862:                     $value = '';
18863:                 }
18864:             } elsif ($item eq 'registered') {
18865:                 unless ($value eq '1') {
18866:                     $value = 0;
18867:                 }
18868:             } elsif ($item eq 'approval') {
18869:                 unless ($value =~ /^[012]$/) {
18870:                     $value = 0;
18871:                 }
18872:             } else {
18873:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
18874:                     $value = 'none';
18875:                 }
18876:             }
18877:             $selfenrollhash{'default'}{$type}{$item} = $value;
18878:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
18879:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
18880:                     if ($selfenrollhash{'default'}{$type}{$item} ne
18881:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
18882:                          push(@{$changes{'default'}{$type}},$item);
18883:                     }
18884:                 } else {
18885:                     push(@{$changes{'default'}{$type}},$item);
18886:                 }
18887:             } else {
18888:                 push(@{$changes{'default'}{$type}},$item);
18889:             }
18890:             if ($item eq 'limit') {
18891:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
18892:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
18893:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
18894:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
18895:                     }
18896:                 } else {
18897:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
18898:                 }
18899:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
18900:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
18901:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
18902:                          push(@{$changes{'default'}{$type}},'cap');
18903:                     }
18904:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
18905:                     push(@{$changes{'default'}{$type}},'cap');
18906:                 }
18907:             }
18908:         }
18909:     }
18910: 
18911:     foreach my $item (@{$itemsref}) {
18912:         if ($item eq 'fields') {
18913:             my @changed;
18914:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
18915:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
18916:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
18917:             }
18918:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
18919:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
18920:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
18921:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
18922:                 } else {
18923:                     @changed = @{$selfenrollhash{'validation'}{$item}};
18924:                 }
18925:             } else {
18926:                 @changed = @{$selfenrollhash{'validation'}{$item}};
18927:             }
18928:             if (@changed) {
18929:                 if ($selfenrollhash{'validation'}{$item}) { 
18930:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
18931:                 } else {
18932:                     $changes{'validation'}{$item} = &mt('None');
18933:                 }
18934:             }
18935:         } else {
18936:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
18937:             if ($item eq 'markup') {
18938:                if ($env{'form.selfenroll_validation_'.$item}) {
18939:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
18940:                }
18941:             }
18942:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
18943:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
18944:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
18945:                 }
18946:             }
18947:         }
18948:     }
18949: 
18950:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
18951:                                              $dom);
18952:     if ($putresult eq 'ok') {
18953:         if (keys(%changes) > 0) {
18954:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18955:             $resulttext = &mt('Changes made:').'<ul>';
18956:             foreach my $key ('admin','default','validation') {
18957:                 if (ref($changes{$key}) eq 'HASH') {
18958:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
18959:                     if ($key eq 'validation') {
18960:                         foreach my $item (@{$itemsref}) {
18961:                             if (exists($changes{$key}{$item})) {
18962:                                 if ($item eq 'markup') {
18963:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
18964:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
18965:                                 } else {  
18966:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
18967:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
18968:                                 }
18969:                             }
18970:                         }
18971:                     } else {
18972:                         foreach my $type (@types) {
18973:                             if ($type eq 'community') {
18974:                                 $roles{'1'} = &mt('Community personnel');
18975:                             } else {
18976:                                 $roles{'1'} = &mt('Course personnel');
18977:                             }
18978:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
18979:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
18980:                                     if ($key eq 'admin') {
18981:                                         my @mgrdc = ();
18982:                                         if (ref($ordered{$key}) eq 'ARRAY') {
18983:                                             foreach my $item (@{$ordered{'admin'}}) {
18984:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
18985:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
18986:                                                         push(@mgrdc,$item);
18987:                                                     }
18988:                                                 }
18989:                                             }
18990:                                             if (@mgrdc) {
18991:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
18992:                                             } else {
18993:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
18994:                                             }
18995:                                         }
18996:                                     } else {
18997:                                         if (ref($ordered{$key}) eq 'ARRAY') {
18998:                                             foreach my $item (@{$ordered{$key}}) {
18999:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
19000:                                                     $domdefaults{$type.'selfenroll'.$item} =
19001:                                                         $selfenrollhash{$key}{$type}{$item};
19002:                                                 }
19003:                                             }
19004:                                         }
19005:                                     }
19006:                                 }
19007:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
19008:                                 foreach my $item (@{$ordered{$key}}) {
19009:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
19010:                                         $resulttext .= '<li>';
19011:                                         if ($key eq 'admin') {
19012:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
19013:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
19014:                                         } else {
19015:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
19016:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
19017:                                         }
19018:                                         $resulttext .= '</li>';
19019:                                     }
19020:                                 }
19021:                                 $resulttext .= '</ul></li>';
19022:                             }
19023:                         }
19024:                         $resulttext .= '</ul></li>'; 
19025:                     }
19026:                 }
19027:             }
19028:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
19029:                 my $cachetime = 24*60*60;
19030:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19031:                 if (ref($lastactref) eq 'HASH') {
19032:                     $lastactref->{'domdefaults'} = 1;
19033:                 }
19034:             }
19035:             $resulttext .= '</ul>';
19036:         } else {
19037:             $resulttext = &mt('No changes made to self-enrollment settings');
19038:         }
19039:     } else {
19040:         $resulttext = '<span class="LC_error">'.
19041:             &mt('An error occurred: [_1]',$putresult).'</span>';
19042:     }
19043:     return $resulttext;
19044: }
19045: 
19046: sub modify_wafproxy {
19047:     my ($dom,$action,$lastactref,%domconfig) = @_;
19048:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19049:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
19050:         %wafproxy,%changes,%expirecache,%expiresaml);
19051:     foreach my $server (sort(keys(%servers))) {
19052:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
19053:         if ($serverhome eq $server) {
19054:             my $serverdom = &Apache::lonnet::host_domain($server);
19055:             if ($serverdom eq $dom) {
19056:                 $canset{$server} = 1;
19057:             }
19058:         }
19059:     }
19060:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
19061:         %{$values{$dom}} = ();
19062:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
19063:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
19064:         }
19065:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
19066:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
19067:         }
19068:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
19069:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
19070:         }
19071:     }
19072:     my $output;
19073:     if (keys(%canset)) {
19074:         %{$wafproxy{'alias'}} = ();
19075:         %{$wafproxy{'saml'}} = ();
19076:         foreach my $key (sort(keys(%canset))) {
19077:             if ($env{'form.wafproxy_'.$dom}) {
19078:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
19079:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
19080:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
19081:                     $changes{'alias'} = 1;
19082:                 }
19083:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
19084:                     $wafproxy{'saml'}{$key} = 1;
19085:                 }
19086:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
19087:                     $changes{'saml'} = 1;
19088:                 }
19089:             } else {
19090:                 $wafproxy{'alias'}{$key} = '';
19091:                 $wafproxy{'saml'}{$key} = '';
19092:                 if ($curralias{$key}) {
19093:                     $changes{'alias'} = 1;
19094:                 }
19095:                 if ($currsaml{$key}) {
19096:                     $changes{'saml'} = 1;
19097:                 }
19098:             }
19099:             if ($wafproxy{'alias'}{$key} eq '') {
19100:                 if ($curralias{$key}) {
19101:                     $expirecache{$key} = 1;
19102:                 }
19103:                 delete($wafproxy{'alias'}{$key});
19104:             }
19105:             if ($wafproxy{'saml'}{$key} eq '') {
19106:                 if ($currsaml{$key}) {
19107:                     $expiresaml{$key} = 1;
19108:                 }
19109:                 delete($wafproxy{'saml'}{$key});
19110:             }
19111:         }
19112:         unless (keys(%{$wafproxy{'alias'}})) {
19113:             delete($wafproxy{'alias'});
19114:         }
19115:         unless (keys(%{$wafproxy{'saml'}})) {
19116:             delete($wafproxy{'saml'});
19117:         }
19118:         # Localization for values in %warn occurs in &mt() calls separately.
19119:         my %warn = (
19120:                      trusted => 'trusted IP range(s)',
19121:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
19122:                      vpnext => 'IP range(s) for backend WAF connections',
19123:                    );
19124:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
19125:             my $possible = $env{'form.wafproxy_'.$item};
19126:             $possible =~ s/^\s+|\s+$//g;
19127:             if ($possible ne '') {
19128:                 if ($item eq 'remoteip') {
19129:                     if ($possible =~ /^[mhn]$/) {
19130:                         $wafproxy{$item} = $possible;
19131:                     }
19132:                 } elsif ($item eq 'ipheader') {
19133:                     if ($wafproxy{'remoteip'} eq 'h') {
19134:                         $wafproxy{$item} = $possible;
19135:                     }
19136:                 } elsif ($item eq 'sslopt') {
19137:                     if ($possible =~ /^0|1$/) {
19138:                         $wafproxy{$item} = $possible;
19139:                     }
19140:                 } else {
19141:                     my (@ok,$count);
19142:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
19143:                         unless ($env{'form.wafproxy_vpnaccess'}) {
19144:                             $possible = '';
19145:                         }
19146:                     } elsif ($item eq 'trusted') {
19147:                         unless ($wafproxy{'remoteip'} eq 'h') {
19148:                             $possible = '';
19149:                         }
19150:                     }
19151:                     unless ($possible eq '') {
19152:                         $possible =~ s/[\r\n]+/\s/g;
19153:                         $possible =~ s/\s*-\s*/-/g;
19154:                         $possible =~ s/\s+/,/g;
19155:                         $possible =~ s/,+/,/g;
19156:                     }
19157:                     $count = 0;
19158:                     if ($possible ne '') {
19159:                         foreach my $poss (split(/\,/,$possible)) {
19160:                             $count ++;
19161:                             $poss = &validate_ip_pattern($poss);
19162:                             if ($poss ne '') {
19163:                                 push(@ok,$poss);
19164:                             }
19165:                         }
19166:                         my $diff = $count - scalar(@ok);
19167:                         if ($diff) {
19168:                             push(@warnings,'<li>'.
19169:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
19170:                                      $diff,$warn{$item}).
19171:                                  '</li>');
19172:                         }
19173:                         if (@ok) {
19174:                             my @cidr_list;
19175:                             foreach my $item (@ok) {
19176:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
19177:                             }
19178:                             $wafproxy{$item} = join(',',@cidr_list);
19179:                         }
19180:                     }
19181:                 }
19182:                 if ($wafproxy{$item} ne $currvalue{$item}) {
19183:                     $changes{$item} = 1;
19184:                 }
19185:             } elsif ($currvalue{$item}) {
19186:                 $changes{$item} = 1;
19187:             }
19188:         }
19189:     } else {
19190:         if (keys(%curralias)) {
19191:             $changes{'alias'} = 1;
19192:         }
19193:         if (keys(%currsaml)) {
19194:             $changes{'saml'} = 1;
19195:         }
19196:         if (keys(%currvalue)) {
19197:             foreach my $key (keys(%currvalue)) {
19198:                 $changes{$key} = 1;
19199:             }
19200:         }
19201:     }
19202:     if (keys(%changes)) {
19203:         my %defaultshash = (
19204:                               wafproxy => \%wafproxy,
19205:                            );
19206:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
19207:                                                  $dom);
19208:         if ($putresult eq 'ok') {
19209:             my $cachetime = 24*60*60;
19210:             my (%domdefaults,$updatedomdefs);
19211:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
19212:                 if ($changes{$item}) {
19213:                     unless ($updatedomdefs) {
19214:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
19215:                         $updatedomdefs = 1;
19216:                     }
19217:                     if ($wafproxy{$item}) {
19218:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
19219:                     } elsif (exists($domdefaults{'waf_'.$item})) {
19220:                         delete($domdefaults{'waf_'.$item});
19221:                     }
19222:                 }
19223:             }
19224:             if ($updatedomdefs) {
19225:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19226:                 if (ref($lastactref) eq 'HASH') {
19227:                     $lastactref->{'domdefaults'} = 1;
19228:                 }
19229:             }
19230:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
19231:                 my %updates = %expirecache;
19232:                 foreach my $key (keys(%expirecache)) {
19233:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
19234:                 }
19235:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
19236:                     my $cachetime = 24*60*60;
19237:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
19238:                         $updates{$key} = 1;
19239:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
19240:                                                       $cachetime);
19241:                     }
19242:                 }
19243:                 if (ref($lastactref) eq 'HASH') {
19244:                     $lastactref->{'proxyalias'} = \%updates;
19245:                 }
19246:             }
19247:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
19248:                 my %samlupdates = %expiresaml;
19249:                 foreach my $key (keys(%expiresaml)) {
19250:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
19251:                 }
19252:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
19253:                     my $cachetime = 24*60*60;
19254:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
19255:                         $samlupdates{$key} = 1;
19256:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
19257:                                                       $cachetime);
19258:                     }
19259:                 }
19260:                 if (ref($lastactref) eq 'HASH') {
19261:                     $lastactref->{'proxysaml'} = \%samlupdates;
19262:                 }
19263:             }
19264:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
19265:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
19266:                 if ($changes{$item}) {
19267:                     if ($item eq 'alias') {
19268:                         my $numaliased = 0;
19269:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
19270:                             my $shown;
19271:                             if (keys(%{$wafproxy{'alias'}})) {
19272:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
19273:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
19274:                                                          &Apache::lonnet::hostname($server),
19275:                                                          $wafproxy{'alias'}{$server}).'</li>';
19276:                                     $numaliased ++;
19277:                                 }
19278:                                 if ($numaliased) {
19279:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
19280:                                                           '<ul>'.$shown.'</ul>').'</li>';
19281:                                 }
19282:                             }
19283:                         }
19284:                         unless ($numaliased) {
19285:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
19286:                         }
19287:                     } elsif ($item eq 'saml') {
19288:                         my $shown;
19289:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
19290:                             if (keys(%{$wafproxy{'saml'}})) {
19291:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
19292:                             }
19293:                         }
19294:                         if ($shown) {
19295:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
19296:                                                   $shown).'</li>';
19297:                         } else {
19298:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
19299:                         }
19300:                     } else {
19301:                         if ($item eq 'remoteip') {
19302:                             my %ip_methods = &remoteip_methods();
19303:                             if ($wafproxy{$item} =~ /^[mh]$/) {
19304:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
19305:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
19306:                             } else {
19307:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
19308:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
19309:                                                '</li>';
19310:                                 } else {
19311:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
19312:                                 }
19313:                             }
19314:                         } elsif ($item eq 'ipheader') {
19315:                             if ($wafproxy{$item}) {
19316:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
19317:                                                       $wafproxy{$item}).'</li>';
19318:                             } else {
19319:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
19320:                             }
19321:                         } elsif ($item eq 'trusted') {
19322:                             if ($wafproxy{$item}) {
19323:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
19324:                                                       $wafproxy{$item}).'</li>';
19325:                             } else {
19326:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
19327:                             }
19328:                         } elsif ($item eq 'vpnint') {
19329:                             if ($wafproxy{$item}) {
19330:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
19331:                                                        $wafproxy{$item}).'</li>';
19332:                             } else {
19333:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
19334:                             }
19335:                         } elsif ($item eq 'vpnext') {
19336:                             if ($wafproxy{$item}) {
19337:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
19338:                                                        $wafproxy{$item}).'</li>';
19339:                             } else {
19340:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
19341:                             }
19342:                         } elsif ($item eq 'sslopt') {
19343:                             if ($wafproxy{$item}) {
19344:                                 $output .= '<li>'.&mt('WAF/Reverse Proxy expected to forward requests to https on LON-CAPA node, regardless of original protocol in web browser (http or https).').'</li>';
19345:                             } else {
19346:                                 $output .= '<li>'.&mt('WAF/Reverse Proxy expected to preserve original protocol in web browser (either http or https) when forwarding to LON-CAPA node.').'</li>';
19347:                             }
19348:                         }
19349:                     }
19350:                 }
19351:             }
19352:             $output .= '</ul>';
19353:         } else {
19354:             $output = '<span class="LC_error">'.
19355:                       &mt('An error occurred: [_1]',$putresult).'</span>';
19356:         }
19357:     } elsif (keys(%canset)) {
19358:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
19359:     }
19360:     if (@warnings) {
19361:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
19362:                        join("\n",@warnings).'</ul>';
19363:     }
19364:     return $output;
19365: }
19366: 
19367: sub validate_ip_pattern {
19368:     my ($pattern) = @_;
19369:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
19370:         my ($start,$end) = ($1,$2);
19371:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
19372:             if (($start !~ m{/}) && ($end !~ m{/})) {
19373:                 return $start.'-'.$end;
19374:             }
19375:         }
19376:     } elsif ($pattern ne '') {
19377:         $pattern = &Net::CIDR::cidrvalidate($pattern);
19378:         if ($pattern ne '') {
19379:             return $pattern;
19380:         }
19381:     }
19382:     return;
19383: }
19384: 
19385: sub modify_usersessions {
19386:     my ($dom,$lastactref,%domconfig) = @_;
19387:     my @hostingtypes = ('version','excludedomain','includedomain');
19388:     my @offloadtypes = ('primary','default');
19389:     my %types = (
19390:                   remote => \@hostingtypes,
19391:                   hosted => \@hostingtypes,
19392:                   spares => \@offloadtypes,
19393:                 );
19394:     my @prefixes = ('remote','hosted','spares');
19395:     my @lcversions = &Apache::lonnet::all_loncaparevs();
19396:     my (%by_ip,%by_location,@intdoms);
19397:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
19398:     my @locations = sort(keys(%by_location));
19399:     my (%defaultshash,%changes);
19400:     foreach my $prefix (@prefixes) {
19401:         $defaultshash{'usersessions'}{$prefix} = {};
19402:     }
19403:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19404:     my $resulttext;
19405:     my %iphost = &Apache::lonnet::get_iphost();
19406:     foreach my $prefix (@prefixes) {
19407:         next if ($prefix eq 'spares');
19408:         foreach my $type (@{$types{$prefix}}) {
19409:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
19410:             if ($type eq 'version') {
19411:                 my $value = $env{'form.'.$prefix.'_'.$type};
19412:                 my $okvalue;
19413:                 if ($value ne '') {
19414:                     if (grep(/^\Q$value\E$/,@lcversions)) {
19415:                         $okvalue = $value;
19416:                     }
19417:                 }
19418:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
19419:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
19420:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
19421:                             if ($inuse == 0) {
19422:                                 $changes{$prefix}{$type} = 1;
19423:                             } else {
19424:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
19425:                                     $changes{$prefix}{$type} = 1;
19426:                                 }
19427:                                 if ($okvalue ne '') {
19428:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
19429:                                 } 
19430:                             }
19431:                         } else {
19432:                             if (($inuse == 1) && ($okvalue ne '')) {
19433:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
19434:                                 $changes{$prefix}{$type} = 1;
19435:                             }
19436:                         }
19437:                     } else {
19438:                         if (($inuse == 1) && ($okvalue ne '')) {
19439:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
19440:                             $changes{$prefix}{$type} = 1;
19441:                         }
19442:                     }
19443:                 } else {
19444:                     if (($inuse == 1) && ($okvalue ne '')) {
19445:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
19446:                         $changes{$prefix}{$type} = 1;
19447:                     }
19448:                 }
19449:             } else {
19450:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
19451:                 my @okvals;
19452:                 foreach my $val (@vals) {
19453:                     if ($val =~ /:/) {
19454:                         my @items = split(/:/,$val);
19455:                         foreach my $item (@items) {
19456:                             if (ref($by_location{$item}) eq 'ARRAY') {
19457:                                 push(@okvals,$item);
19458:                             }
19459:                         }
19460:                     } else {
19461:                         if (ref($by_location{$val}) eq 'ARRAY') {
19462:                             push(@okvals,$val);
19463:                         }
19464:                     }
19465:                 }
19466:                 @okvals = sort(@okvals);
19467:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
19468:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
19469:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
19470:                             if ($inuse == 0) {
19471:                                 $changes{$prefix}{$type} = 1; 
19472:                             } else {
19473:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
19474:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
19475:                                 if (@changed > 0) {
19476:                                     $changes{$prefix}{$type} = 1;
19477:                                 }
19478:                             }
19479:                         } else {
19480:                             if ($inuse == 1) {
19481:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
19482:                                 $changes{$prefix}{$type} = 1;
19483:                             }
19484:                         } 
19485:                     } else {
19486:                         if ($inuse == 1) {
19487:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
19488:                             $changes{$prefix}{$type} = 1;
19489:                         }
19490:                     }
19491:                 } else {
19492:                     if ($inuse == 1) {
19493:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
19494:                         $changes{$prefix}{$type} = 1;
19495:                     }
19496:                 }
19497:             }
19498:         }
19499:     }
19500: 
19501:     my @alldoms = &Apache::lonnet::all_domains();
19502:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19503:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
19504:     my $savespares;
19505: 
19506:     foreach my $lonhost (sort(keys(%servers))) {
19507:         my $serverhomeID =
19508:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
19509:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
19510:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
19511:         my %spareschg;
19512:         foreach my $type (@{$types{'spares'}}) {
19513:             my @okspares;
19514:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
19515:             foreach my $server (@checked) {
19516:                 if (&Apache::lonnet::hostname($server) ne '') {
19517:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
19518:                         unless (grep(/^\Q$server\E$/,@okspares)) {
19519:                             push(@okspares,$server);
19520:                         }
19521:                     }
19522:                 }
19523:             }
19524:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
19525:             my $newspare;
19526:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
19527:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
19528:                     $newspare = $new;
19529:                 }
19530:             }
19531:             my @spares;
19532:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
19533:                 @spares = sort(@okspares,$newspare);
19534:             } else {
19535:                 @spares = sort(@okspares);
19536:             }
19537:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
19538:             if (ref($spareid{$lonhost}) eq 'HASH') {
19539:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
19540:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
19541:                     if (@diffs > 0) {
19542:                         $spareschg{$type} = 1;
19543:                     }
19544:                 }
19545:             }
19546:         }
19547:         if (keys(%spareschg) > 0) {
19548:             $changes{'spares'}{$lonhost} = \%spareschg;
19549:         }
19550:     }
19551:     $defaultshash{'usersessions'}{'offloadnow'} = {};
19552:     $defaultshash{'usersessions'}{'offloadoth'} = {};
19553:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
19554:     my @okoffload;
19555:     if (@offloadnow) {
19556:         foreach my $server (@offloadnow) {
19557:             if (&Apache::lonnet::hostname($server) ne '') {
19558:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
19559:                     push(@okoffload,$server);
19560:                 }
19561:             }
19562:         }
19563:         if (@okoffload) {
19564:             foreach my $lonhost (@okoffload) {
19565:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
19566:             }
19567:         }
19568:     }
19569:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
19570:     my @okoffloadoth;
19571:     if (@offloadoth) {
19572:         foreach my $server (@offloadoth) {
19573:             if (&Apache::lonnet::hostname($server) ne '') {
19574:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
19575:                     push(@okoffloadoth,$server);
19576:                 }
19577:             }
19578:         }
19579:         if (@okoffloadoth) {
19580:             foreach my $lonhost (@okoffloadoth) {
19581:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
19582:             }
19583:         }
19584:     }
19585:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
19586:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
19587:             if (ref($changes{'spares'}) eq 'HASH') {
19588:                 if (keys(%{$changes{'spares'}}) > 0) {
19589:                     $savespares = 1;
19590:                 }
19591:             }
19592:         } else {
19593:             $savespares = 1;
19594:         }
19595:         foreach my $offload ('offloadnow','offloadoth') {
19596:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
19597:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
19598:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
19599:                         $changes{$offload} = 1;
19600:                         last;
19601:                     }
19602:                 }
19603:                 unless ($changes{$offload}) {
19604:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
19605:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
19606:                             $changes{$offload} = 1;
19607:                             last;
19608:                         }
19609:                     }
19610:                 }
19611:             } else {
19612:                 if (($offload eq 'offloadnow') && (@okoffload)) {
19613:                      $changes{'offloadnow'} = 1;
19614:                 }
19615:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
19616:                     $changes{'offloadoth'} = 1;
19617:                 }
19618:             }
19619:         }
19620:     } else {
19621:         if (@okoffload) {
19622:             $changes{'offloadnow'} = 1;
19623:         }
19624:         if (@okoffloadoth) {
19625:             $changes{'offloadoth'} = 1;
19626:         }
19627:     }
19628:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
19629:     if ((keys(%changes) > 0) || ($savespares)) {
19630:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
19631:                                                  $dom);
19632:         if ($putresult eq 'ok') {
19633:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
19634:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
19635:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
19636:                 }
19637:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
19638:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
19639:                 }
19640:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
19641:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
19642:                 }
19643:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
19644:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
19645:                 }
19646:             }
19647:             my $cachetime = 24*60*60;
19648:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19649:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
19650:             if (ref($lastactref) eq 'HASH') {
19651:                 $lastactref->{'domdefaults'} = 1;
19652:                 $lastactref->{'usersessions'} = 1;
19653:             }
19654:             if (keys(%changes) > 0) {
19655:                 my %lt = &usersession_titles();
19656:                 $resulttext = &mt('Changes made:').'<ul>';
19657:                 foreach my $prefix (@prefixes) {
19658:                     if (ref($changes{$prefix}) eq 'HASH') {
19659:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
19660:                         if ($prefix eq 'spares') {
19661:                             if (ref($changes{$prefix}) eq 'HASH') {
19662:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
19663:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
19664:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
19665:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
19666:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
19667:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
19668:                                         foreach my $type (@{$types{$prefix}}) {
19669:                                             if ($changes{$prefix}{$lonhost}{$type}) {
19670:                                                 my $offloadto = &mt('None');
19671:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
19672:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
19673:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
19674:                                                     }
19675:                                                 }
19676:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
19677:                                             }
19678:                                         }
19679:                                     }
19680:                                     $resulttext .= '</li>';
19681:                                 }
19682:                             }
19683:                         } else {
19684:                             foreach my $type (@{$types{$prefix}}) {
19685:                                 if (defined($changes{$prefix}{$type})) {
19686:                                     my $newvalue;
19687:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
19688:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
19689:                                             if ($type eq 'version') {
19690:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
19691:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
19692:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
19693:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
19694:                                                 }
19695:                                             }
19696:                                         }
19697:                                     }
19698:                                     if ($newvalue eq '') {
19699:                                         if ($type eq 'version') {
19700:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
19701:                                         } else {
19702:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
19703:                                         }
19704:                                     } else {
19705:                                         if ($type eq 'version') {
19706:                                             $newvalue .= ' '.&mt('(or later)');
19707:                                         }
19708:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
19709:                                     }
19710:                                 }
19711:                             }
19712:                         }
19713:                         $resulttext .= '</ul>';
19714:                     }
19715:                 }
19716:                 if ($changes{'offloadnow'}) {
19717:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
19718:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
19719:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
19720:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
19721:                                 $resulttext .= '<li>'.$lonhost.'</li>';
19722:                             }
19723:                             $resulttext .= '</ul>';
19724:                         } else {
19725:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
19726:                         }
19727:                     } else {
19728:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
19729:                     }
19730:                 }
19731:                 if ($changes{'offloadoth'}) {
19732:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
19733:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
19734:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
19735:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
19736:                                 $resulttext .= '<li>'.$lonhost.'</li>';
19737:                             }
19738:                             $resulttext .= '</ul>';
19739:                         } else {
19740:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
19741:                         }
19742:                     } else {
19743:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
19744:                     }
19745:                 }
19746:                 $resulttext .= '</ul>';
19747:             } else {
19748:                 $resulttext = $nochgmsg;
19749:             }
19750:         } else {
19751:             $resulttext = '<span class="LC_error">'.
19752:                           &mt('An error occurred: [_1]',$putresult).'</span>';
19753:         }
19754:     } else {
19755:         $resulttext = $nochgmsg;
19756:     }
19757:     return $resulttext;
19758: }
19759: 
19760: sub modify_loadbalancing {
19761:     my ($dom,%domconfig) = @_;
19762:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
19763:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
19764:     my ($othertitle,$usertypes,$types) =
19765:         &Apache::loncommon::sorted_inst_types($dom);
19766:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19767:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
19768:     my @sparestypes = ('primary','default');
19769:     my %typetitles = &sparestype_titles();
19770:     my $resulttext;
19771:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
19772:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
19773:         %existing = %{$domconfig{'loadbalancing'}};
19774:     }
19775:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
19776:                               \%currtargets,\%currrules,\%currcookies);
19777:     my ($saveloadbalancing,%defaultshash,%changes);
19778:     my ($alltypes,$othertypes,$titles) =
19779:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
19780:     my %ruletitles = &offloadtype_text();
19781:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
19782:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
19783:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
19784:         if ($balancer eq '') {
19785:             next;
19786:         }
19787:         if (!exists($servers{$balancer})) {
19788:             if (exists($currbalancer{$balancer})) {
19789:                 push(@{$changes{'delete'}},$balancer);
19790:             }
19791:             next;
19792:         }
19793:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
19794:             push(@{$changes{'delete'}},$balancer);
19795:             next;
19796:         }
19797:         if (!exists($currbalancer{$balancer})) {
19798:             push(@{$changes{'add'}},$balancer);
19799:         }
19800:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
19801:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
19802:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
19803:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
19804:             $saveloadbalancing = 1;
19805:         }
19806:         foreach my $sparetype (@sparestypes) {
19807:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
19808:             my @offloadto;
19809:             foreach my $target (@targets) {
19810:                 if (($servers{$target}) && ($target ne $balancer)) {
19811:                     if ($sparetype eq 'default') {
19812:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
19813:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
19814:                         }
19815:                     }
19816:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
19817:                         push(@offloadto,$target);
19818:                     }
19819:                 }
19820:             }
19821:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
19822:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
19823:                     push(@offloadto,$balancer);
19824:                 }
19825:             }
19826:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
19827:         }
19828:         if ($env{'form.loadbalancing_cookie_'.$i}) {
19829:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
19830:             if (exists($currbalancer{$balancer})) {
19831:                 unless ($currcookies{$balancer}) {
19832:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
19833:                 }
19834:             }
19835:         } elsif (exists($currbalancer{$balancer})) {
19836:             if ($currcookies{$balancer}) {
19837:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
19838:             }
19839:         }
19840:         if (ref($currtargets{$balancer}) eq 'HASH') {
19841:             foreach my $sparetype (@sparestypes) {
19842:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
19843:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
19844:                     if (@targetdiffs > 0) {
19845:                         $changes{'curr'}{$balancer}{'targets'} = 1;
19846:                     }
19847:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
19848:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
19849:                         $changes{'curr'}{$balancer}{'targets'} = 1;
19850:                     }
19851:                 }
19852:             }
19853:         } else {
19854:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
19855:                 foreach my $sparetype (@sparestypes) {
19856:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
19857:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
19858:                             $changes{'curr'}{$balancer}{'targets'} = 1;
19859:                         }
19860:                     }
19861:                 }
19862:             }
19863:         }
19864:         my $ishomedom;
19865:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
19866:             $ishomedom = 1;
19867:         }
19868:         if (ref($alltypes) eq 'ARRAY') {
19869:             foreach my $type (@{$alltypes}) {
19870:                 my $rule;
19871:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
19872:                          (!$ishomedom)) {
19873:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
19874:                 }
19875:                 if ($rule eq 'specific') {
19876:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
19877:                     if (exists($servers{$specifiedhost})) {
19878:                         $rule = $specifiedhost;
19879:                     }
19880:                 }
19881:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
19882:                 if (ref($currrules{$balancer}) eq 'HASH') {
19883:                     if ($rule ne $currrules{$balancer}{$type}) {
19884:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
19885:                     }
19886:                 } elsif ($rule ne '') {
19887:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
19888:                 }
19889:             }
19890:         }
19891:     }
19892:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
19893:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
19894:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
19895:             $defaultshash{'loadbalancing'} = {};
19896:         }
19897:         my $putresult = &Apache::lonnet::put_dom('configuration',
19898:                                                  \%defaultshash,$dom);
19899:         if ($putresult eq 'ok') {
19900:             if (keys(%changes) > 0) {
19901:                 my %toupdate;
19902:                 if (ref($changes{'delete'}) eq 'ARRAY') {
19903:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
19904:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
19905:                         $toupdate{$balancer} = 1;
19906:                     }
19907:                 }
19908:                 if (ref($changes{'add'}) eq 'ARRAY') {
19909:                     foreach my $balancer (sort(@{$changes{'add'}})) {
19910:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
19911:                         $toupdate{$balancer} = 1;
19912:                     }
19913:                 }
19914:                 if (ref($changes{'curr'}) eq 'HASH') {
19915:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
19916:                         $toupdate{$balancer} = 1;
19917:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
19918:                             if ($changes{'curr'}{$balancer}{'targets'}) {
19919:                                 my %offloadstr;
19920:                                 foreach my $sparetype (@sparestypes) {
19921:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
19922:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
19923:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
19924:                                         }
19925:                                     }
19926:                                 }
19927:                                 if (keys(%offloadstr) == 0) {
19928:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
19929:                                 } else {
19930:                                     my $showoffload;
19931:                                     foreach my $sparetype (@sparestypes) {
19932:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
19933:                                         if (defined($offloadstr{$sparetype})) {
19934:                                             $showoffload .= $offloadstr{$sparetype};
19935:                                         } else {
19936:                                             $showoffload .= &mt('None');
19937:                                         }
19938:                                         $showoffload .= ('&nbsp;'x3);
19939:                                     }
19940:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
19941:                                 }
19942:                             }
19943:                         }
19944:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
19945:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
19946:                                 foreach my $type (@{$alltypes}) {
19947:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
19948:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
19949:                                         my $balancetext;
19950:                                         if ($rule eq '') {
19951:                                             $balancetext =  $ruletitles{'default'};
19952:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
19953:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
19954:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
19955:                                                 foreach my $sparetype (@sparestypes) {
19956:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
19957:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
19958:                                                     }
19959:                                                 }
19960:                                                 foreach my $item (@{$alltypes}) {
19961:                                                     next if ($item =~  /^_LC_ipchange/);
19962:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
19963:                                                     if ($hasrule eq 'homeserver') {
19964:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
19965:                                                     } else {
19966:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
19967:                                                             if ($servers{$hasrule}) {
19968:                                                                 $toupdate{$hasrule} = 1;
19969:                                                             }
19970:                                                         }
19971:                                                     }
19972:                                                 }
19973:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
19974:                                                     $balancetext =  $ruletitles{$rule};
19975:                                                 } else {
19976:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
19977:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
19978:                                                     if ($receiver) {
19979:                                                         $toupdate{$receiver};
19980:                                                     }
19981:                                                 }
19982:                                             } else {
19983:                                                 $balancetext =  $ruletitles{$rule};
19984:                                             }
19985:                                         } else {
19986:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
19987:                                         }
19988:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
19989:                                     }
19990:                                 }
19991:                             }
19992:                         }
19993:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
19994:                             if ($currcookies{$balancer}) {
19995:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
19996:                                                           $balancer).'</li>';
19997:                             } else {
19998:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
19999:                                                           $balancer).'</li>';
20000:                             }
20001:                         }
20002:                     }
20003:                 }
20004:                 if (keys(%toupdate)) {
20005:                     my %thismachine;
20006:                     my $updatedhere;
20007:                     my $cachetime = 60*60*24;
20008:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
20009:                     foreach my $lonhost (keys(%toupdate)) {
20010:                         if ($thismachine{$lonhost}) {
20011:                             unless ($updatedhere) {
20012:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
20013:                                                               $defaultshash{'loadbalancing'},
20014:                                                               $cachetime);
20015:                                 $updatedhere = 1;
20016:                             }
20017:                         } else {
20018:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
20019:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
20020:                         }
20021:                     }
20022:                 }
20023:                 if ($resulttext ne '') {
20024:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
20025:                 } else {
20026:                     $resulttext = $nochgmsg;
20027:                 }
20028:             } else {
20029:                 $resulttext = $nochgmsg;
20030:             }
20031:         } else {
20032:             $resulttext = '<span class="LC_error">'.
20033:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20034:         }
20035:     } else {
20036:         $resulttext = $nochgmsg;
20037:     }
20038:     return $resulttext;
20039: }
20040: 
20041: sub recurse_check {
20042:     my ($chkcats,$categories,$depth,$name) = @_;
20043:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
20044:         my $chg = 0;
20045:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
20046:             my $category = $chkcats->[$depth]{$name}[$j];
20047:             my $item;
20048:             if ($category eq '') {
20049:                 $chg ++;
20050:             } else {
20051:                 my $deeper = $depth + 1;
20052:                 $item = &escape($category).':'.&escape($name).':'.$depth;
20053:                 if ($chg) {
20054:                     $categories->{$item} -= $chg;
20055:                 }
20056:                 &recurse_check($chkcats,$categories,$deeper,$category);
20057:                 $deeper --;
20058:             }
20059:         }
20060:     }
20061:     return;
20062: }
20063: 
20064: sub recurse_cat_deletes {
20065:     my ($item,$coursecategories,$deletions) = @_;
20066:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
20067:     my $subdepth = $depth + 1;
20068:     if (ref($coursecategories) eq 'HASH') {
20069:         foreach my $subitem (keys(%{$coursecategories})) {
20070:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
20071:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
20072:                 delete($coursecategories->{$subitem});
20073:                 $deletions->{$subitem} = 1;
20074:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
20075:             }
20076:         }
20077:     }
20078:     return;
20079: }
20080: 
20081: sub active_dc_picker {
20082:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
20083:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
20084:     my @domcoord = keys(%domcoords);
20085:     if (keys(%currhash)) {
20086:         foreach my $dc (keys(%currhash)) {
20087:             unless (exists($domcoords{$dc})) {
20088:                 push(@domcoord,$dc);
20089:             }
20090:         }
20091:     }
20092:     @domcoord = sort(@domcoord);
20093:     my $numdcs = scalar(@domcoord);
20094:     my $rows = 0;
20095:     my $table;
20096:     if ($numdcs > 1) {
20097:         $table = '<table>';
20098:         for (my $i=0; $i<@domcoord; $i++) {
20099:             my $rem = $i%($numinrow);
20100:             if ($rem == 0) {
20101:                 if ($i > 0) {
20102:                     $table .= '</tr>';
20103:                 }
20104:                 $table .= '<tr>';
20105:                 $rows ++;
20106:             }
20107:             my $check = '';
20108:             if ($inputtype eq 'radio') {
20109:                 if (keys(%currhash) == 0) {
20110:                     if (!$i) {
20111:                         $check = ' checked="checked"';
20112:                     }
20113:                 } elsif (exists($currhash{$domcoord[$i]})) {
20114:                     $check = ' checked="checked"';
20115:                 }
20116:             } else {
20117:                 if (exists($currhash{$domcoord[$i]})) {
20118:                     $check = ' checked="checked"';
20119:                 }
20120:             }
20121:             if ($i == @domcoord - 1) {
20122:                 my $colsleft = $numinrow - $rem;
20123:                 if ($colsleft > 1) {
20124:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
20125:                 } else {
20126:                     $table .= '<td class="LC_left_item">';
20127:                 }
20128:             } else {
20129:                 $table .= '<td class="LC_left_item">';
20130:             }
20131:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
20132:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
20133:             $table .= '<span class="LC_nobreak"><label>'.
20134:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
20135:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
20136:             if ($user ne $dcname.':'.$dcdom) {
20137:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
20138:             }
20139:             $table .= '</label></span></td>';
20140:         }
20141:         $table .= '</tr></table>';
20142:     } elsif ($numdcs == 1) {
20143:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
20144:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
20145:         if ($inputtype eq 'radio') {
20146:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
20147:             if ($user ne $dcname.':'.$dcdom) {
20148:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
20149:             }
20150:         } else {
20151:             my $check;
20152:             if (exists($currhash{$domcoord[0]})) {
20153:                 $check = ' checked="checked"';
20154:             }
20155:             $table = '<span class="LC_nobreak"><label>'.
20156:                      '<input type="checkbox" name="'.$name.'" '.
20157:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
20158:             if ($user ne $dcname.':'.$dcdom) {
20159:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
20160:             }
20161:             $table .= '</label></span>';
20162:             $rows ++;
20163:         }
20164:     }
20165:     return ($numdcs,$table,$rows);
20166: }
20167: 
20168: sub usersession_titles {
20169:     return &Apache::lonlocal::texthash(
20170:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
20171:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
20172:                spares => 'Servers offloaded to, when busy',
20173:                version => 'LON-CAPA version requirement',
20174:                excludedomain => 'Allow all, but exclude specific domains',
20175:                includedomain => 'Deny all, but include specific domains',
20176:                primary => 'Primary (checked first)',
20177:                default => 'Default',
20178:            );
20179: }
20180: 
20181: sub id_for_thisdom {
20182:     my (%servers) = @_;
20183:     my %altids;
20184:     foreach my $server (keys(%servers)) {
20185:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
20186:         if ($serverhome ne $server) {
20187:             $altids{$serverhome} = $server;
20188:         }
20189:     }
20190:     return %altids;
20191: }
20192: 
20193: sub count_servers {
20194:     my ($currbalancer,%servers) = @_;
20195:     my (@spares,$numspares);
20196:     foreach my $lonhost (sort(keys(%servers))) {
20197:         next if ($currbalancer eq $lonhost);
20198:         push(@spares,$lonhost);
20199:     }
20200:     if ($currbalancer) {
20201:         $numspares = scalar(@spares);
20202:     } else {
20203:         $numspares = scalar(@spares) - 1;
20204:     }
20205:     return ($numspares,@spares);
20206: }
20207: 
20208: sub lonbalance_targets_js {
20209:     my ($dom,$types,$servers,$settings) = @_;
20210:     my $select = &mt('Select');
20211:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
20212:     if (ref($servers) eq 'HASH') {
20213:         $alltargets = join("','",sort(keys(%{$servers})));
20214:         my @homedoms;
20215:         foreach my $server (sort(keys(%{$servers}))) {
20216:             if (&Apache::lonnet::host_domain($server) eq $dom) {
20217:                 push(@homedoms,'1');
20218:             } else {
20219:                 push(@homedoms,'0');
20220:             }
20221:         }
20222:         $allishome = join("','",@homedoms);
20223:     }
20224:     if (ref($types) eq 'ARRAY') {
20225:         if (@{$types} > 0) {
20226:             @alltypes = @{$types};
20227:         }
20228:     }
20229:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
20230:     $allinsttypes = join("','",@alltypes);
20231:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
20232:     if (ref($settings) eq 'HASH') {
20233:         %existing = %{$settings};
20234:     }
20235:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
20236:                               \%currtargets,\%currrules,\%currcookies);
20237:     my $balancers = join("','",sort(keys(%currbalancer)));
20238:     return <<"END";
20239: 
20240: <script type="text/javascript">
20241: // <![CDATA[
20242: 
20243: currBalancers = new Array('$balancers');
20244: 
20245: function toggleTargets(balnum) {
20246:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
20247:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
20248:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
20249:     var prevbalancer = prevhostitem.value;
20250:     var baltotal = document.getElementById('loadbalancing_total').value;
20251:     prevhostitem.value = balancer;
20252:     if (prevbalancer != '') {
20253:         var prevIdx = currBalancers.indexOf(prevbalancer);
20254:         if (prevIdx != -1) {
20255:             currBalancers.splice(prevIdx,1);
20256:         }
20257:     }
20258:     if (balancer == '') {
20259:         hideSpares(balnum);
20260:     } else {
20261:         var currIdx = currBalancers.indexOf(balancer);
20262:         if (currIdx == -1) {
20263:             currBalancers.push(balancer);
20264:         }
20265:         var homedoms = new Array('$allishome');
20266:         var ishomedom = homedoms[lonhostitem.selectedIndex];
20267:         showSpares(balancer,ishomedom,balnum);
20268:     }
20269:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
20270:     return;
20271: }
20272: 
20273: function showSpares(balancer,ishomedom,balnum) {
20274:     var alltargets = new Array('$alltargets');
20275:     var insttypes = new Array('$allinsttypes');
20276:     var offloadtypes = new Array('primary','default');
20277: 
20278:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
20279:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
20280:  
20281:     for (var i=0; i<offloadtypes.length; i++) {
20282:         var count = 0;
20283:         for (var j=0; j<alltargets.length; j++) {
20284:             if (alltargets[j] != balancer) {
20285:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
20286:                 item.value = alltargets[j];
20287:                 item.style.textAlign='left';
20288:                 item.style.textFace='normal';
20289:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
20290:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
20291:                     item.disabled = '';
20292:                 } else {
20293:                     item.disabled = 'disabled';
20294:                     item.checked = false;
20295:                 }
20296:                 count ++;
20297:             }
20298:         }
20299:     }
20300:     for (var k=0; k<insttypes.length; k++) {
20301:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
20302:             if (ishomedom == 1) {
20303:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
20304:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
20305:             } else {
20306:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
20307:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
20308:             }
20309:         } else {
20310:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
20311:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
20312:         }
20313:         if ((insttypes[k] != '_LC_external') && 
20314:             ((insttypes[k] != '_LC_internetdom') ||
20315:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
20316:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
20317:             item.options.length = 0;
20318:             item.options[0] = new Option("","",true,true);
20319:             var idx = 0;
20320:             for (var m=0; m<alltargets.length; m++) {
20321:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
20322:                     idx ++;
20323:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
20324:                 }
20325:             }
20326:         }
20327:     }
20328:     return;
20329: }
20330: 
20331: function hideSpares(balnum) {
20332:     var alltargets = new Array('$alltargets');
20333:     var insttypes = new Array('$allinsttypes');
20334:     var offloadtypes = new Array('primary','default');
20335: 
20336:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
20337:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
20338: 
20339:     var total = alltargets.length - 1;
20340:     for (var i=0; i<offloadtypes; i++) {
20341:         for (var j=0; j<total; j++) {
20342:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
20343:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
20344:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
20345:         }
20346:     }
20347:     for (var k=0; k<insttypes.length; k++) {
20348:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
20349:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
20350:         if (insttypes[k] != '_LC_external') {
20351:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
20352:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
20353:         }
20354:     }
20355:     return;
20356: }
20357: 
20358: function checkOffloads(item,balnum,type) {
20359:     var alltargets = new Array('$alltargets');
20360:     var offloadtypes = new Array('primary','default');
20361:     if (item.checked) {
20362:         var total = alltargets.length - 1;
20363:         var other;
20364:         if (type == offloadtypes[0]) {
20365:             other = offloadtypes[1];
20366:         } else {
20367:             other = offloadtypes[0];
20368:         }
20369:         for (var i=0; i<total; i++) {
20370:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
20371:             if (server == item.value) {
20372:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
20373:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
20374:                 }
20375:             }
20376:         }
20377:     }
20378:     return;
20379: }
20380: 
20381: function singleServerToggle(balnum,type) {
20382:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
20383:     if (offloadtoSelIdx == 0) {
20384:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
20385:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
20386: 
20387:     } else {
20388:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
20389:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
20390:     }
20391:     return;
20392: }
20393: 
20394: function balanceruleChange(formname,balnum,type) {
20395:     if (type == '_LC_external') {
20396:         return;
20397:     }
20398:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
20399:     for (var i=0; i<typesRules.length; i++) {
20400:         if (formname.elements[typesRules[i]].checked) {
20401:             if (formname.elements[typesRules[i]].value != 'specific') {
20402:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
20403:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
20404:             } else {
20405:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
20406:             }
20407:         }
20408:     }
20409:     return;
20410: }
20411: 
20412: function balancerDeleteChange(balnum) {
20413:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
20414:     var baltotal = document.getElementById('loadbalancing_total').value;
20415:     var addtarget;
20416:     var removetarget;
20417:     var action = 'delete';
20418:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
20419:         var lonhost = hostitem.value;
20420:         var currIdx = currBalancers.indexOf(lonhost);
20421:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
20422:             if (currIdx != -1) {
20423:                 currBalancers.splice(currIdx,1);
20424:             }
20425:             addtarget = lonhost;
20426:         } else {
20427:             if (currIdx == -1) {
20428:                 currBalancers.push(lonhost);
20429:             }
20430:             removetarget = lonhost;
20431:             action = 'undelete';
20432:         }
20433:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
20434:     }
20435:     return;
20436: }
20437: 
20438: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
20439:     if (baltotal > 1) {
20440:         var offloadtypes = new Array('primary','default');
20441:         var alltargets = new Array('$alltargets');
20442:         var insttypes = new Array('$allinsttypes');
20443:         for (var i=0; i<baltotal; i++) {
20444:             if (i != balnum) {
20445:                 for (var j=0; j<offloadtypes.length; j++) {
20446:                     var total = alltargets.length - 1;
20447:                     for (var k=0; k<total; k++) {
20448:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
20449:                         var server = serveritem.value;
20450:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
20451:                             if (server == addtarget) {
20452:                                 serveritem.disabled = '';
20453:                             }
20454:                         }
20455:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
20456:                             if (server == removetarget) {
20457:                                 serveritem.disabled = 'disabled';
20458:                                 serveritem.checked = false;
20459:                             }
20460:                         }
20461:                     }
20462:                 }
20463:                 for (var j=0; j<insttypes.length; j++) {
20464:                     if (insttypes[j] != '_LC_external') {
20465:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
20466:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
20467:                             var currSel = singleserver.selectedIndex;
20468:                             var currVal = singleserver.options[currSel].value;
20469:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
20470:                                 var numoptions = singleserver.options.length;
20471:                                 var needsnew = 1;
20472:                                 for (var k=0; k<numoptions; k++) {
20473:                                     if (singleserver.options[k] == addtarget) {
20474:                                         needsnew = 0;
20475:                                         break;
20476:                                     }
20477:                                 }
20478:                                 if (needsnew == 1) {
20479:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
20480:                                 }
20481:                             }
20482:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
20483:                                 singleserver.options.length = 0;
20484:                                 if ((currVal) && (currVal != removetarget)) {
20485:                                     singleserver.options[0] = new Option("","",false,false);
20486:                                 } else {
20487:                                     singleserver.options[0] = new Option("","",true,true);
20488:                                 }
20489:                                 var idx = 0;
20490:                                 for (var m=0; m<alltargets.length; m++) {
20491:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
20492:                                         idx ++;
20493:                                         if (currVal == alltargets[m]) {
20494:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
20495:                                         } else {
20496:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
20497:                                         }
20498:                                     }
20499:                                 }
20500:                             }
20501:                         }
20502:                     }
20503:                 }
20504:             }
20505:         }
20506:     }
20507:     return;
20508: }
20509: 
20510: // ]]>
20511: </script>
20512: 
20513: END
20514: }
20515: 
20516: sub new_spares_js {
20517:     my @sparestypes = ('primary','default');
20518:     my $types = join("','",@sparestypes);
20519:     my $select = &mt('Select');
20520:     return <<"END";
20521: 
20522: <script type="text/javascript">
20523: // <![CDATA[
20524: 
20525: function updateNewSpares(formname,lonhost) {
20526:     var types = new Array('$types');
20527:     var include = new Array();
20528:     var exclude = new Array();
20529:     for (var i=0; i<types.length; i++) {
20530:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
20531:         for (var j=0; j<spareboxes.length; j++) {
20532:             if (formname.elements[spareboxes[j]].checked) {
20533:                 exclude.push(formname.elements[spareboxes[j]].value);
20534:             } else {
20535:                 include.push(formname.elements[spareboxes[j]].value);
20536:             }
20537:         }
20538:     }
20539:     for (var i=0; i<types.length; i++) {
20540:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
20541:         var selIdx = newSpare.selectedIndex;
20542:         var currnew = newSpare.options[selIdx].value;
20543:         var okSpares = new Array();
20544:         for (var j=0; j<newSpare.options.length; j++) {
20545:             var possible = newSpare.options[j].value;
20546:             if (possible != '') {
20547:                 if (exclude.indexOf(possible) == -1) {
20548:                     okSpares.push(possible);
20549:                 } else {
20550:                     if (currnew == possible) {
20551:                         selIdx = 0;
20552:                     }
20553:                 }
20554:             }
20555:         }
20556:         for (var k=0; k<include.length; k++) {
20557:             if (okSpares.indexOf(include[k]) == -1) {
20558:                 okSpares.push(include[k]);
20559:             }
20560:         }
20561:         okSpares.sort();
20562:         newSpare.options.length = 0;
20563:         if (selIdx == 0) {
20564:             newSpare.options[0] = new Option("$select","",true,true);
20565:         } else {
20566:             newSpare.options[0] = new Option("$select","",false,false);
20567:         }
20568:         for (var m=0; m<okSpares.length; m++) {
20569:             var idx = m+1;
20570:             var selThis = 0;
20571:             if (selIdx != 0) {
20572:                 if (okSpares[m] == currnew) {
20573:                     selThis = 1;
20574:                 }
20575:             }
20576:             if (selThis == 1) {
20577:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
20578:             } else {
20579:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
20580:             }
20581:         }
20582:     }
20583:     return;
20584: }
20585: 
20586: function checkNewSpares(lonhost,type) {
20587:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
20588:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
20589:     if (chosen != '') {
20590:         var othertype;
20591:         var othernewSpare;
20592:         if (type == 'primary') {
20593:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
20594:         }
20595:         if (type == 'default') {
20596:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
20597:         }
20598:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
20599:             othernewSpare.selectedIndex = 0;
20600:         }
20601:     }
20602:     return;
20603: }
20604: 
20605: // ]]>
20606: </script>
20607: 
20608: END
20609: 
20610: }
20611: 
20612: sub common_domprefs_js {
20613:     return <<"END";
20614: 
20615: <script type="text/javascript">
20616: // <![CDATA[
20617: 
20618: function getIndicesByName(formname,item) {
20619:     var group = new Array();
20620:     for (var i=0;i<formname.elements.length;i++) {
20621:         if (formname.elements[i].name == item) {
20622:             group.push(formname.elements[i].id);
20623:         }
20624:     }
20625:     return group;
20626: }
20627: 
20628: // ]]>
20629: </script>
20630: 
20631: END
20632: 
20633: }
20634: 
20635: sub recaptcha_js {
20636:     my %lt = &captcha_phrases();
20637:     return <<"END";
20638: 
20639: <script type="text/javascript">
20640: // <![CDATA[
20641: 
20642: function updateCaptcha(caller,context) {
20643:     var privitem;
20644:     var pubitem;
20645:     var privtext;
20646:     var pubtext;
20647:     var versionitem;
20648:     var versiontext;
20649:     if (document.getElementById(context+'_recaptchapub')) {
20650:         pubitem = document.getElementById(context+'_recaptchapub');
20651:     } else {
20652:         return;
20653:     }
20654:     if (document.getElementById(context+'_recaptchapriv')) {
20655:         privitem = document.getElementById(context+'_recaptchapriv');
20656:     } else {
20657:         return;
20658:     }
20659:     if (document.getElementById(context+'_recaptchapubtxt')) {
20660:         pubtext = document.getElementById(context+'_recaptchapubtxt');
20661:     } else {
20662:         return;
20663:     }
20664:     if (document.getElementById(context+'_recaptchaprivtxt')) {
20665:         privtext = document.getElementById(context+'_recaptchaprivtxt');
20666:     } else {
20667:         return;
20668:     }
20669:     if (document.getElementById(context+'_recaptchaversion')) {
20670:         versionitem = document.getElementById(context+'_recaptchaversion');
20671:     } else {
20672:         return;
20673:     }
20674:     if (document.getElementById(context+'_recaptchavertxt')) {
20675:         versiontext = document.getElementById(context+'_recaptchavertxt');
20676:     } else {
20677:         return;
20678:     }
20679:     if (caller.checked) {
20680:         if (caller.value == 'recaptcha') {
20681:             pubitem.type = 'text';
20682:             privitem.type = 'text';
20683:             pubitem.size = '40';
20684:             privitem.size = '40';
20685:             pubtext.innerHTML = "$lt{'pub'}";
20686:             privtext.innerHTML = "$lt{'priv'}";
20687:             versionitem.type = 'text';
20688:             versionitem.size = '3';
20689:             versiontext.innerHTML = "$lt{'ver'}";
20690:         } else {
20691:             pubitem.type = 'hidden';
20692:             privitem.type = 'hidden';
20693:             versionitem.type = 'hidden';
20694:             pubtext.innerHTML = '';
20695:             privtext.innerHTML = '';
20696:             versiontext.innerHTML = '';
20697:         }
20698:     }
20699:     return;
20700: }
20701: 
20702: // ]]>
20703: </script>
20704: 
20705: END
20706: 
20707: }
20708: 
20709: sub toggle_display_js {
20710:     return <<"END";
20711: 
20712: <script type="text/javascript">
20713: // <![CDATA[
20714: 
20715: function toggleDisplay(domForm,caller) {
20716:     if (document.getElementById(caller)) {
20717:         var divitem = document.getElementById(caller);
20718:         var optionsElement = domForm.coursecredits;
20719:         var checkval = 1;
20720:         var dispval = 'block';
20721:         var selfcreateRegExp = /^cancreate_emailverified/;
20722:         if (caller == 'emailoptions') {
20723:             optionsElement = domForm.cancreate_email;
20724:         }
20725:         if (caller == 'studentsubmission') {
20726:             optionsElement = domForm.postsubmit;
20727:         }
20728:         if (caller == 'cloneinstcode') {
20729:             optionsElement = domForm.canclone;
20730:             checkval = 'instcode';
20731:         }
20732:         if (selfcreateRegExp.test(caller)) {
20733:             optionsElement = domForm.elements[caller];
20734:             checkval = 'other';
20735:             dispval = 'inline'
20736:         }
20737:         if (optionsElement.length) {
20738:             var currval;
20739:             for (var i=0; i<optionsElement.length; i++) {
20740:                 if (optionsElement[i].checked) {
20741:                    currval = optionsElement[i].value;
20742:                 }
20743:             }
20744:             if (currval == checkval) {
20745:                 divitem.style.display = dispval;
20746:             } else {
20747:                 divitem.style.display = 'none';
20748:             }
20749:         }
20750:     }
20751:     return;
20752: }
20753: 
20754: // ]]>
20755: </script>
20756: 
20757: END
20758: 
20759: }
20760: 
20761: sub captcha_phrases {
20762:     return &Apache::lonlocal::texthash (
20763:                  priv => 'Private key',
20764:                  pub  => 'Public key',
20765:                  original  => 'original (CAPTCHA)',
20766:                  recaptcha => 'successor (ReCAPTCHA)',
20767:                  notused   => 'unused',
20768:                  ver => 'ReCAPTCHA version (1 or 2)',
20769:     );
20770: }
20771: 
20772: sub devalidate_remote_domconfs {
20773:     my ($dom,$cachekeys) = @_;
20774:     return unless (ref($cachekeys) eq 'HASH');
20775:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20776:     my %thismachine;
20777:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
20778:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
20779:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
20780:                       'ipaccess');
20781:     my %cache_by_lonhost;
20782:     if (exists($cachekeys->{'samllanding'})) {
20783:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
20784:             my %landing = %{$cachekeys->{'samllanding'}};
20785:             my %domservers = &Apache::lonnet::get_servers($dom);
20786:             if (keys(%domservers)) {
20787:                 foreach my $server (keys(%domservers)) {
20788:                     my @cached;
20789:                     next if ($thismachine{$server});
20790:                     if ($landing{$server}) {
20791:                         push(@cached,&escape('samllanding').':'.&escape($server));
20792:                     }
20793:                     if (@cached) {
20794:                         $cache_by_lonhost{$server} = \@cached;
20795:                     }
20796:                 }
20797:             }
20798:         }
20799:     }
20800:     if (keys(%servers)) {
20801:         foreach my $server (keys(%servers)) {
20802:             next if ($thismachine{$server});
20803:             my @cached;
20804:             foreach my $name (@posscached) {
20805:                 if ($cachekeys->{$name}) {
20806:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
20807:                         if (ref($cachekeys->{$name}) eq 'HASH') {
20808:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
20809:                                 push(@cached,&escape($name).':'.&escape($key));
20810:                             }
20811:                         }
20812:                     } else {
20813:                         push(@cached,&escape($name).':'.&escape($dom));
20814:                     }
20815:                 }
20816:             }
20817:             if ((exists($cache_by_lonhost{$server})) &&
20818:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
20819:                 push(@cached,@{$cache_by_lonhost{$server}});
20820:             }
20821:             if (@cached) {
20822:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
20823:             }
20824:         }
20825:     }
20826:     return;
20827: }
20828: 
20829: 1;

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