File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.425: download - view: text, annotated - select for diffs
Sat Jun 3 19:18:11 2023 UTC (12 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Remove trailing white space
- Remove some lines containing only a line feed
- Fix some indents
  No code changes.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.425 2023/06/03 19:18:11 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, placement, 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 LONCAPA::SSL;
  175: use File::Copy;
  176: use Locale::Language;
  177: use DateTime::TimeZone;
  178: use DateTime::Locale;
  179: use Time::HiRes qw( sleep );
  180: use Net::CIDR;
  181: use Crypt::CBC;
  182: 
  183: my $registered_cleanup;
  184: my $modified_urls;
  185: 
  186: sub handler {
  187:     my $r=shift;
  188:     if ($r->header_only) {
  189:         &Apache::loncommon::content_type($r,'text/html');
  190:         $r->send_http_header;
  191:         return OK;
  192:     }
  193: 
  194:     my $context = 'domain';
  195:     my $dom = $env{'request.role.domain'};
  196:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  197:     if (&Apache::lonnet::allowed('mau',$dom)) {
  198:         &Apache::loncommon::content_type($r,'text/html');
  199:         $r->send_http_header;
  200:     } else {
  201:         $env{'user.error.msg'}=
  202:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  203:         return HTTP_NOT_ACCEPTABLE;
  204:     }
  205: 
  206:     $registered_cleanup=0;
  207:     @{$modified_urls}=();
  208: 
  209:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  210:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  211:                                             ['phase','actions']);
  212:     my $phase = 'pickactions';
  213:     if ( exists($env{'form.phase'}) ) {
  214:         $phase = $env{'form.phase'};
  215:     }
  216:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  217:     my %domconfig =
  218:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  219:                 'quotas','autoenroll','autoupdate','autocreate',
  220:                 'directorysrch','usercreation','usermodification',
  221:                 'contacts','defaults','scantron','coursecategories',
  222:                 'serverstatuses','requestcourses','helpsettings',
  223:                 'coursedefaults','usersessions','loadbalancing',
  224:                 'requestauthor','selfenrollment','inststatus',
  225:                 'ltitools','toolsec','ssl','trust','lti','ltisec',
  226:                 'privacy','passwords','proctoring','wafproxy','ipaccess'],$dom);
  227:     my %encconfig =
  228:         &Apache::lonnet::get_dom('encconfig',['ltitools','lti','proctoring','linkprot'],$dom,undef,1);
  229:     my ($checked_is_home,$is_home);
  230:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  231:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  232:             my $home = &Apache::lonnet::domain($dom,'primary');
  233:             unless (($home eq 'no_host') || ($home eq '')) {
  234:                 my @ids=&Apache::lonnet::current_machine_ids();
  235:                 if (grep(/^\Q$home\E$/,@ids)) {
  236:                     $is_home = 1;
  237:                 }
  238:             }
  239:             $checked_is_home = 1;
  240:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  241:                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
  242:                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
  243:                     $domconfig{'ltitools'}{$id}{'key'} = $encconfig{'ltitools'}{$id}{'key'};
  244:                     if (($is_home) && ($phase eq 'process')) {
  245:                         $domconfig{'ltitools'}{$id}{'secret'} = $encconfig{'ltitools'}{$id}{'secret'};
  246:                     }
  247:                 }
  248:             }
  249:         }
  250:     }
  251:     if (ref($domconfig{'lti'}) eq 'HASH') {
  252:         if (ref($encconfig{'lti'}) eq 'HASH') {
  253:             unless ($checked_is_home) {
  254:                 my $home = &Apache::lonnet::domain($dom,'primary');
  255:                 unless (($home eq 'no_host') || ($home eq '')) {
  256:                     my @ids=&Apache::lonnet::current_machine_ids();
  257:                     if (grep(/^\Q$home\E$/,@ids)) {
  258:                         $is_home = 1;
  259:                     }
  260:                 }
  261:                 $checked_is_home = 1;
  262:             }
  263:             foreach my $id (keys(%{$domconfig{'lti'}})) {
  264:                 if ((ref($domconfig{'lti'}{$id}) eq 'HASH') &&
  265:                     (ref($encconfig{'lti'}{$id}) eq 'HASH')) {
  266:                     $domconfig{'lti'}{$id}{'key'} = $encconfig{'lti'}{$id}{'key'};
  267:                     if (($is_home) && ($phase eq 'process')) {
  268:                         $domconfig{'lti'}{$id}{'secret'} = $encconfig{'lti'}{$id}{'secret'};
  269:                     }
  270:                 }
  271:             }
  272:         }
  273:     }
  274:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
  275:         if (ref($domconfig{'ltisec'}{'linkprot'}) eq 'HASH') {
  276:             if (ref($encconfig{'linkprot'}) eq 'HASH') {
  277:                 foreach my $id (keys(%{$domconfig{'ltisec'}{'linkprot'}})) {
  278:                     unless ($id =~ /^\d+$/) {
  279:                         delete($domconfig{'ltisec'}{'linkprot'}{$id});
  280:                     }
  281:                     if ((ref($domconfig{'ltisec'}{'linkprot'}{$id}) eq 'HASH') &&
  282:                         (ref($encconfig{'linkprot'}{$id}) eq 'HASH')) {
  283:                         foreach my $item ('key','secret') {
  284:                             $domconfig{'ltisec'}{'linkprot'}{$id}{$item} = $encconfig{'linkprot'}{$id}{$item};
  285:                         }
  286:                     }
  287:                 }
  288:             }
  289:         }
  290:     }
  291:     if (ref($domconfig{'proctoring'}) eq 'HASH') {
  292:         if (ref($encconfig{'proctoring'}) eq 'HASH') {
  293:             foreach my $provider (keys(%{$domconfig{'proctoring'}})) {
  294:                 if ((ref($domconfig{'proctoring'}{$provider}) eq 'HASH') &&
  295:                     (ref($encconfig{'proctoring'}{$provider}) eq 'HASH')) {
  296:                     foreach my $item ('key','secret') {
  297:                         $domconfig{'proctoring'}{$provider}{$item} = $encconfig{'proctoring'}{$provider}{$item};
  298:                     }
  299:                 }
  300:             }
  301:         }
  302:     }
  303:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  304:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  305:                        'contacts','privacy','usercreation','selfcreation',
  306:                        'usermodification','scantron','requestcourses','requestauthor',
  307:                        'coursecategories','serverstatuses','helpsettings','coursedefaults',
  308:                        'ltitools','proctoring','selfenrollment','usersessions','ssl',
  309:                        'trust','lti');
  310:     my %existing;
  311:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  312:         %existing = %{$domconfig{'loadbalancing'}};
  313:     }
  314:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  315:         push(@prefs_order,'loadbalancing');
  316:     }
  317:     my %prefs = (
  318:         'rolecolors' =>
  319:                    { text => 'Default color schemes',
  320:                      help => 'Domain_Configuration_Color_Schemes',
  321:                      header => [{col1 => 'Student Settings',
  322:                                  col2 => '',},
  323:                                 {col1 => 'Coordinator Settings',
  324:                                  col2 => '',},
  325:                                 {col1 => 'Author Settings',
  326:                                  col2 => '',},
  327:                                 {col1 => 'Administrator Settings',
  328:                                  col2 => '',}],
  329:                       print => \&print_rolecolors,
  330:                       modify => \&modify_rolecolors,
  331:                     },
  332:         'login' =>
  333:                     { text => 'Log-in page options',
  334:                       help => 'Domain_Configuration_Login_Page',
  335:                       header => [{col1 => 'Log-in Page Items',
  336:                                   col2 => '',},
  337:                                  {col1 => 'Log-in Help',
  338:                                   col2 => 'Value'},
  339:                                  {col1 => 'Custom HTML in document head',
  340:                                   col2 => 'Value'},
  341:                                  {col1 => 'SSO',
  342:                                   col2 => 'Dual login: SSO and non-SSO options'},
  343:                                 ],
  344:                       print => \&print_login,
  345:                       modify => \&modify_login,
  346:                     },
  347:         'defaults' => 
  348:                     { text => 'Default authentication/language/timezone/portal/types',
  349:                       help => 'Domain_Configuration_LangTZAuth',
  350:                       header => [{col1 => 'Setting',
  351:                                   col2 => 'Value'},
  352:                                  {col1 => 'Institutional user types',
  353:                                   col2 => 'Name displayed'},
  354:                                  {col1 => 'Mapping for missing usernames via standard log-in',
  355:                                   col2 => 'Rules in use'}],
  356:                       print => \&print_defaults,
  357:                       modify => \&modify_defaults,
  358:                     },
  359:         'wafproxy' =>
  360:                     { text => 'Web Application Firewall/Reverse Proxy',
  361:                       help => 'Domain_Configuration_WAF_Proxy',
  362:                       header => [{col1 => 'Domain(s)',
  363:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  364:                                  },
  365:                                  {col1 => 'Domain(s)',
  366:                                   col2 => 'WAF Configuration',}],
  367:                       print => \&print_wafproxy,
  368:                       modify => \&modify_wafproxy,
  369:                     },
  370:         'passwords' =>
  371:                     { text => 'Passwords (Internal authentication)',
  372:                       help => 'Domain_Configuration_Passwords',
  373:                       header => [{col1 => 'Resetting Forgotten Password',
  374:                                   col2 => 'Settings'},
  375:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  376:                                   col2 => 'Settings'},
  377:                                  {col1 => 'Rules for LON-CAPA Passwords',
  378:                                   col2 => 'Settings'},
  379:                                  {col1 => 'Course Owner Changing Student Passwords',
  380:                                   col2 => 'Settings'}],
  381:                       print => \&print_passwords,
  382:                       modify => \&modify_passwords,
  383:                     },
  384:         'quotas' => 
  385:                     { text => 'Blogs, personal pages/timezones, webDAV/quotas, portfolio',
  386:                       help => 'Domain_Configuration_Quotas',
  387:                       header => [{col1 => 'User affiliation',
  388:                                   col2 => 'Available tools',
  389:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  390:                       print => \&print_quotas,
  391:                       modify => \&modify_quotas,
  392:                     },
  393:         'autoenroll' =>
  394:                    { text => 'Auto-enrollment settings',
  395:                      help => 'Domain_Configuration_Auto_Enrollment',
  396:                      header => [{col1 => 'Configuration setting',
  397:                                  col2 => 'Value(s)'}],
  398:                      print => \&print_autoenroll,
  399:                      modify => \&modify_autoenroll,
  400:                    },
  401:         'autoupdate' => 
  402:                    { text => 'Auto-update settings',
  403:                      help => 'Domain_Configuration_Auto_Updates',
  404:                      header => [{col1 => 'Setting',
  405:                                  col2 => 'Value',},
  406:                                 {col1 => 'Setting',
  407:                                  col2 => 'Affiliation'},
  408:                                 {col1 => 'User population',
  409:                                  col2 => 'Updatable user data'}],
  410:                      print => \&print_autoupdate,
  411:                      modify => \&modify_autoupdate,
  412:                   },
  413:         'autocreate' => 
  414:                   { text => 'Auto-course creation settings',
  415:                      help => 'Domain_Configuration_Auto_Creation',
  416:                      header => [{col1 => 'Configuration Setting',
  417:                                  col2 => 'Value',}],
  418:                      print => \&print_autocreate,
  419:                      modify => \&modify_autocreate,
  420:                   },
  421:         'directorysrch' => 
  422:                   { text => 'Directory searches',
  423:                     help => 'Domain_Configuration_InstDirectory_Search',
  424:                     header => [{col1 => 'Institutional Directory Setting',
  425:                                 col2 => 'Value',},
  426:                                {col1 => 'LON-CAPA Directory Setting',
  427:                                 col2 => 'Value',}],
  428:                     print => \&print_directorysrch,
  429:                     modify => \&modify_directorysrch,
  430:                   },
  431:         'contacts' =>
  432:                   { text => 'E-mail addresses and helpform',
  433:                     help => 'Domain_Configuration_Contact_Info',
  434:                     header => [{col1 => 'Default e-mail addresses',
  435:                                 col2 => 'Value',},
  436:                                {col1 => 'Recipient(s) for notifications',
  437:                                 col2 => 'Value',},
  438:                                {col1 => 'Nightly status check e-mail',
  439:                                 col2 => 'Settings',},
  440:                                {col1 => 'Ask helpdesk form settings',
  441:                                 col2 => 'Value',},],
  442:                     print => \&print_contacts,
  443:                     modify => \&modify_contacts,
  444:                   },
  445:         'usercreation' => 
  446:                   { text => 'User creation',
  447:                     help => 'Domain_Configuration_User_Creation',
  448:                     header => [{col1 => 'Format rule type',
  449:                                 col2 => 'Format rules in force'},
  450:                                {col1 => 'User account creation',
  451:                                 col2 => 'Usernames which may be created',},
  452:                                {col1 => 'Context',
  453:                                 col2 => 'Assignable authentication types'}],
  454:                     print => \&print_usercreation,
  455:                     modify => \&modify_usercreation,
  456:                   },
  457:         'selfcreation' => 
  458:                   { text => 'Users self-creating accounts',
  459:                     help => 'Domain_Configuration_Self_Creation', 
  460:                     header => [{col1 => 'Self-creation with institutional username',
  461:                                 col2 => 'Enabled?'},
  462:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  463:                                 col2 => 'Information user can enter'},
  464:                                {col1 => 'Self-creation with e-mail verification',
  465:                                 col2 => 'Settings'}],
  466:                     print => \&print_selfcreation,
  467:                     modify => \&modify_selfcreation,
  468:                   },
  469:         'usermodification' =>
  470:                   { text => 'User modification',
  471:                     help => 'Domain_Configuration_User_Modification',
  472:                     header => [{col1 => 'Target user has role',
  473:                                 col2 => 'User information updatable in author context'},
  474:                                {col1 => 'Target user has role',
  475:                                 col2 => 'User information updatable in course context'}],
  476:                     print => \&print_usermodification,
  477:                     modify => \&modify_usermodification,
  478:                   },
  479:         'scantron' =>
  480:                   { text => 'Bubblesheet format',
  481:                     help => 'Domain_Configuration_Scantron_Format',
  482:                     header => [ {col1 => 'Bubblesheet format file',
  483:                                  col2 => ''},
  484:                                 {col1 => 'Bubblesheet data upload formats',
  485:                                  col2 => 'Settings'}],
  486:                     print => \&print_scantron,
  487:                     modify => \&modify_scantron,
  488:                   },
  489:         'requestcourses' => 
  490:                  {text => 'Request creation of courses',
  491:                   help => 'Domain_Configuration_Request_Courses',
  492:                   header => [{col1 => 'User affiliation',
  493:                               col2 => 'Availability/Processing of requests',},
  494:                              {col1 => 'Setting',
  495:                               col2 => 'Value'},
  496:                              {col1 => 'Available textbooks',
  497:                               col2 => ''},
  498:                              {col1 => 'Available templates',
  499:                               col2 => ''},
  500:                              {col1 => 'Validation (not official courses)',
  501:                               col2 => 'Value'},],
  502:                   print => \&print_quotas,
  503:                   modify => \&modify_quotas,
  504:                  },
  505:         'requestauthor' =>
  506:                  {text => 'Request Authoring Space',
  507:                   help => 'Domain_Configuration_Request_Author',
  508:                   header => [{col1 => 'User affiliation',
  509:                               col2 => 'Availability/Processing of requests',},
  510:                              {col1 => 'Setting',
  511:                               col2 => 'Value'}],
  512:                   print => \&print_quotas,
  513:                   modify => \&modify_quotas,
  514:                  },
  515:         'coursecategories' =>
  516:                   { text => 'Cataloging of courses/communities',
  517:                     help => 'Domain_Configuration_Cataloging_Courses',
  518:                     header => [{col1 => 'Catalog type/availability',
  519:                                 col2 => '',},
  520:                                {col1 => 'Category settings for standard catalog',
  521:                                 col2 => '',},
  522:                                {col1 => 'Categories',
  523:                                 col2 => '',
  524:                                }],
  525:                     print => \&print_coursecategories,
  526:                     modify => \&modify_coursecategories,
  527:                   },
  528:         'serverstatuses' =>
  529:                  {text   => 'Access to server status pages',
  530:                   help   => 'Domain_Configuration_Server_Status',
  531:                   header => [{col1 => 'Status Page',
  532:                               col2 => 'Other named users',
  533:                               col3 => 'Specific IPs',
  534:                             }],
  535:                   print => \&print_serverstatuses,
  536:                   modify => \&modify_serverstatuses,
  537:                  },
  538:         'helpsettings' =>
  539:                  {text   => 'Support settings',
  540:                   help   => 'Domain_Configuration_Help_Settings',
  541:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  542:                               col2 => 'Value'},
  543:                              {col1 => 'Helpdesk Roles',
  544:                               col2 => 'Settings'},],
  545:                   print  => \&print_helpsettings,
  546:                   modify => \&modify_helpsettings,
  547:                  },
  548:         'coursedefaults' => 
  549:                  {text => 'Course/Community defaults',
  550:                   help => 'Domain_Configuration_Course_Defaults',
  551:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  552:                               col2 => 'Value',},
  553:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  554:                               col2 => 'Value',},],
  555:                   print => \&print_coursedefaults,
  556:                   modify => \&modify_coursedefaults,
  557:                  },
  558:         'selfenrollment' => 
  559:                  {text   => 'Self-enrollment in Course/Community',
  560:                   help   => 'Domain_Configuration_Selfenrollment',
  561:                   header => [{col1 => 'Configuration Rights',
  562:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  563:                              {col1 => 'Defaults',
  564:                               col2 => 'Value'},
  565:                              {col1 => 'Self-enrollment validation (optional)',
  566:                               col2 => 'Value'},],
  567:                   print => \&print_selfenrollment,
  568:                   modify => \&modify_selfenrollment,
  569:                  },
  570:         'privacy' => 
  571:                  {text   => 'Availability of User Information',
  572:                   help   => 'Domain_Configuration_User_Privacy',
  573:                   header => [{col1 => 'Role assigned in different domain',
  574:                               col2 => 'Approval options'},
  575:                              {col1 => 'Role assigned in different domain to user of type',
  576:                               col2 => 'User information available in that domain'},
  577:                              {col1 => "Role assigned in user's domain",
  578:                               col2 => 'Information viewable by privileged user'},
  579:                              {col1 => "Role assigned in user's domain",
  580:                               col2 => 'Information viewable by unprivileged user'}],
  581:                   print => \&print_privacy,
  582:                   modify => \&modify_privacy,
  583:                  },
  584:         'usersessions' =>
  585:                  {text  => 'User session hosting/offloading',
  586:                   help  => 'Domain_Configuration_User_Sessions',
  587:                   header => [{col1 => 'Domain server',
  588:                               col2 => 'Servers to offload sessions to when busy'},
  589:                              {col1 => 'Hosting of users from other domains',
  590:                               col2 => 'Rules'},
  591:                              {col1 => "Hosting domain's own users elsewhere",
  592:                               col2 => 'Rules'}],
  593:                   print => \&print_usersessions,
  594:                   modify => \&modify_usersessions,
  595:                  },
  596:         'loadbalancing' =>
  597:                  {text  => 'Dedicated Load Balancer(s)',
  598:                   help  => 'Domain_Configuration_Load_Balancing',
  599:                   header => [{col1 => 'Balancers',
  600:                               col2 => 'Default destinations',
  601:                               col3 => 'User affiliation',
  602:                               col4 => 'Overrides'},
  603:                             ],
  604:                   print => \&print_loadbalancing,
  605:                   modify => \&modify_loadbalancing,
  606:                  },
  607:         'ltitools' =>
  608:                  {text => 'External Tools (LTI)',
  609:                   help => 'Domain_Configuration_LTI_Tools',
  610:                   header => [{col1 => 'Encryption of shared secrets',
  611:                               col2 => 'Settings'},
  612:                              {col1 => 'Rules for shared secrets',
  613:                               col2 => 'Settings'},
  614:                              {col1 => 'Providers',
  615:                               col2 => 'Settings',}],
  616:                   print => \&print_ltitools,
  617:                   modify => \&modify_ltitools,
  618:                  },
  619:         'proctoring' =>
  620:                  {text => 'Remote Proctoring Integration',
  621:                   help => 'Domain_Configuration_Proctoring',
  622:                   header => [{col1 => 'Name',
  623:                               col2 => 'Configuration'}],
  624:                   print => \&print_proctoring,
  625:                   modify => \&modify_proctoring,
  626:                  },
  627:         'ssl' =>
  628:                  {text  => 'LON-CAPA Network (SSL)',
  629:                   help  => 'Domain_Configuration_Network_SSL',
  630:                   header => [{col1 => 'Server',
  631:                               col2 => 'Certificate Status'},
  632:                              {col1 => 'Connections to other servers',
  633:                               col2 => 'Rules'},
  634:                              {col1 => 'Connections from other servers',
  635:                               col2 => 'Rules'},
  636:                              {col1 => "Replicating domain's published content",
  637:                               col2 => 'Rules'}],
  638:                   print => \&print_ssl,
  639:                   modify => \&modify_ssl,
  640:                  },
  641:         'trust' =>
  642:                  {text   => 'Trust Settings',
  643:                   help   => 'Domain_Configuration_Trust',
  644:                   header => [{col1 => "Access to this domain's content by others",
  645:                               col2 => 'Rules'},
  646:                              {col1 => "Access to other domain's content by this domain",
  647:                               col2 => 'Rules'},
  648:                              {col1 => "Enrollment in this domain's courses by others",
  649:                               col2 => 'Rules',},
  650:                              {col1 => "Co-author roles in this domain for others",
  651:                               col2 => 'Rules',},
  652:                              {col1 => "Co-author roles for this domain's users elsewhere",
  653:                               col2 => 'Rules',},
  654:                              {col1 => "Domain roles in this domain assignable to others",
  655:                               col2 => 'Rules'},
  656:                              {col1 => "Course catalog for this domain displayed elsewhere",
  657:                               col2 => 'Rules'},
  658:                              {col1 => "Requests for creation of courses in this domain by others",
  659:                               col2 => 'Rules'},
  660:                              {col1 => "Users in other domains can send messages to this domain",
  661:                               col2 => 'Rules'},],
  662:                   print => \&print_trust,
  663:                   modify => \&modify_trust,
  664:                  },
  665:         'lti' =>
  666:                  {text => 'LTI Link Protection and LTI Consumers',
  667:                   help => 'Domain_Configuration_LTI_Provider',
  668:                   header => [{col1 => 'Encryption of shared secrets',
  669:                               col2 => 'Settings'},
  670:                              {col1 => 'Rules for shared secrets',
  671:                               col2 => 'Settings'},
  672:                              {col1 => 'Link Protectors',
  673:                               col2 => 'Settings'},
  674:                              {col1 => 'Consumers',
  675:                               col2 => 'Settings'},],
  676:                   print => \&print_lti,
  677:                   modify => \&modify_lti,
  678:                  },
  679:         'ipaccess' =>
  680:                        {text => 'IP-based access control',
  681:                         help => 'Domain_Configuration_IP_Access',
  682:                         header => [{col1 => 'Setting',
  683:                                     col2 => 'Value'},],
  684:                         print  => \&print_ipaccess,
  685:                         modify => \&modify_ipaccess,
  686:                        },
  687:     );
  688:     if (keys(%servers) > 1) {
  689:         $prefs{'login'}  = { text   => 'Log-in page options',
  690:                              help   => 'Domain_Configuration_Login_Page',
  691:                             header => [{col1 => 'Log-in Service',
  692:                                         col2 => 'Server Setting',},
  693:                                        {col1 => 'Log-in Page Items',
  694:                                         col2 => 'Settings'},
  695:                                        {col1 => 'Log-in Help',
  696:                                         col2 => 'Value'},
  697:                                        {col1 => 'Custom HTML in document head',
  698:                                         col2 => 'Value'},
  699:                                        {col1 => 'SSO',
  700:                                         col2 => 'Dual login: SSO and non-SSO options'},
  701:                                       ],
  702:                             print => \&print_login,
  703:                             modify => \&modify_login,
  704:                            };
  705:     }
  706: 
  707:     my @roles = ('student','coordinator','author','admin');
  708:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  709:     &Apache::lonhtmlcommon::add_breadcrumb
  710:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  711:       text=>"Settings to display/modify"});
  712:     my $confname = $dom.'-domainconfig';
  713: 
  714:     if ($phase eq 'process') {
  715:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  716:                                                               \%prefs,\%domconfig,$confname,\@roles);
  717:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  718:             $r->rflush();
  719:             &devalidate_remote_domconfs($dom,$result);
  720:         }
  721:     } elsif ($phase eq 'display') {
  722:         my $js = &recaptcha_js().
  723:                  &toggle_display_js();
  724:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  725:             my ($othertitle,$usertypes,$types) =
  726:                 &Apache::loncommon::sorted_inst_types($dom);
  727:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  728:                                           $domconfig{'loadbalancing'}).
  729:                    &new_spares_js().
  730:                    &common_domprefs_js().
  731:                    &Apache::loncommon::javascript_array_indexof();
  732:         }
  733:         if (grep(/^requestcourses$/,@actions)) {
  734:             my $javascript_validations;
  735:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  736:             $js .= <<END;
  737: <script type="text/javascript">
  738: $javascript_validations
  739: </script>
  740: $coursebrowserjs
  741: END
  742:         } elsif (grep(/^ipaccess$/,@actions)) {
  743:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  744:         }
  745:         if (grep(/^selfcreation$/,@actions)) {
  746:             $js .= &selfcreate_javascript();
  747:         }
  748:         if (grep(/^contacts$/,@actions)) {
  749:             $js .= &contacts_javascript();
  750:         }
  751:         if (grep(/^scantron$/,@actions)) {
  752:             $js .= &scantron_javascript();
  753:         }
  754:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  755:     } else {
  756: # check if domconfig user exists for the domain.
  757:         my $servadm = $r->dir_config('lonAdmEMail');
  758:         my ($configuserok,$author_ok,$switchserver) =
  759:             &config_check($dom,$confname,$servadm);
  760:         unless ($configuserok eq 'ok') {
  761:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  762:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  763:                           $confname).
  764:                       '<br />'
  765:             );
  766:             if ($switchserver) {
  767:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  768:                           '<br />'.
  769:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  770:                           '<br />'.
  771:                           &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).
  772:                           '<br />'.
  773:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  774:                 );
  775:             } else {
  776:                 $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.').
  777:                           '<br />'.
  778:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  779:                 );
  780:             }
  781:             $r->print(&Apache::loncommon::end_page());
  782:             return OK;
  783:         }
  784:         if (keys(%domconfig) == 0) {
  785:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  786:             my @ids=&Apache::lonnet::current_machine_ids();
  787:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  788:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  789:                 my @loginimages = ('img','logo','domlogo','login');
  790:                 my $custom_img_count = 0;
  791:                 foreach my $img (@loginimages) {
  792:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  793:                         $custom_img_count ++;
  794:                     }
  795:                 }
  796:                 foreach my $role (@roles) {
  797:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  798:                         $custom_img_count ++;
  799:                     }
  800:                 }
  801:                 if ($custom_img_count > 0) {
  802:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  803:                     my $switch_server = &check_switchserver($dom,$confname);
  804:                     $r->print(
  805:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  806:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  807:     &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 />'.
  808:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  809:                     if ($switch_server) {
  810:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  811:                     }
  812:                     $r->print(&Apache::loncommon::end_page());
  813:                     return OK;
  814:                 }
  815:             }
  816:         }
  817:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  818:     }
  819:     return OK;
  820: }
  821: 
  822: sub process_changes {
  823:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  824:     my %domconfig;
  825:     if (ref($values) eq 'HASH') {
  826:         %domconfig = %{$values};
  827:     }
  828:     my $output;
  829:     if ($action eq 'login') {
  830:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  831:     } elsif ($action eq 'rolecolors') {
  832:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  833:                                      $lastactref,%domconfig);
  834:     } elsif ($action eq 'quotas') {
  835:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  836:     } elsif ($action eq 'autoenroll') {
  837:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  838:     } elsif ($action eq 'autoupdate') {
  839:         $output = &modify_autoupdate($dom,%domconfig);
  840:     } elsif ($action eq 'autocreate') {
  841:         $output = &modify_autocreate($dom,%domconfig);
  842:     } elsif ($action eq 'directorysrch') {
  843:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  844:     } elsif ($action eq 'usercreation') {
  845:         $output = &modify_usercreation($dom,%domconfig);
  846:     } elsif ($action eq 'selfcreation') {
  847:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  848:     } elsif ($action eq 'usermodification') {
  849:         $output = &modify_usermodification($dom,%domconfig);
  850:     } elsif ($action eq 'contacts') {
  851:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  852:     } elsif ($action eq 'defaults') {
  853:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  854:     } elsif ($action eq 'scantron') {
  855:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  856:     } elsif ($action eq 'coursecategories') {
  857:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  858:     } elsif ($action eq 'serverstatuses') {
  859:         $output = &modify_serverstatuses($dom,%domconfig);
  860:     } elsif ($action eq 'requestcourses') {
  861:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  862:     } elsif ($action eq 'requestauthor') {
  863:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  864:     } elsif ($action eq 'helpsettings') {
  865:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  866:     } elsif ($action eq 'coursedefaults') {
  867:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  868:     } elsif ($action eq 'selfenrollment') {
  869:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  870:     } elsif ($action eq 'usersessions') {
  871:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  872:     } elsif ($action eq 'loadbalancing') {
  873:         $output = &modify_loadbalancing($dom,%domconfig);
  874:     } elsif ($action eq 'ltitools') {
  875:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  876:     } elsif ($action eq 'proctoring') {
  877:         $output = &modify_proctoring($r,$dom,$action,$lastactref,%domconfig);
  878:     } elsif ($action eq 'ssl') {
  879:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  880:     } elsif ($action eq 'trust') {
  881:         $output = &modify_trust($dom,$lastactref,%domconfig);
  882:     } elsif ($action eq 'lti') {
  883:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  884:     } elsif ($action eq 'privacy') {
  885:         $output = &modify_privacy($dom,%domconfig);
  886:     } elsif ($action eq 'passwords') {
  887:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  888:     } elsif ($action eq 'wafproxy') {
  889:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  890:     } elsif ($action eq 'ipaccess') {
  891:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  892:     }
  893:     return $output;
  894: }
  895: 
  896: sub print_config_box {
  897:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  898:     my $rowtotal = 0;
  899:     my $output;
  900:     if ($action eq 'coursecategories') {
  901:         $output = &coursecategories_javascript($settings);
  902:     } elsif ($action eq 'defaults') {
  903:         $output = &defaults_javascript($settings); 
  904:     } elsif ($action eq 'passwords') {
  905:         $output = &passwords_javascript($action);
  906:     } elsif ($action eq 'helpsettings') {
  907:         my (%privs,%levelscurrent);
  908:         my %full=();
  909:         my %levels=(
  910:                      course => {},
  911:                      domain => {},
  912:                      system => {},
  913:                    );
  914:         my $context = 'domain';
  915:         my $crstype = 'Course';
  916:         my $formname = 'display';
  917:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  918:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  919:         $output =
  920:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  921:                                                       \@templateroles);
  922:     } elsif ($action eq 'ltitools') {
  923:         $output .= &Apache::lonconfigsettings::ltitools_javascript($settings);
  924:     } elsif ($action eq 'lti') {
  925:         $output .= &passwords_javascript('ltisecrets')."\n".
  926:                    &lti_javascript($dom,$settings);
  927:     } elsif ($action eq 'proctoring') {
  928:         $output .= &proctoring_javascript($settings);
  929:     } elsif ($action eq 'wafproxy') {
  930:         $output .= &wafproxy_javascript($dom);
  931:     } elsif ($action eq 'autoupdate') {
  932:         $output .= &autoupdate_javascript();
  933:     } elsif ($action eq 'autoenroll') {
  934:         $output .= &autoenroll_javascript();
  935:     } elsif ($action eq 'login') {
  936:         $output .= &saml_javascript();
  937:     } elsif ($action eq 'ipaccess') {
  938:         $output .= &ipaccess_javascript($settings);
  939:     }
  940:     $output .=
  941:          '<table class="LC_nested_outer">
  942:           <tr>
  943:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  944:            &mt($item->{text}).'&nbsp;'.
  945:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  946:           '</tr>';
  947:     $rowtotal ++;
  948:     my $numheaders = 1;
  949:     if (ref($item->{'header'}) eq 'ARRAY') {
  950:         $numheaders = scalar(@{$item->{'header'}});
  951:     }
  952:     if ($numheaders > 1) {
  953:         my $colspan = '';
  954:         my $rightcolspan = '';
  955:         my $leftnobr = '';
  956:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  957:             ($action eq 'directorysrch') ||
  958:             (($action eq 'login') && ($numheaders < 5))) {
  959:             $colspan = ' colspan="2"';
  960:         }
  961:         if ($action eq 'usersessions') {
  962:             $rightcolspan = ' colspan="3"'; 
  963:         }
  964:         if ($action eq 'passwords') {
  965:             $leftnobr = ' LC_nobreak';
  966:         }
  967:         $output .= '
  968:           <tr>
  969:            <td>
  970:             <table class="LC_nested">
  971:              <tr class="LC_info_row">
  972:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  973:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  974:              </tr>';
  975:         $rowtotal ++;
  976:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  977:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  978:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  979:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  980:             ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy') ||
  981:             ($action eq 'lti') || ($action eq 'ltitools')) {
  982:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  983:         } elsif ($action eq 'passwords') {
  984:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  985:         } elsif ($action eq 'coursecategories') {
  986:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  987:         } elsif ($action eq 'scantron') {
  988:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  989:         } elsif ($action eq 'login') {
  990:             if ($numheaders == 5) {
  991:                 $colspan = ' colspan="2"';
  992:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  993:             } else {
  994:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  995:             }
  996:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  997:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  998:         } elsif ($action eq 'rolecolors') {
  999:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
 1000:         }
 1001:         $output .= '
 1002:            </table>
 1003:           </td>
 1004:          </tr>
 1005:          <tr>
 1006:            <td>
 1007:             <table class="LC_nested">
 1008:              <tr class="LC_info_row">
 1009:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
 1010:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
 1011:              </tr>';
 1012:             $rowtotal ++;
 1013:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
 1014:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
 1015:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
 1016:             ($action eq 'trust') || ($action eq 'contacts') || ($action eq 'defaults') ||
 1017:             ($action eq 'privacy') || ($action eq 'passwords') || ($action eq 'lti') ||
 1018:             ($action eq 'ltitools')) {
 1019:             if ($action eq 'coursecategories') {
 1020:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
 1021:                 $colspan = ' colspan="2"';
 1022:             } elsif ($action eq 'trust') {
 1023:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
 1024:             } elsif ($action eq 'passwords') {
 1025:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
 1026:             } else {
 1027:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
 1028:             }
 1029:             if ($action eq 'trust') {
 1030:                 $output .= '
 1031:             </table>
 1032:           </td>
 1033:          </tr>';
 1034:                 my @trusthdrs = qw(2 3 4 5 6 7);
 1035:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
 1036:                 for (my $i=0; $i<@trusthdrs; $i++) {
 1037:                     $output .= '
 1038:          <tr>
 1039:            <td>
 1040:             <table class="LC_nested">
 1041:              <tr class="LC_info_row">
 1042:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
 1043:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
 1044:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
 1045:             </table>
 1046:           </td>
 1047:          </tr>';
 1048:                 }
 1049:                 $output .= '
 1050:          <tr>
 1051:            <td>
 1052:             <table class="LC_nested">
 1053:              <tr class="LC_info_row">
 1054:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
 1055:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
 1056:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1057:             } else {
 1058:                 $output .= '
 1059:            </table>
 1060:           </td>
 1061:          </tr>
 1062:          <tr>
 1063:            <td>
 1064:             <table class="LC_nested">
 1065:              <tr class="LC_info_row">
 1066:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1067:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1068:              </tr>'."\n";
 1069:                 if ($action eq 'coursecategories') {
 1070:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
 1071:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || 
 1072:                          ($action eq 'passwords') || ($action eq 'lti')) {
 1073:                     if ($action eq 'passwords') {
 1074:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
 1075:                     } else {
 1076:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
 1077:                     }
 1078:                     $output .= '
 1079:              </tr>
 1080:             </table>
 1081:            </td>
 1082:           </tr>
 1083:           <tr>
 1084:            <td>
 1085:             <table class="LC_nested">
 1086:              <tr class="LC_info_row">
 1087:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1088:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
 1089:                     if ($action eq 'passwords') {
 1090:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
 1091:                     } else {
 1092:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1093:                     }
 1094:                     $output .= '
 1095:             </table>
 1096:           </td>
 1097:          </tr>
 1098:          <tr>';
 1099:                 } else {
 1100:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1101:                 }
 1102:             }
 1103:             $rowtotal ++;
 1104:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
 1105:                  ($action eq 'directorysrch') || ($action eq 'helpsettings') ||
 1106:                  ($action eq 'wafproxy')) {
 1107:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1108:         } elsif ($action eq 'scantron') {
 1109:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
 1110:         } elsif ($action eq 'ssl') {
 1111:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
 1112:             </table>
 1113:           </td>
 1114:          </tr>
 1115:          <tr>
 1116:            <td>
 1117:             <table class="LC_nested">
 1118:              <tr class="LC_info_row">
 1119:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1120:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1121:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
 1122:             </table>
 1123:           </td>
 1124:          </tr>
 1125:          <tr>
 1126:            <td>
 1127:             <table class="LC_nested">
 1128:              <tr class="LC_info_row">
 1129:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1130:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1131:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1132:         } elsif ($action eq 'login') {
 1133:             if ($numheaders == 5) {
 1134:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1135:            </table>
 1136:           </td>
 1137:          </tr>
 1138:          <tr>
 1139:            <td>
 1140:             <table class="LC_nested">
 1141:              <tr class="LC_info_row">
 1142:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1143:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1144:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1145:                 $rowtotal ++;
 1146:             } else {
 1147:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1148:             }
 1149:             $output .= '
 1150:            </table>
 1151:           </td>
 1152:          </tr>
 1153:          <tr>
 1154:            <td>
 1155:             <table class="LC_nested">
 1156:              <tr class="LC_info_row">';
 1157:             if ($numheaders == 5) {
 1158:                 $output .= '
 1159:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1160:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1161:              </tr>';
 1162:             } else {
 1163:                 $output .= '
 1164:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1165:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1166:              </tr>';
 1167:             }
 1168:             $rowtotal ++;
 1169:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
 1170:            </table>
 1171:           </td>
 1172:          </tr>
 1173:          <tr>
 1174:            <td>
 1175:             <table class="LC_nested">
 1176:              <tr class="LC_info_row">';
 1177:             if ($numheaders == 5) {
 1178:                 $output .= '
 1179:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1180:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1181:              </tr>';
 1182:             } else {
 1183:                 $output .= '
 1184:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1185:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1186:              </tr>';
 1187:             }
 1188:             $rowtotal ++;
 1189:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1190:         } elsif ($action eq 'requestcourses') {
 1191:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1192:             $rowtotal ++;
 1193:             $output .= &print_studentcode($settings,\$rowtotal).'
 1194:            </table>
 1195:           </td>
 1196:          </tr>
 1197:          <tr>
 1198:            <td>
 1199:             <table class="LC_nested">
 1200:              <tr class="LC_info_row">
 1201:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1202:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1203:                        &textbookcourses_javascript($settings).
 1204:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1205:             </table>
 1206:            </td>
 1207:           </tr>
 1208:          <tr>
 1209:            <td>
 1210:             <table class="LC_nested">
 1211:              <tr class="LC_info_row">
 1212:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1213:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1214:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1215:             </table>
 1216:            </td>
 1217:           </tr>
 1218:           <tr>
 1219:            <td>
 1220:             <table class="LC_nested">
 1221:              <tr class="LC_info_row">
 1222:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1223:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1224:              </tr>'.
 1225:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1226:         } elsif ($action eq 'requestauthor') {
 1227:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1228:             $rowtotal ++;
 1229:         } elsif ($action eq 'rolecolors') {
 1230:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1231:            </table>
 1232:           </td>
 1233:          </tr>
 1234:          <tr>
 1235:            <td>
 1236:             <table class="LC_nested">
 1237:              <tr class="LC_info_row">
 1238:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1239:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1240:               <td class="LC_right_item" style="vertical-align: top">'.
 1241:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1242:              </tr>'.
 1243:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1244:            </table>
 1245:           </td>
 1246:          </tr>
 1247:          <tr>
 1248:            <td>
 1249:             <table class="LC_nested">
 1250:              <tr class="LC_info_row">
 1251:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1252:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1253:              </tr>'.
 1254:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1255:             $rowtotal += 2;
 1256:         }
 1257:     } else {
 1258:         $output .= '
 1259:           <tr>
 1260:            <td>
 1261:             <table class="LC_nested">
 1262:              <tr class="LC_info_row">';
 1263:         if ($action eq 'login') {
 1264:             $output .= '  
 1265:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1266:         } elsif ($action eq 'serverstatuses') {
 1267:             $output .= '
 1268:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1269:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1270: 
 1271:         } else {
 1272:             $output .= '
 1273:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1274:         }
 1275:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1276:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1277:                        &mt($item->{'header'}->[0]->{'col2'});
 1278:             if ($action eq 'serverstatuses') {
 1279:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1280:             } 
 1281:         } else {
 1282:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1283:                        &mt($item->{'header'}->[0]->{'col2'});
 1284:         }
 1285:         $output .= '</td>';
 1286:         if ($item->{'header'}->[0]->{'col3'}) {
 1287:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1288:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1289:                             &mt($item->{'header'}->[0]->{'col3'});
 1290:             } else {
 1291:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1292:                            &mt($item->{'header'}->[0]->{'col3'});
 1293:             }
 1294:             if ($action eq 'serverstatuses') {
 1295:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1296:             }
 1297:             $output .= '</td>';
 1298:         }
 1299:         if ($item->{'header'}->[0]->{'col4'}) {
 1300:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1301:                        &mt($item->{'header'}->[0]->{'col4'});
 1302:         }
 1303:         $output .= '</tr>';
 1304:         $rowtotal ++;
 1305:         if ($action eq 'quotas') {
 1306:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1307:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1308:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1309:                  ($action eq 'proctoring') || ($action eq 'ipaccess')) {
 1310:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1311:         }
 1312:     }
 1313:     $output .= '
 1314:    </table>
 1315:   </td>
 1316:  </tr>
 1317: </table><br />';
 1318:     return ($output,$rowtotal);
 1319: }
 1320: 
 1321: sub print_login {
 1322:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1323:     my ($css_class,$datatable,$switchserver,%lt);
 1324:     my %choices = &login_choices();
 1325:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1326:         %lt = &login_file_options();
 1327:         $switchserver = &check_switchserver($dom,$confname);
 1328:     }
 1329:     if ($caller eq 'service') {
 1330:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1331:         my $choice = $choices{'disallowlogin'};
 1332:         $css_class = ' class="LC_odd_row"';
 1333:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1334:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1335:                       '<th>'.$choices{'server'}.'</th>'.
 1336:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1337:                       '<th>'.$choices{'custompath'}.'</th>'.
 1338:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1339:         my %disallowed;
 1340:         if (ref($settings) eq 'HASH') {
 1341:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1342:                %disallowed = %{$settings->{'loginvia'}};
 1343:             }
 1344:         }
 1345:         foreach my $lonhost (sort(keys(%servers))) {
 1346:             my $direct = 'selected="selected"';
 1347:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1348:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1349:                     $direct = '';
 1350:                 }
 1351:             }
 1352:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1353:                           '<td><select name="'.$lonhost.'_server">'.
 1354:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1355:                           '</option>';
 1356:             foreach my $hostid (sort(keys(%servers))) {
 1357:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1358:                 my $selected = '';
 1359:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1360:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1361:                         $selected = 'selected="selected"';
 1362:                     }
 1363:                 }
 1364:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1365:                               $servers{$hostid}.'</option>';
 1366:             }
 1367:             $datatable .= '</select></td>'.
 1368:                           '<td><select name="'.$lonhost.'_serverpath">';
 1369:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1370:                 my $pathname = $path;
 1371:                 if ($path eq 'custom') {
 1372:                     $pathname = &mt('Custom Path').' ->';
 1373:                 }
 1374:                 my $selected = '';
 1375:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1376:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1377:                         $selected = 'selected="selected"';
 1378:                     }
 1379:                 } elsif ($path eq '') {
 1380:                     $selected = 'selected="selected"';
 1381:                 }
 1382:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1383:             }
 1384:             $datatable .= '</select></td>';
 1385:             my ($custom,$exempt);
 1386:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1387:                 $custom = $disallowed{$lonhost}{'custompath'};
 1388:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1389:             }
 1390:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1391:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1392:                           '</tr>';
 1393:         }
 1394:         $datatable .= '</table></td></tr>';
 1395:         return $datatable;
 1396:     } elsif ($caller eq 'page') {
 1397:         my %defaultchecked = ( 
 1398:                                'coursecatalog' => 'on',
 1399:                                'helpdesk'      => 'on',
 1400:                                'adminmail'     => 'off',
 1401:                                'newuser'       => 'off',
 1402:                              );
 1403:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1404:         my (%checkedon,%checkedoff);
 1405:         foreach my $item (@toggles) {
 1406:             if ($defaultchecked{$item} eq 'on') { 
 1407:                 $checkedon{$item} = ' checked="checked" ';
 1408:                 $checkedoff{$item} = ' ';
 1409:             } elsif ($defaultchecked{$item} eq 'off') {
 1410:                 $checkedoff{$item} = ' checked="checked" ';
 1411:                 $checkedon{$item} = ' ';
 1412:             }
 1413:         }
 1414:         my @images = ('img','logo','domlogo','login');
 1415:         my @alttext = ('img','logo','domlogo');
 1416:         my @logintext = ('textcol','bgcol');
 1417:         my @bgs = ('pgbg','mainbg','sidebg');
 1418:         my @links = ('link','alink','vlink');
 1419:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1420:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1421:         my (%is_custom,%designs);
 1422:         my %defaults = (
 1423:                        font => $defaultdesign{'login.font'},
 1424:                        );
 1425:         foreach my $item (@images) {
 1426:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1427:             $defaults{'showlogo'}{$item} = 1;
 1428:         }
 1429:         foreach my $item (@bgs) {
 1430:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1431:         }
 1432:         foreach my $item (@logintext) {
 1433:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1434:         }
 1435:         foreach my $item (@links) {
 1436:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1437:         }
 1438:         if (ref($settings) eq 'HASH') {
 1439:             foreach my $item (@toggles) {
 1440:                 if ($settings->{$item} eq '1') {
 1441:                     $checkedon{$item} =  ' checked="checked" ';
 1442:                     $checkedoff{$item} = ' ';
 1443:                 } elsif ($settings->{$item} eq '0') {
 1444:                     $checkedoff{$item} =  ' checked="checked" ';
 1445:                     $checkedon{$item} = ' ';
 1446:                 }
 1447:             }
 1448:             foreach my $item (@images) {
 1449:                 if (defined($settings->{$item})) {
 1450:                     $designs{$item} = $settings->{$item};
 1451:                     $is_custom{$item} = 1;
 1452:                 }
 1453:                 if (defined($settings->{'showlogo'}{$item})) {
 1454:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1455:                 }
 1456:             }
 1457:             foreach my $item (@alttext) {
 1458:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1459:                     if ($settings->{'alttext'}->{$item} ne '') {
 1460:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1461:                     }
 1462:                 }
 1463:             }
 1464:             foreach my $item (@logintext) {
 1465:                 if ($settings->{$item} ne '') {
 1466:                     $designs{'logintext'}{$item} = $settings->{$item};
 1467:                     $is_custom{$item} = 1;
 1468:                 }
 1469:             }
 1470:             if ($settings->{'font'} ne '') {
 1471:                 $designs{'font'} = $settings->{'font'};
 1472:                 $is_custom{'font'} = 1;
 1473:             }
 1474:             foreach my $item (@bgs) {
 1475:                 if ($settings->{$item} ne '') {
 1476:                     $designs{'bgs'}{$item} = $settings->{$item};
 1477:                     $is_custom{$item} = 1;
 1478:                 }
 1479:             }
 1480:             foreach my $item (@links) {
 1481:                 if ($settings->{$item} ne '') {
 1482:                     $designs{'links'}{$item} = $settings->{$item};
 1483:                     $is_custom{$item} = 1;
 1484:                 }
 1485:             }
 1486:         } else {
 1487:             if ($designhash{$dom.'.login.font'} ne '') {
 1488:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1489:                 $is_custom{'font'} = 1;
 1490:             }
 1491:             foreach my $item (@images) {
 1492:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1493:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1494:                     $is_custom{$item} = 1;
 1495:                 }
 1496:             }
 1497:             foreach my $item (@bgs) {
 1498:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1499:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1500:                     $is_custom{$item} = 1;
 1501:                 }
 1502:             }
 1503:             foreach my $item (@links) {
 1504:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1505:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1506:                     $is_custom{$item} = 1;
 1507:                 }
 1508:             }
 1509:         }
 1510:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1511:                                                       logo => 'Institution Logo',
 1512:                                                       domlogo => 'Domain Logo',
 1513:                                                       login => 'Login box');
 1514:         my $itemcount = 1;
 1515:         foreach my $item (@toggles) {
 1516:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1517:             $datatable .=  
 1518:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1519:                 '</td><td>'.
 1520:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1521:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1522:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1523:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1524:                 '</tr>';
 1525:             $itemcount ++;
 1526:         }
 1527:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1528:         $datatable .= '</tr></table></td></tr>';
 1529:     } elsif ($caller eq 'help') {
 1530:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1531:         my $itemcount = 1;
 1532:         $defaulturl = '/adm/loginproblems.html';
 1533:         $defaulttype = 'default';
 1534:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1535:         my @currlangs;
 1536:         if (ref($settings) eq 'HASH') {
 1537:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1538:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1539:                     next if ($settings->{'helpurl'}{$key} eq '');
 1540:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1541:                     $type{$key} = 'custom';
 1542:                     unless ($key eq 'nolang') {
 1543:                         push(@currlangs,$key);
 1544:                     }
 1545:                 }
 1546:             } elsif ($settings->{'helpurl'} ne '') {
 1547:                 $type{'nolang'} = 'custom';
 1548:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1549:             }
 1550:         }
 1551:         foreach my $lang ('nolang',sort(@currlangs)) {
 1552:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1553:             $datatable .= '<tr'.$css_class.'>';
 1554:             if ($url{$lang} eq '') {
 1555:                 $url{$lang} = $defaulturl;
 1556:             }
 1557:             if ($type{$lang} eq '') {
 1558:                 $type{$lang} = $defaulttype;
 1559:             }
 1560:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1561:             if ($lang eq 'nolang') {
 1562:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1563:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1564:             } else {
 1565:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1566:                                   $langchoices{$lang},
 1567:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1568:             }
 1569:             $datatable .= '</span></td>'."\n".
 1570:                           '<td class="LC_left_item">';
 1571:             if ($type{$lang} eq 'custom') {
 1572:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1573:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1574:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1575:             } else {
 1576:                 $datatable .= $lt{'upl'};
 1577:             }
 1578:             $datatable .='<br />';
 1579:             if ($switchserver) {
 1580:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1581:             } else {
 1582:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1583:             }
 1584:             $datatable .= '</td></tr>';
 1585:             $itemcount ++;
 1586:         }
 1587:         my @addlangs;
 1588:         foreach my $lang (sort(keys(%langchoices))) {
 1589:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1590:             push(@addlangs,$lang);
 1591:         }
 1592:         if (@addlangs > 0) {
 1593:             my %toadd;
 1594:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1595:             $toadd{''} = &mt('Select');
 1596:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1597:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1598:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1599:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1600:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1601:             if ($switchserver) {
 1602:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1603:             } else {
 1604:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1605:             }
 1606:             $datatable .= '</td></tr>';
 1607:             $itemcount ++;
 1608:         }
 1609:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1610:     } elsif ($caller eq 'headtag') {
 1611:         my %domservers = &Apache::lonnet::get_servers($dom);
 1612:         my $choice = $choices{'headtag'};
 1613:         $css_class = ' class="LC_odd_row"';
 1614:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1615:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1616:                       '<th>'.$choices{'current'}.'</th>'.
 1617:                       '<th>'.$choices{'action'}.'</th>'.
 1618:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1619:         my (%currurls,%currexempt);
 1620:         if (ref($settings) eq 'HASH') {
 1621:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1622:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1623:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1624:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1625:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1626:                     }
 1627:                 }
 1628:             }
 1629:         }
 1630:         foreach my $lonhost (sort(keys(%domservers))) {
 1631:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1632:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1633:             if ($currurls{$lonhost}) {
 1634:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1635:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1636:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1637:                               '">'.$lt{'curr'}.'</a></td>'.
 1638:                               '<td><span class="LC_nobreak"><label>'.
 1639:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1640:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1641:             } else {
 1642:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1643:             }
 1644:             $datatable .='<br />';
 1645:             if ($switchserver) {
 1646:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1647:             } else {
 1648:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1649:             }
 1650:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1651:         }
 1652:         $datatable .= '</table></td></tr>';
 1653:     } elsif ($caller eq 'saml') {
 1654:         my %domservers = &Apache::lonnet::get_servers($dom);
 1655:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1656:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1657:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1658:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1659:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlwindow,%samlnotsso,%styleon,%styleoff);
 1660:         foreach my $lonhost (keys(%domservers)) {
 1661:             $samlurl{$lonhost} = '/adm/sso';
 1662:             $styleon{$lonhost} = 'display:none';
 1663:             $styleoff{$lonhost} = '';
 1664:         }
 1665:         if ((ref($settings) eq 'HASH') && (ref($settings->{'saml'}) eq 'HASH')) {
 1666:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1667:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1668:                     $saml{$lonhost} = 1;
 1669:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1670:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1671:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1672:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1673:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1674:                     $samlwindow{$lonhost} = $settings->{'saml'}{$lonhost}{'window'};
 1675:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1676:                     $styleon{$lonhost} = '';
 1677:                     $styleoff{$lonhost} = 'display:none';
 1678:                 } else {
 1679:                     $styleon{$lonhost} = 'display:none';
 1680:                     $styleoff{$lonhost} = '';
 1681:                 }
 1682:             }
 1683:         }
 1684:         my $itemcount = 1;
 1685:         foreach my $lonhost (sort(keys(%domservers))) {
 1686:             my $samlon = ' ';
 1687:             my $samloff = ' checked="checked" ';
 1688:             if ($saml{$lonhost}) {
 1689:                 $samlon = $samloff;
 1690:                 $samloff = ' ';
 1691:             }
 1692:             my $samlwinon = '';
 1693:             my $samlwinoff = ' checked="checked"';
 1694:             if ($samlwindow{$lonhost}) {
 1695:                 $samlwinon = $samlwinoff;
 1696:                 $samlwinoff = '';
 1697:             }
 1698:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1699:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1700:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1701:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1702:                           &mt('No').'</label>'.('&nbsp;'x2).
 1703:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1704:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1705:                           &mt('Yes').'</label></span></td>'.
 1706:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1707:                           '<table width="100%"><tr><th colspan="3" align="center">'.&mt('SSO').'</th></tr>'.
 1708:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1709:                           '<th>'.&mt('Alt Text').'</th></tr>'.
 1710:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="20" value="'.
 1711:                           $samltext{$lonhost}.'" /></td><td>';
 1712:             if ($samlimg{$lonhost}) {
 1713:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1714:                               '<span class="LC_nobreak"><label>'.
 1715:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1716:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1717:             } else {
 1718:                 $datatable .= $lt{'upl'};
 1719:             }
 1720:             $datatable .='<br />';
 1721:             if ($switchserver) {
 1722:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1723:             } else {
 1724:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1725:             }
 1726:             $datatable .= '</td>'.
 1727:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="25" '.
 1728:                           'value="'.$samlalt{$lonhost}.'" /></td></tr></table><br />'.
 1729:                           '<table width="100%"><tr><th colspan="3" align="center">'.&mt('SSO').'</th><th align="center">'.
 1730:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1731:                           '<tr><th>'.&mt('URL').'</th><th>'.&mt('Tool Tip').'</th>'.
 1732:                           '<th>'.&mt('Pop-up if iframe').'</th><th>'.&mt('Text').'</th></tr>'.
 1733:                           '<tr'.$css_class.'>'.
 1734:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="30" '.
 1735:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1736:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="20">'.
 1737:                           $samltitle{$lonhost}.'</textarea></td>'.
 1738:                           '<td><label><input type="radio" name="saml_window_'.$lonhost.'" value=""'.$samlwinoff.'>'.
 1739:                           &mt('No').'</label>'.('&nbsp;'x2).'<label><input type="radio" '.
 1740:                           'name="saml_window_'.$lonhost.'" value="1"'.$samlwinon.'>'.&mt('Yes').'</label></td>'.
 1741:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="12" '.
 1742:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1743:                           '</table></td>'.
 1744:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1745:            $itemcount ++;
 1746:         }
 1747:         $datatable .= '</table></td></tr>';
 1748:     }
 1749:     return $datatable;
 1750: }
 1751: 
 1752: sub login_choices {
 1753:     my %choices =
 1754:         &Apache::lonlocal::texthash (
 1755:             coursecatalog => 'Display Course/Community Catalog link?',
 1756:             adminmail     => "Display Administrator's E-mail Address?",
 1757:             helpdesk      => 'Display "Contact Helpdesk" link',
 1758:             disallowlogin => "Login page requests redirected",
 1759:             hostid        => "Server",
 1760:             server        => "Redirect to:",
 1761:             serverpath    => "Path",
 1762:             custompath    => "Custom", 
 1763:             exempt        => "Exempt IP(s)",
 1764:             directlogin   => "No redirect",
 1765:             newuser       => "Link to create a user account",
 1766:             img           => "Header",
 1767:             logo          => "Main Logo",
 1768:             domlogo       => "Domain Logo",
 1769:             login         => "Log-in Header", 
 1770:             textcol       => "Text color",
 1771:             bgcol         => "Box color",
 1772:             bgs           => "Background colors",
 1773:             links         => "Link colors",
 1774:             font          => "Font color",
 1775:             pgbg          => "Header",
 1776:             mainbg        => "Page",
 1777:             sidebg        => "Login box",
 1778:             link          => "Link",
 1779:             alink         => "Active link",
 1780:             vlink         => "Visited link",
 1781:             headtag       => "Custom markup",
 1782:             action        => "Action",
 1783:             current       => "Current",
 1784:             samllanding   => "Dual login?",
 1785:             samloptions   => "Options",
 1786:             alttext       => "Alt text",
 1787:         );
 1788:     return %choices;
 1789: }
 1790: 
 1791: sub login_file_options {
 1792:       return &Apache::lonlocal::texthash(
 1793:                                            del     => 'Delete?',
 1794:                                            rep     => 'Replace:',
 1795:                                            upl     => 'Upload:',
 1796:                                            curr    => 'View contents',
 1797:                                            default => 'Default',
 1798:                                            custom  => 'Custom',
 1799:                                            none    => 'None',
 1800:       );
 1801: }
 1802: 
 1803: sub print_ipaccess {
 1804:     my ($dom,$settings,$rowtotal) = @_;
 1805:     my $css_class;
 1806:     my $itemcount = 0;
 1807:     my $datatable;
 1808:     my %ordered;
 1809:     if (ref($settings) eq 'HASH') {
 1810:         foreach my $item (keys(%{$settings})) {
 1811:             if (ref($settings->{$item}) eq 'HASH') {
 1812:                 my $num = $settings->{$item}{'order'};
 1813:                 if ($num eq '') {
 1814:                     $num = scalar(keys(%{$settings}));
 1815:                 }
 1816:                 $ordered{$num} = $item;
 1817:             }
 1818:         }
 1819:     }
 1820:     my $maxnum = scalar(keys(%ordered));
 1821:     if (keys(%ordered)) {
 1822:         my @items = sort { $a <=> $b } keys(%ordered);
 1823:         for (my $i=0; $i<@items; $i++) {
 1824:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1825:             my $item = $ordered{$items[$i]};
 1826:             my ($name,$ipranges,%commblocks,%courses);
 1827:             if (ref($settings->{$item}) eq 'HASH') {
 1828:                 $name = $settings->{$item}->{'name'};
 1829:                 $ipranges = $settings->{$item}->{'ip'};
 1830:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1831:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1832:                 }
 1833:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1834:                     %courses = %{$settings->{$item}->{'courses'}};
 1835:                 }
 1836:             }
 1837:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1838:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1839:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1840:             for (my $k=0; $k<=$maxnum; $k++) {
 1841:                 my $vpos = $k+1;
 1842:                 my $selstr;
 1843:                 if ($k == $i) {
 1844:                     $selstr = ' selected="selected" ';
 1845:                 }
 1846:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1847:             }
 1848:             $datatable .= '</select>'.('&nbsp;'x2).
 1849:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1850:                 &mt('Delete?').'</label></span></td>'.
 1851:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1852:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1853:                 '</td></tr>';
 1854:             $itemcount ++;
 1855:         }
 1856:     }
 1857:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1858:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1859:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1860:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1861:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1862:     for (my $k=0; $k<$maxnum+1; $k++) {
 1863:         my $vpos = $k+1;
 1864:         my $selstr;
 1865:         if ($k == $maxnum) {
 1866:             $selstr = ' selected="selected" ';
 1867:         }
 1868:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1869:     }
 1870:     $datatable .= '</select>&nbsp;'."\n".
 1871:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1872:                   '<td colspan="2">'.
 1873:                   &ipaccess_options('add',$itemcount,$dom).
 1874:                   '</td>'."\n".
 1875:                   '</tr>'."\n";
 1876:     $$rowtotal ++;
 1877:     return $datatable;
 1878: }
 1879: 
 1880: sub ipaccess_options {
 1881:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1882:     my (%currblocks,%currcourses,$output);
 1883:     if (ref($blocksref) eq 'HASH') {
 1884:         %currblocks = %{$blocksref};
 1885:     }
 1886:     if (ref($coursesref) eq 'HASH') {
 1887:         %currcourses = %{$coursesref};
 1888:     }
 1889:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1890:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1891:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1892:               '</span></fieldset>'.
 1893:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1894:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1895:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1896:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1897:               $ipranges.'</textarea></fieldset>'.
 1898:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1899:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1900:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1901:               '<table>';
 1902:     foreach my $cid (sort(keys(%currcourses))) {
 1903:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1904:         $output .= '<tr><td><span class="LC_nobreak">'.
 1905:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1906:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1907:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1908:     }
 1909:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1910:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1911:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1912:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1913:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1914:                '</span></td></tr></table>'."\n".
 1915:                '</fieldset>';
 1916:     return $output;
 1917: }
 1918: 
 1919: sub blocker_checkboxes {
 1920:     my ($num,$blocks) = @_;
 1921:     my ($typeorder,$types) = &commblocktype_text();
 1922:     my $numinrow = 6;
 1923:     my $output = '<table>';
 1924:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1925:         my $block = $typeorder->[$i];
 1926:         my $blockstatus;
 1927:         if (ref($blocks) eq 'HASH') {
 1928:             if ($blocks->{$block} eq 'on') {
 1929:                 $blockstatus = 'checked="checked"';
 1930:             }
 1931:         }
 1932:         my $rem = $i%($numinrow);
 1933:         if ($rem == 0) {
 1934:             if ($i > 0) {
 1935:                 $output .= '</tr>';
 1936:             }
 1937:             $output .= '<tr>';
 1938:         }
 1939:         if ($i == scalar(@{$typeorder})-1) {
 1940:             my $colsleft = $numinrow-$rem;
 1941:             if ($colsleft > 1) {
 1942:                 $output .= '<td colspan="'.$colsleft.'">';
 1943:             } else {
 1944:                 $output .= '<td>';
 1945:             }
 1946:         } else {
 1947:             $output .= '<td>';
 1948:         }
 1949:         my $item = 'ipaccess_block_'.$num;
 1950:         if ($blockstatus) {
 1951:             $blockstatus = ' '.$blockstatus;
 1952:         }
 1953:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1954:                    '<input type="checkbox" name="'.$item.'"'.
 1955:                    $blockstatus.' value="'.$block.'"'.' />'.
 1956:                    $types->{$block}.'</label></span>'."\n".
 1957:                    '<br /></td>';
 1958:     }
 1959:     $output .= '</tr></table>';
 1960:     return $output;
 1961: }
 1962: 
 1963: sub commblocktype_text {
 1964:     my %types = &Apache::lonlocal::texthash(
 1965:         'com' => 'Messaging',
 1966:         'chat' => 'Chat Room',
 1967:         'boards' => 'Discussion',
 1968:         'port' => 'Portfolio',
 1969:         'groups' => 'Groups',
 1970:         'blogs' => 'Blogs',
 1971:         'about' => 'User Information',
 1972:         'printout' => 'Printouts',
 1973:         'passwd' => 'Change Password',
 1974:         'grades' => 'Gradebook',
 1975:         'search' => 'Course search',
 1976:         'wishlist' => 'Stored links',
 1977:         'annotate' => 'Annotations',
 1978:     );
 1979:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1980:     return ($typeorder,\%types);
 1981: }
 1982: 
 1983: sub print_rolecolors {
 1984:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1985:     my %choices = &color_font_choices();
 1986:     my @bgs = ('pgbg','tabbg','sidebg');
 1987:     my @links = ('link','alink','vlink');
 1988:     my @images = ('img');
 1989:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1990:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1991:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1992:     my (%is_custom,%designs);
 1993:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1994:     if (ref($settings) eq 'HASH') {
 1995:         if (ref($settings->{$role}) eq 'HASH') {
 1996:             if ($settings->{$role}->{'img'} ne '') {
 1997:                 $designs{'img'} = $settings->{$role}->{'img'};
 1998:                 $is_custom{'img'} = 1;
 1999:             }
 2000:             if ($settings->{$role}->{'font'} ne '') {
 2001:                 $designs{'font'} = $settings->{$role}->{'font'};
 2002:                 $is_custom{'font'} = 1;
 2003:             }
 2004:             if ($settings->{$role}->{'fontmenu'} ne '') {
 2005:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 2006:                 $is_custom{'fontmenu'} = 1;
 2007:             }
 2008:             foreach my $item (@bgs) {
 2009:                 if ($settings->{$role}->{$item} ne '') {
 2010:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 2011:                     $is_custom{$item} = 1;
 2012:                 }
 2013:             }
 2014:             foreach my $item (@links) {
 2015:                 if ($settings->{$role}->{$item} ne '') {
 2016:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 2017:                     $is_custom{$item} = 1;
 2018:                 }
 2019:             }
 2020:         }
 2021:     } else {
 2022:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 2023:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 2024:             $is_custom{'img'} = 1;
 2025:         }
 2026:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 2027:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 2028:             $is_custom{'fontmenu'} = 1; 
 2029:         }
 2030:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 2031:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 2032:             $is_custom{'font'} = 1;
 2033:         }
 2034:         foreach my $item (@bgs) {
 2035:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 2036:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 2037:                 $is_custom{$item} = 1;
 2038:             
 2039:             }
 2040:         }
 2041:         foreach my $item (@links) {
 2042:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 2043:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 2044:                 $is_custom{$item} = 1;
 2045:             }
 2046:         }
 2047:     }
 2048:     my $itemcount = 1;
 2049:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 2050:     $datatable .= '</tr></table></td></tr>';
 2051:     return $datatable;
 2052: }
 2053: 
 2054: sub role_defaults {
 2055:     my ($role,$bgs,$links,$images,$logintext) = @_;
 2056:     my %defaults;
 2057:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 2058:         return %defaults;
 2059:     }
 2060:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 2061:     if ($role eq 'login') {
 2062:         %defaults = (
 2063:                        font => $defaultdesign{$role.'.font'},
 2064:                     );
 2065:         if (ref($logintext) eq 'ARRAY') {
 2066:             foreach my $item (@{$logintext}) {
 2067:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 2068:             }
 2069:         }
 2070:         foreach my $item (@{$images}) {
 2071:             $defaults{'showlogo'}{$item} = 1;
 2072:         }
 2073:     } else {
 2074:         %defaults = (
 2075:                        img => $defaultdesign{$role.'.img'},
 2076:                        font => $defaultdesign{$role.'.font'},
 2077:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 2078:                     );
 2079:     }
 2080:     foreach my $item (@{$bgs}) {
 2081:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 2082:     }
 2083:     foreach my $item (@{$links}) {
 2084:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 2085:     }
 2086:     foreach my $item (@{$images}) {
 2087:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 2088:     }
 2089:     return %defaults;
 2090: }
 2091: 
 2092: sub display_color_options {
 2093:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 2094:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 2095:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2096:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2097:     my $datatable = '<tr'.$css_class.'>'.
 2098:         '<td>'.$choices->{'font'}.'</td>';
 2099:     if (!$is_custom->{'font'}) {
 2100:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 2101:     } else {
 2102:         $datatable .= '<td>&nbsp;</td>';
 2103:     }
 2104:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 2105: 
 2106:     $datatable .= '<td><span class="LC_nobreak">'.
 2107:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 2108:                   ' value="'.$current_color.'" />&nbsp;'.
 2109:                   '&nbsp;</span></td></tr>';
 2110:     unless ($role eq 'login') { 
 2111:         $datatable .= '<tr'.$css_class.'>'.
 2112:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 2113:         if (!$is_custom->{'fontmenu'}) {
 2114:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 2115:         } else {
 2116:             $datatable .= '<td>&nbsp;</td>';
 2117:         }
 2118: 	$current_color = $designs->{'fontmenu'} ?
 2119: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 2120:         $datatable .= '<td><span class="LC_nobreak">'.
 2121:                       '<input class="colorchooser" type="text" size="10" name="'
 2122: 		      .$role.'_fontmenu"'.
 2123:                       ' value="'.$current_color.'" />&nbsp;'.
 2124:                       '&nbsp;</span></td></tr>';
 2125:     }
 2126:     my $switchserver = &check_switchserver($dom,$confname);
 2127:     foreach my $img (@{$images}) {
 2128: 	$itemcount ++;
 2129:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2130:         $datatable .= '<tr'.$css_class.'>'.
 2131:                       '<td>'.$choices->{$img};
 2132:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 2133:         if ($role eq 'login') {
 2134:             if ($img eq 'login') {
 2135:                 $login_hdr_pick =
 2136:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 2137:                 $logincolors =
 2138:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 2139:                                        $designs,$defaults);
 2140:             } else {
 2141:                 if ($img ne 'domlogo') {
 2142:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 2143:                 }
 2144:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 2145:                     $alttext = $designs->{'alttext'}{$img};
 2146:                 }
 2147:             }
 2148:         }
 2149:         $datatable .= '</td>';
 2150:         if ($designs->{$img} ne '') {
 2151:             $imgfile = $designs->{$img};
 2152: 	    $img_import = ($imgfile =~ m{^/adm/});
 2153:         } else {
 2154:             $imgfile = $defaults->{$img};
 2155:         }
 2156:         if ($imgfile) {
 2157:             my ($showfile,$fullsize);
 2158:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 2159:                 my $urldir = $1;
 2160:                 my $filename = $2;
 2161:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 2162:                 if (@info) {
 2163:                     my $thumbfile = 'tn-'.$filename;
 2164:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 2165:                     if (@thumb) {
 2166:                         $showfile = $urldir.'/'.$thumbfile;
 2167:                     } else {
 2168:                         $showfile = $imgfile;
 2169:                     }
 2170:                 } else {
 2171:                     $showfile = '';
 2172:                 }
 2173:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 2174:                 $showfile = $imgfile;
 2175:                 my $imgdir = $1;
 2176:                 my $filename = $2;
 2177:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 2178:                     $showfile = "/$imgdir/tn-".$filename;
 2179:                 } else {
 2180:                     my $input = $londocroot.$imgfile;
 2181:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 2182:                     if (!-e $output) {
 2183:                         my ($width,$height) = &thumb_dimensions();
 2184:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 2185:                         if ($fullwidth ne '' && $fullheight ne '') {
 2186:                             if ($fullwidth > $width && $fullheight > $height) { 
 2187:                                 my $size = $width.'x'.$height;
 2188:                                 my @args = ('convert','-sample',$size,$input,$output);
 2189:                                 system({$args[0]} @args);
 2190:                                 $showfile = "/$imgdir/tn-".$filename;
 2191:                             }
 2192:                         }
 2193:                     }
 2194:                 }
 2195:             }
 2196:             if ($showfile) {
 2197:                 if ($showfile =~ m{^/(adm|res)/}) {
 2198:                     if ($showfile =~ m{^/res/}) {
 2199:                         my $local_showfile =
 2200:                             &Apache::lonnet::filelocation('',$showfile);
 2201:                         &Apache::lonnet::repcopy($local_showfile);
 2202:                     }
 2203:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 2204:                 }
 2205:                 if ($imgfile) {
 2206:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 2207:                         if ($imgfile =~ m{^/res/}) {
 2208:                             my $local_imgfile =
 2209:                                 &Apache::lonnet::filelocation('',$imgfile);
 2210:                             &Apache::lonnet::repcopy($local_imgfile);
 2211:                         }
 2212:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 2213:                     } else {
 2214:                         $fullsize = $imgfile;
 2215:                     }
 2216:                 }
 2217:                 $datatable .= '<td>';
 2218:                 if ($img eq 'login') {
 2219:                     $datatable .= $login_hdr_pick;
 2220:                 } 
 2221:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 2222:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 2223:             } else {
 2224:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2225:                               &mt('Upload:').'<br />';
 2226:             }
 2227:         } else {
 2228:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2229:                           &mt('Upload:').'<br />';
 2230:         }
 2231:         if ($switchserver) {
 2232:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2233:         } else {
 2234:             if ($img ne 'login') { # suppress file selection for Log-in header
 2235:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 2236:             }
 2237:         }
 2238:         if (($role eq 'login') && ($img ne 'login')) {
 2239:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 2240:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 2241:                           '</label></span>';
 2242:         }
 2243:         $datatable .= '</td></tr>';
 2244:     }
 2245:     $itemcount ++;
 2246:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2247:     $datatable .= '<tr'.$css_class.'>'.
 2248:                   '<td>'.$choices->{'bgs'}.'</td>';
 2249:     my $bgs_def;
 2250:     foreach my $item (@{$bgs}) {
 2251:         if (!$is_custom->{$item}) {
 2252:             $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>';
 2253:         }
 2254:     }
 2255:     if ($bgs_def) {
 2256:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2257:     } else {
 2258:         $datatable .= '<td>&nbsp;</td>';
 2259:     }
 2260:     $datatable .= '<td class="LC_right_item">'.
 2261:                   '<table border="0"><tr>';
 2262: 
 2263:     foreach my $item (@{$bgs}) {
 2264:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 2265: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2266:         if ($designs->{'bgs'}{$item}) {
 2267:             $datatable .= '&nbsp;';
 2268:         }
 2269:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2270:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2271:     }
 2272:     $datatable .= '</tr></table></td></tr>';
 2273:     $itemcount ++;
 2274:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2275:     $datatable .= '<tr'.$css_class.'>'.
 2276:                   '<td>'.$choices->{'links'}.'</td>';
 2277:     my $links_def;
 2278:     foreach my $item (@{$links}) {
 2279:         if (!$is_custom->{$item}) {
 2280:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2281:         }
 2282:     }
 2283:     if ($links_def) {
 2284:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2285:     } else {
 2286:         $datatable .= '<td>&nbsp;</td>';
 2287:     }
 2288:     $datatable .= '<td class="LC_right_item">'.
 2289:                   '<table border="0"><tr>';
 2290:     foreach my $item (@{$links}) {
 2291: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2292:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 2293:         if ($designs->{'links'}{$item}) {
 2294:             $datatable.='&nbsp;';
 2295:         }
 2296:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2297:                       '" /></td>';
 2298:     }
 2299:     $$rowtotal += $itemcount;
 2300:     return $datatable;
 2301: }
 2302: 
 2303: sub logo_display_options {
 2304:     my ($img,$defaults,$designs) = @_;
 2305:     my $checkedon;
 2306:     if (ref($defaults) eq 'HASH') {
 2307:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2308:             if ($defaults->{'showlogo'}{$img}) {
 2309:                 $checkedon = 'checked="checked" ';     
 2310:             }
 2311:         } 
 2312:     }
 2313:     if (ref($designs) eq 'HASH') {
 2314:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2315:             if (defined($designs->{'showlogo'}{$img})) {
 2316:                 if ($designs->{'showlogo'}{$img} == 0) {
 2317:                     $checkedon = '';
 2318:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2319:                     $checkedon = 'checked="checked" ';
 2320:                 }
 2321:             }
 2322:         }
 2323:     }
 2324:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2325:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2326:            &mt('show').'</label>'."\n";
 2327: }
 2328: 
 2329: sub login_header_options  {
 2330:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2331:     my $output = '';
 2332:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2333:         $output .= &mt('Text default(s):').'<br />';
 2334:         if (!$is_custom->{'textcol'}) {
 2335:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2336:                        '&nbsp;&nbsp;&nbsp;';
 2337:         }
 2338:         if (!$is_custom->{'bgcol'}) {
 2339:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2340:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2341:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2342:         }
 2343:         $output .= '<br />';
 2344:     }
 2345:     $output .='<br />';
 2346:     return $output;
 2347: }
 2348: 
 2349: sub login_text_colors {
 2350:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2351:     my $color_menu = '<table border="0"><tr>';
 2352:     foreach my $item (@{$logintext}) {
 2353:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 2354:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2355:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2356:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2357:     }
 2358:     $color_menu .= '</tr></table><br />';
 2359:     return $color_menu;
 2360: }
 2361: 
 2362: sub image_changes {
 2363:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2364:     my $output;
 2365:     if ($img eq 'login') {
 2366:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2367:     } elsif (!$is_custom) {
 2368:         if ($img ne 'domlogo') {
 2369:             $output = &mt('Default image:').'<br />';
 2370:         } else {
 2371:             $output = &mt('Default in use:').'<br />';
 2372:         }
 2373:     }
 2374:     if ($img ne 'login') {
 2375:         if ($img_import) {
 2376:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2377:         }
 2378:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2379:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2380:         if ($is_custom) {
 2381:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2382:                        '<input type="checkbox" name="'.
 2383:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2384:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2385:         } else {
 2386:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 2387:         }
 2388:     }
 2389:     return $output;
 2390: }
 2391: 
 2392: sub print_quotas {
 2393:     my ($dom,$settings,$rowtotal,$action) = @_;
 2394:     my $context;
 2395:     if ($action eq 'quotas') {
 2396:         $context = 'tools';
 2397:     } else {
 2398:         $context = $action;
 2399:     }
 2400:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2401:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2402:     my $typecount = 0;
 2403:     my ($css_class,%titles);
 2404:     if ($context eq 'requestcourses') {
 2405:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 2406:         @options =('norequest','approval','validate','autolimit');
 2407:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2408:         %titles = &courserequest_titles();
 2409:     } elsif ($context eq 'requestauthor') {
 2410:         @usertools = ('author');
 2411:         @options = ('norequest','approval','automatic');
 2412:         %titles = &authorrequest_titles();
 2413:     } else {
 2414:         @usertools = ('aboutme','blog','webdav','portfolio','timezone');
 2415:         %titles = &tool_titles();
 2416:     }
 2417:     if (ref($types) eq 'ARRAY') {
 2418:         foreach my $type (@{$types}) {
 2419:             my ($currdefquota,$currauthorquota);
 2420:             unless (($context eq 'requestcourses') ||
 2421:                     ($context eq 'requestauthor')) {
 2422:                 if (ref($settings) eq 'HASH') {
 2423:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2424:                         $currdefquota = $settings->{defaultquota}->{$type};
 2425:                     } else {
 2426:                         $currdefquota = $settings->{$type};
 2427:                     }
 2428:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2429:                         $currauthorquota = $settings->{authorquota}->{$type};
 2430:                     }
 2431:                 }
 2432:             }
 2433:             if (defined($usertypes->{$type})) {
 2434:                 $typecount ++;
 2435:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2436:                 $datatable .= '<tr'.$css_class.'>'.
 2437:                               '<td>'.$usertypes->{$type}.'</td>'.
 2438:                               '<td class="LC_left_item">';
 2439:                 if ($context eq 'requestcourses') {
 2440:                     $datatable .= '<table><tr>';
 2441:                 }
 2442:                 my %cell;  
 2443:                 foreach my $item (@usertools) {
 2444:                     if ($context eq 'requestcourses') {
 2445:                         my ($curroption,$currlimit);
 2446:                         if (ref($settings) eq 'HASH') {
 2447:                             if (ref($settings->{$item}) eq 'HASH') {
 2448:                                 $curroption = $settings->{$item}->{$type};
 2449:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2450:                                     $currlimit = $1; 
 2451:                                 }
 2452:                             }
 2453:                         }
 2454:                         if (!$curroption) {
 2455:                             $curroption = 'norequest';
 2456:                         }
 2457:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2458:                         foreach my $option (@options) {
 2459:                             my $val = $option;
 2460:                             if ($option eq 'norequest') {
 2461:                                 $val = 0;  
 2462:                             }
 2463:                             if ($option eq 'validate') {
 2464:                                 my $canvalidate = 0;
 2465:                                 if (ref($validations{$item}) eq 'HASH') { 
 2466:                                     if ($validations{$item}{$type}) {
 2467:                                         $canvalidate = 1;
 2468:                                     }
 2469:                                 }
 2470:                                 next if (!$canvalidate);
 2471:                             }
 2472:                             my $checked = '';
 2473:                             if ($option eq $curroption) {
 2474:                                 $checked = ' checked="checked"';
 2475:                             } elsif ($option eq 'autolimit') {
 2476:                                 if ($curroption =~ /^autolimit/) {
 2477:                                     $checked = ' checked="checked"';
 2478:                                 }                       
 2479:                             } 
 2480:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2481:                                   '<input type="radio" name="crsreq_'.$item.
 2482:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2483:                                   $titles{$option}.'</label>';
 2484:                             if ($option eq 'autolimit') {
 2485:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2486:                                                 $item.'_limit_'.$type.'" size="1" '.
 2487:                                                 'value="'.$currlimit.'" />';
 2488:                             }
 2489:                             $cell{$item} .= '</span> ';
 2490:                             if ($option eq 'autolimit') {
 2491:                                 $cell{$item} .= $titles{'unlimited'};
 2492:                             }
 2493:                         }
 2494:                     } elsif ($context eq 'requestauthor') {
 2495:                         my $curroption;
 2496:                         if (ref($settings) eq 'HASH') {
 2497:                             $curroption = $settings->{$type};
 2498:                         }
 2499:                         if (!$curroption) {
 2500:                             $curroption = 'norequest';
 2501:                         }
 2502:                         foreach my $option (@options) {
 2503:                             my $val = $option;
 2504:                             if ($option eq 'norequest') {
 2505:                                 $val = 0;
 2506:                             }
 2507:                             my $checked = '';
 2508:                             if ($option eq $curroption) {
 2509:                                 $checked = ' checked="checked"';
 2510:                             }
 2511:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2512:                                   '<input type="radio" name="authorreq_'.$type.
 2513:                                   '" value="'.$val.'"'.$checked.' />'.
 2514:                                   $titles{$option}.'</label></span>&nbsp; ';
 2515:                         }
 2516:                     } else {
 2517:                         my $checked = 'checked="checked" ';
 2518:                         if ($item eq 'timezone') {
 2519:                             $checked = '';
 2520:                         }
 2521:                         if (ref($settings) eq 'HASH') {
 2522:                             if (ref($settings->{$item}) eq 'HASH') {
 2523:                                 if (!$settings->{$item}->{$type}) {
 2524:                                     $checked = '';
 2525:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2526:                                     $checked =  'checked="checked" ';
 2527:                                 }
 2528:                             }
 2529:                         }
 2530:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2531:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2532:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2533:                                       '</label></span>&nbsp; ';
 2534:                     }
 2535:                 }
 2536:                 if ($context eq 'requestcourses') {
 2537:                     $datatable .= '</tr><tr>';
 2538:                     foreach my $item (@usertools) {
 2539:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2540:                     }
 2541:                     $datatable .= '</tr></table>';
 2542:                 }
 2543:                 $datatable .= '</td>';
 2544:                 unless (($context eq 'requestcourses') ||
 2545:                         ($context eq 'requestauthor')) {
 2546:                     $datatable .= 
 2547:                               '<td class="LC_right_item">'.
 2548:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2549:                               '<input type="text" name="quota_'.$type.
 2550:                               '" value="'.$currdefquota.
 2551:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2552:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2553:                               '<input type="text" name="authorquota_'.$type.
 2554:                               '" value="'.$currauthorquota.
 2555:                               '" size="5" /></span></td>';
 2556:                 }
 2557:                 $datatable .= '</tr>';
 2558:             }
 2559:         }
 2560:     }
 2561:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2562:         $defaultquota = '20';
 2563:         $authorquota = '500';
 2564:         if (ref($settings) eq 'HASH') {
 2565:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2566:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2567:             } elsif (defined($settings->{'default'})) {
 2568:                 $defaultquota = $settings->{'default'};
 2569:             }
 2570:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2571:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2572:             }
 2573:         }
 2574:     }
 2575:     $typecount ++;
 2576:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2577:     $datatable .= '<tr'.$css_class.'>'.
 2578:                   '<td>'.$othertitle.'</td>'.
 2579:                   '<td class="LC_left_item">';
 2580:     if ($context eq 'requestcourses') {
 2581:         $datatable .= '<table><tr>';
 2582:     }
 2583:     my %defcell;
 2584:     foreach my $item (@usertools) {
 2585:         if ($context eq 'requestcourses') {
 2586:             my ($curroption,$currlimit);
 2587:             if (ref($settings) eq 'HASH') {
 2588:                 if (ref($settings->{$item}) eq 'HASH') {
 2589:                     $curroption = $settings->{$item}->{'default'};
 2590:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2591:                         $currlimit = $1;
 2592:                     }
 2593:                 }
 2594:             }
 2595:             if (!$curroption) {
 2596:                 $curroption = 'norequest';
 2597:             }
 2598:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2599:             foreach my $option (@options) {
 2600:                 my $val = $option;
 2601:                 if ($option eq 'norequest') {
 2602:                     $val = 0;
 2603:                 }
 2604:                 if ($option eq 'validate') {
 2605:                     my $canvalidate = 0;
 2606:                     if (ref($validations{$item}) eq 'HASH') {
 2607:                         if ($validations{$item}{'default'}) {
 2608:                             $canvalidate = 1;
 2609:                         }
 2610:                     }
 2611:                     next if (!$canvalidate);
 2612:                 }
 2613:                 my $checked = '';
 2614:                 if ($option eq $curroption) {
 2615:                     $checked = ' checked="checked"';
 2616:                 } elsif ($option eq 'autolimit') {
 2617:                     if ($curroption =~ /^autolimit/) {
 2618:                         $checked = ' checked="checked"';
 2619:                     }
 2620:                 }
 2621:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2622:                                   '<input type="radio" name="crsreq_'.$item.
 2623:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2624:                                   $titles{$option}.'</label>';
 2625:                 if ($option eq 'autolimit') {
 2626:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2627:                                        $item.'_limit_default" size="1" '.
 2628:                                        'value="'.$currlimit.'" />';
 2629:                 }
 2630:                 $defcell{$item} .= '</span> ';
 2631:                 if ($option eq 'autolimit') {
 2632:                     $defcell{$item} .= $titles{'unlimited'};
 2633:                 }
 2634:             }
 2635:         } elsif ($context eq 'requestauthor') {
 2636:             my $curroption;
 2637:             if (ref($settings) eq 'HASH') {
 2638:                 $curroption = $settings->{'default'};
 2639:             }
 2640:             if (!$curroption) {
 2641:                 $curroption = 'norequest';
 2642:             }
 2643:             foreach my $option (@options) {
 2644:                 my $val = $option;
 2645:                 if ($option eq 'norequest') {
 2646:                     $val = 0;
 2647:                 }
 2648:                 my $checked = '';
 2649:                 if ($option eq $curroption) {
 2650:                     $checked = ' checked="checked"';
 2651:                 }
 2652:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2653:                               '<input type="radio" name="authorreq_default"'.
 2654:                               ' value="'.$val.'"'.$checked.' />'.
 2655:                               $titles{$option}.'</label></span>&nbsp; ';
 2656:             }
 2657:         } else {
 2658:             my $checked = 'checked="checked" ';
 2659:             if (ref($settings) eq 'HASH') {
 2660:                 if (ref($settings->{$item}) eq 'HASH') {
 2661:                     if ($settings->{$item}->{'default'} == 0) {
 2662:                         $checked = '';
 2663:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2664:                         $checked = 'checked="checked" ';
 2665:                     }
 2666:                 }
 2667:             }
 2668:             $datatable .= '<span class="LC_nobreak"><label>'.
 2669:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2670:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2671:                           '</label></span>&nbsp; ';
 2672:         }
 2673:     }
 2674:     if ($context eq 'requestcourses') {
 2675:         $datatable .= '</tr><tr>';
 2676:         foreach my $item (@usertools) {
 2677:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2678:         }
 2679:         $datatable .= '</tr></table>';
 2680:     }
 2681:     $datatable .= '</td>';
 2682:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2683:         $datatable .= '<td class="LC_right_item">'.
 2684:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2685:                       '<input type="text" name="defaultquota" value="'.
 2686:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2687:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2688:                       '<input type="text" name="authorquota" value="'.
 2689:                       $authorquota.'" size="5" /></span></td>';
 2690:     }
 2691:     $datatable .= '</tr>';
 2692:     $typecount ++;
 2693:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2694:     $datatable .= '<tr'.$css_class.'>'.
 2695:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2696:     if ($context eq 'requestcourses') {
 2697:         $datatable .= &mt('(overrides affiliation, if set)').
 2698:                       '</td>'.
 2699:                       '<td class="LC_left_item">'.
 2700:                       '<table><tr>';
 2701:     } else {
 2702:         $datatable .= &mt('(overrides affiliation, if checked)').
 2703:                       '</td>'.
 2704:                       '<td class="LC_left_item" colspan="2">'.
 2705:                       '<br />';
 2706:     }
 2707:     my %advcell;
 2708:     foreach my $item (@usertools) {
 2709:         if ($context eq 'requestcourses') {
 2710:             my ($curroption,$currlimit);
 2711:             if (ref($settings) eq 'HASH') {
 2712:                 if (ref($settings->{$item}) eq 'HASH') {
 2713:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2714:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2715:                         $currlimit = $1;
 2716:                     }
 2717:                 }
 2718:             }
 2719:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2720:             my $checked = '';
 2721:             if ($curroption eq '') {
 2722:                 $checked = ' checked="checked"';
 2723:             }
 2724:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2725:                                '<input type="radio" name="crsreq_'.$item.
 2726:                                '__LC_adv" value=""'.$checked.' />'.
 2727:                                &mt('No override set').'</label></span>&nbsp; ';
 2728:             foreach my $option (@options) {
 2729:                 my $val = $option;
 2730:                 if ($option eq 'norequest') {
 2731:                     $val = 0;
 2732:                 }
 2733:                 if ($option eq 'validate') {
 2734:                     my $canvalidate = 0;
 2735:                     if (ref($validations{$item}) eq 'HASH') {
 2736:                         if ($validations{$item}{'_LC_adv'}) {
 2737:                             $canvalidate = 1;
 2738:                         }
 2739:                     }
 2740:                     next if (!$canvalidate);
 2741:                 }
 2742:                 my $checked = '';
 2743:                 if ($val eq $curroption) {
 2744:                     $checked = ' checked="checked"';
 2745:                 } elsif ($option eq 'autolimit') {
 2746:                     if ($curroption =~ /^autolimit/) {
 2747:                         $checked = ' checked="checked"';
 2748:                     }
 2749:                 }
 2750:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2751:                                   '<input type="radio" name="crsreq_'.$item.
 2752:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2753:                                   $titles{$option}.'</label>';
 2754:                 if ($option eq 'autolimit') {
 2755:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2756:                                        $item.'_limit__LC_adv" size="1" '.
 2757:                                        'value="'.$currlimit.'" />';
 2758:                 }
 2759:                 $advcell{$item} .= '</span> ';
 2760:                 if ($option eq 'autolimit') {
 2761:                     $advcell{$item} .= $titles{'unlimited'};
 2762:                 }
 2763:             }
 2764:         } elsif ($context eq 'requestauthor') {
 2765:             my $curroption;
 2766:             if (ref($settings) eq 'HASH') {
 2767:                 $curroption = $settings->{'_LC_adv'};
 2768:             }
 2769:             my $checked = '';
 2770:             if ($curroption eq '') {
 2771:                 $checked = ' checked="checked"';
 2772:             }
 2773:             $datatable .= '<span class="LC_nobreak"><label>'.
 2774:                           '<input type="radio" name="authorreq__LC_adv"'.
 2775:                           ' value=""'.$checked.' />'.
 2776:                           &mt('No override set').'</label></span>&nbsp; ';
 2777:             foreach my $option (@options) {
 2778:                 my $val = $option;
 2779:                 if ($option eq 'norequest') {
 2780:                     $val = 0;
 2781:                 }
 2782:                 my $checked = '';
 2783:                 if ($val eq $curroption) {
 2784:                     $checked = ' checked="checked"';
 2785:                 }
 2786:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2787:                               '<input type="radio" name="authorreq__LC_adv"'.
 2788:                               ' value="'.$val.'"'.$checked.' />'.
 2789:                               $titles{$option}.'</label></span>&nbsp; ';
 2790:             }
 2791:         } else {
 2792:             my $checked = 'checked="checked" ';
 2793:             if (ref($settings) eq 'HASH') {
 2794:                 if (ref($settings->{$item}) eq 'HASH') {
 2795:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2796:                         $checked = '';
 2797:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2798:                         $checked = 'checked="checked" ';
 2799:                     }
 2800:                 }
 2801:             }
 2802:             $datatable .= '<span class="LC_nobreak"><label>'.
 2803:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2804:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2805:                           '</label></span>&nbsp; ';
 2806:         }
 2807:     }
 2808:     if ($context eq 'requestcourses') {
 2809:         $datatable .= '</tr><tr>';
 2810:         foreach my $item (@usertools) {
 2811:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2812:         }
 2813:         $datatable .= '</tr></table>';
 2814:     }
 2815:     $datatable .= '</td></tr>';
 2816:     $$rowtotal += $typecount;
 2817:     return $datatable;
 2818: }
 2819: 
 2820: sub print_requestmail {
 2821:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2822:     my ($now,$datatable,%currapp);
 2823:     $now = time;
 2824:     if (ref($settings) eq 'HASH') {
 2825:         if (ref($settings->{'notify'}) eq 'HASH') {
 2826:             if ($settings->{'notify'}{'approval'} ne '') {
 2827:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2828:             }
 2829:         }
 2830:     }
 2831:     my $numinrow = 2;
 2832:     my $css_class;
 2833:     if ($$rowtotal%2) {
 2834:         $css_class = 'LC_odd_row';
 2835:     }
 2836:     if ($customcss) {
 2837:         $css_class .= " $customcss";
 2838:     }
 2839:     $css_class =~ s/^\s+//;
 2840:     if ($css_class) {
 2841:         $css_class = ' class="'.$css_class.'"';
 2842:     }
 2843:     if ($rowstyle) {
 2844:         $css_class .= ' style="'.$rowstyle.'"';
 2845:     }
 2846:     my $text;
 2847:     if ($action eq 'requestcourses') {
 2848:         $text = &mt('Receive notification of course requests requiring approval');
 2849:     } elsif ($action eq 'requestauthor') {
 2850:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2851:     } else {
 2852:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2853:     }
 2854:     $datatable = '<tr'.$css_class.'>'.
 2855:                  ' <td>'.$text.'</td>'.
 2856:                  ' <td class="LC_left_item">';
 2857:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2858:                                                  $action.'notifyapproval',%currapp);
 2859:     if ($numdc > 0) {
 2860:         $datatable .= $table;
 2861:     } else {
 2862:         $datatable .= &mt('There are no active Domain Coordinators');
 2863:     }
 2864:     $datatable .='</td></tr>';
 2865:     return $datatable;
 2866: }
 2867: 
 2868: sub print_studentcode {
 2869:     my ($settings,$rowtotal) = @_;
 2870:     my $rownum = 0; 
 2871:     my ($output,%current);
 2872:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2873:     if (ref($settings) eq 'HASH') {
 2874:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2875:             foreach my $type (@crstypes) {
 2876:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2877:             }
 2878:         }
 2879:     }
 2880:     $output .= '<tr>'.
 2881:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2882:                '<td class="LC_left_item">';
 2883:     foreach my $type (@crstypes) {
 2884:         my $check = ' ';
 2885:         if ($current{$type}) {
 2886:             $check = ' checked="checked" ';
 2887:         }
 2888:         $output .= '<span class="LC_nobreak"><label>'.
 2889:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2890:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2891:     }
 2892:     $output .= '</td></tr>';
 2893:     $$rowtotal ++;
 2894:     return $output;
 2895: }
 2896: 
 2897: sub print_textbookcourses {
 2898:     my ($dom,$type,$settings,$rowtotal) = @_;
 2899:     my $rownum = 0;
 2900:     my $css_class;
 2901:     my $itemcount = 1;
 2902:     my $maxnum = 0;
 2903:     my $bookshash;
 2904:     if (ref($settings) eq 'HASH') {
 2905:         $bookshash = $settings->{$type};
 2906:     }
 2907:     my %ordered;
 2908:     if (ref($bookshash) eq 'HASH') {
 2909:         foreach my $item (keys(%{$bookshash})) {
 2910:             if (ref($bookshash->{$item}) eq 'HASH') {
 2911:                 my $num = $bookshash->{$item}{'order'};
 2912:                 $ordered{$num} = $item;
 2913:             }
 2914:         }
 2915:     }
 2916:     my $confname = $dom.'-domainconfig';
 2917:     my $switchserver = &check_switchserver($dom,$confname);
 2918:     my $maxnum = scalar(keys(%ordered));
 2919:     my $datatable;
 2920:     if (keys(%ordered)) {
 2921:         my @items = sort { $a <=> $b } keys(%ordered);
 2922:         for (my $i=0; $i<@items; $i++) {
 2923:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2924:             my $key = $ordered{$items[$i]};
 2925:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2926:             my $coursetitle = $coursehash{'description'};
 2927:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2928:             if (ref($bookshash->{$key}) eq 'HASH') {
 2929:                 $subject = $bookshash->{$key}->{'subject'};
 2930:                 $title = $bookshash->{$key}->{'title'};
 2931:                 if ($type eq 'textbooks') {
 2932:                     $publisher = $bookshash->{$key}->{'publisher'};
 2933:                     $author = $bookshash->{$key}->{'author'};
 2934:                     $image = $bookshash->{$key}->{'image'};
 2935:                     if ($image ne '') {
 2936:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2937:                         my $imagethumb = "$path/tn-".$imagefile;
 2938:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2939:                     }
 2940:                 }
 2941:             }
 2942:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2943:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2944:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2945:             for (my $k=0; $k<=$maxnum; $k++) {
 2946:                 my $vpos = $k+1;
 2947:                 my $selstr;
 2948:                 if ($k == $i) {
 2949:                     $selstr = ' selected="selected" ';
 2950:                 }
 2951:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2952:             }
 2953:             $datatable .= '</select>'.('&nbsp;'x2).
 2954:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2955:                 &mt('Delete?').'</label></span></td>'.
 2956:                 '<td colspan="2">'.
 2957:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2958:                 ('&nbsp;'x2).
 2959:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2960:             if ($type eq 'textbooks') {
 2961:                 $datatable .= ('&nbsp;'x2).
 2962:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2963:                               ('&nbsp;'x2).
 2964:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2965:                               ('&nbsp;'x2).
 2966:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2967:                 if ($image) {
 2968:                     $datatable .= $imgsrc.
 2969:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2970:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2971:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2972:                 }
 2973:                 if ($switchserver) {
 2974:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2975:                 } else {
 2976:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2977:                 }
 2978:             }
 2979:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2980:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2981:                           $coursetitle.'</span></td></tr>'."\n";
 2982:             $itemcount ++;
 2983:         }
 2984:     }
 2985:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2986:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2987:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2988:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2989:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2990:     for (my $k=0; $k<$maxnum+1; $k++) {
 2991:         my $vpos = $k+1;
 2992:         my $selstr;
 2993:         if ($k == $maxnum) {
 2994:             $selstr = ' selected="selected" ';
 2995:         }
 2996:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2997:     }
 2998:     $datatable .= '</select>&nbsp;'."\n".
 2999:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 3000:                   '<td colspan="2">'.
 3001:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 3002:                   ('&nbsp;'x2).
 3003:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 3004:                   ('&nbsp;'x2);
 3005:     if ($type eq 'textbooks') {
 3006:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 3007:                       ('&nbsp;'x2).
 3008:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 3009:                       ('&nbsp;'x2).
 3010:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 3011:         if ($switchserver) {
 3012:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 3013:         } else {
 3014:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 3015:         }
 3016:         $datatable .= '</span>'."\n";
 3017:     }
 3018:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 3019:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 3020:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 3021:                   &Apache::loncommon::selectcourse_link
 3022:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 3023:                   '</span></td>'."\n".
 3024:                   '</tr>'."\n";
 3025:     $itemcount ++;
 3026:     return $datatable;
 3027: }
 3028: 
 3029: sub textbookcourses_javascript {
 3030:     my ($settings) = @_;
 3031:     return unless(ref($settings) eq 'HASH');
 3032:     my (%ordered,%total,%jstext);
 3033:     foreach my $type ('textbooks','templates') {
 3034:         $total{$type} = 0;
 3035:         if (ref($settings->{$type}) eq 'HASH') {
 3036:             foreach my $item (keys(%{$settings->{$type}})) {
 3037:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 3038:                     my $num = $settings->{$type}->{$item}{'order'};
 3039:                     $ordered{$type}{$num} = $item;
 3040:                 }
 3041:             }
 3042:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 3043:         }
 3044:         my @jsarray = ();
 3045:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 3046:             push(@jsarray,$ordered{$type}{$item});
 3047:         }
 3048:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 3049:     }
 3050:     return <<"ENDSCRIPT";
 3051: <script type="text/javascript">
 3052: // <![CDATA[
 3053: function reorderBooks(form,item,caller) {
 3054:     var changedVal;
 3055: $jstext{'textbooks'};
 3056: $jstext{'templates'};
 3057:     var newpos;
 3058:     var maxh;
 3059:     if (caller == 'textbooks') {  
 3060:         newpos = 'textbooks_addbook_pos';
 3061:         maxh = 1 + $total{'textbooks'};
 3062:     } else {
 3063:         newpos = 'templates_addbook_pos';
 3064:         maxh = 1 + $total{'templates'};
 3065:     }
 3066:     var current = new Array;
 3067:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3068:     if (item == newpos) {
 3069:         changedVal = newitemVal;
 3070:     } else {
 3071:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3072:         current[newitemVal] = newpos;
 3073:     }
 3074:     if (caller == 'textbooks') {
 3075:         for (var i=0; i<textbooks.length; i++) {
 3076:             var elementName = 'textbooks_'+textbooks[i];
 3077:             if (elementName != item) {
 3078:                 if (form.elements[elementName]) {
 3079:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3080:                     current[currVal] = elementName;
 3081:                 }
 3082:             }
 3083:         }
 3084:     }
 3085:     if (caller == 'templates') {
 3086:         for (var i=0; i<templates.length; i++) {
 3087:             var elementName = 'templates_'+templates[i];
 3088:             if (elementName != item) {
 3089:                 if (form.elements[elementName]) {
 3090:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3091:                     current[currVal] = elementName;
 3092:                 }
 3093:             }
 3094:         }
 3095:     }
 3096:     var oldVal;
 3097:     for (var j=0; j<maxh; j++) {
 3098:         if (current[j] == undefined) {
 3099:             oldVal = j;
 3100:         }
 3101:     }
 3102:     if (oldVal < changedVal) {
 3103:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3104:            var elementName = current[k];
 3105:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3106:         }
 3107:     } else {
 3108:         for (var k=changedVal; k<oldVal; k++) {
 3109:             var elementName = current[k];
 3110:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3111:         }
 3112:     }
 3113:     return;
 3114: }
 3115: 
 3116: // ]]>
 3117: </script>
 3118: 
 3119: ENDSCRIPT
 3120: }
 3121: 
 3122: sub ltitools_javascript {
 3123:     my ($settings) = @_;
 3124:     my $togglejs = &ltitools_toggle_js();
 3125:     unless (ref($settings) eq 'HASH') {
 3126:         return $togglejs;
 3127:     }
 3128:     my (%ordered,$total,%jstext);
 3129:     $total = 0;
 3130:     foreach my $item (keys(%{$settings})) {
 3131:         if (ref($settings->{$item}) eq 'HASH') {
 3132:             my $num = $settings->{$item}{'order'};
 3133:             $ordered{$num} = $item;
 3134:         }
 3135:     }
 3136:     $total = scalar(keys(%{$settings}));
 3137:     my @jsarray = ();
 3138:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3139:         push(@jsarray,$ordered{$item});
 3140:     }
 3141:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 3142:     return <<"ENDSCRIPT";
 3143: <script type="text/javascript">
 3144: // <![CDATA[
 3145: function reorderLTITools(form,item) {
 3146:     var changedVal;
 3147: $jstext
 3148:     var newpos = 'ltitools_add_pos';
 3149:     var maxh = 1 + $total;
 3150:     var current = new Array;
 3151:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3152:     if (item == newpos) {
 3153:         changedVal = newitemVal;
 3154:     } else {
 3155:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3156:         current[newitemVal] = newpos;
 3157:     }
 3158:     for (var i=0; i<ltitools.length; i++) {
 3159:         var elementName = 'ltitools_'+ltitools[i];
 3160:         if (elementName != item) {
 3161:             if (form.elements[elementName]) {
 3162:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3163:                 current[currVal] = elementName;
 3164:             }
 3165:         }
 3166:     }
 3167:     var oldVal;
 3168:     for (var j=0; j<maxh; j++) {
 3169:         if (current[j] == undefined) {
 3170:             oldVal = j;
 3171:         }
 3172:     }
 3173:     if (oldVal < changedVal) {
 3174:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3175:            var elementName = current[k];
 3176:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3177:         }
 3178:     } else {
 3179:         for (var k=changedVal; k<oldVal; k++) {
 3180:             var elementName = current[k];
 3181:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3182:         }
 3183:     }
 3184:     return;
 3185: }
 3186: 
 3187: // ]]>
 3188: </script>
 3189: 
 3190: $togglejs
 3191: 
 3192: ENDSCRIPT
 3193: }
 3194: 
 3195: sub ltitools_toggle_js {
 3196:     return <<"ENDSCRIPT";
 3197: <script type="text/javascript">
 3198: // <![CDATA[
 3199: 
 3200: function toggleLTITools(form,setting,item) {
 3201:     var radioname = '';
 3202:     var divid = '';
 3203:     if ((setting == 'passback') || (setting == 'roster')) {
 3204:         radioname = 'ltitools_'+setting+'_'+item;
 3205:         divid = 'ltitools_'+setting+'time_'+item;
 3206:         var num = form.elements[radioname].length;
 3207:         if (num) {
 3208:             var setvis = '';
 3209:             for (var i=0; i<num; i++) {
 3210:                 if (form.elements[radioname][i].checked) {
 3211:                     if (form.elements[radioname][i].value == '1') {
 3212:                         if (document.getElementById(divid)) {
 3213:                             document.getElementById(divid).style.display = 'inline-block';
 3214:                         }
 3215:                         setvis = 1;
 3216:                     }
 3217:                     break;
 3218:                 }
 3219:             }
 3220:         }
 3221:         if (!setvis) {
 3222:             if (document.getElementById(divid)) {
 3223:                 document.getElementById(divid).style.display = 'none';
 3224:             }
 3225:         }
 3226:     }
 3227:     if (setting == 'user') {
 3228:         divid = 'ltitools_'+setting+'_div_'+item;
 3229:         var checkid = 'ltitools_'+setting+'_field_'+item;
 3230:         if (document.getElementById(divid)) {
 3231:             if (document.getElementById(checkid)) {
 3232:                 if (document.getElementById(checkid).checked) {
 3233:                     document.getElementById(divid).style.display = 'inline-block';
 3234:                 } else {
 3235:                     document.getElementById(divid).style.display = 'none';
 3236:                 }
 3237:             }
 3238:         }
 3239:     }
 3240:     return;
 3241: }
 3242: // ]]>
 3243: </script>
 3244: 
 3245: ENDSCRIPT
 3246: }
 3247: 
 3248: sub wafproxy_javascript {
 3249:     my ($dom) = @_;
 3250:     return <<"ENDSCRIPT";
 3251: <script type="text/javascript">
 3252: // <![CDATA[
 3253: function updateWAF() {
 3254:     if (document.getElementById('wafproxy_remoteip')) {
 3255:         var wafremote = 0;
 3256:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 3257:             wafremote = 1;
 3258:         }
 3259:         var fields = new Array('header','trust');
 3260:         for (var i=0; i<fields.length; i++) {
 3261:             if (document.getElementById('wafproxy_'+fields[i])) {
 3262:                 if (wafremote == 1) {
 3263:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 3264:                 }
 3265:                 else {
 3266:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 3267:                 }
 3268:             }
 3269:         }
 3270:         if (document.getElementById('wafproxyranges_$dom')) {
 3271:             if (wafremote == 1) {
 3272:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3273:             } else {
 3274:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3275:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 3276:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 3277:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3278:                         }
 3279:                     }
 3280:                 }
 3281:             }
 3282:         }
 3283:     }
 3284:     return;
 3285: }
 3286: 
 3287: function checkWAF() {
 3288:     if (document.getElementById('wafproxy_remoteip')) {
 3289:         var wafvpn = 0;
 3290:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3291:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3292:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3293:                     wafvpn = 1;
 3294:                 }
 3295:                 break;
 3296:             }
 3297:         }
 3298:         var vpn = new Array('vpnint','vpnext');
 3299:         for (var i=0; i<vpn.length; i++) {
 3300:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3301:                 if (wafvpn == 1) {
 3302:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3303:                 }
 3304:                 else {
 3305:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3306:                 }
 3307:             }
 3308:         }
 3309:         if (document.getElementById('wafproxyranges_$dom')) {
 3310:             if (wafvpn == 1) {
 3311:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3312:             }
 3313:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3314:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3315:             }
 3316:         }
 3317:     }
 3318:     return;
 3319: }
 3320: 
 3321: function toggleWAF() {
 3322:     if (document.getElementById('wafproxy_table')) {
 3323:         var wafproxy = 0;
 3324:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3325:              if (document.display.wafproxy_${dom}[i].checked) {
 3326:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3327:                      wafproxy = 1;
 3328:                      break;
 3329:                 }
 3330:             }
 3331:         }
 3332:         if (wafproxy == 1) {
 3333:             document.getElementById('wafproxy_table').style.display='inline';
 3334:         }
 3335:         else {
 3336:            document.getElementById('wafproxy_table').style.display='none';
 3337:         }
 3338:         if (document.getElementById('wafproxyrow_${dom}')) {
 3339:             if (wafproxy == 1) {
 3340:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3341:             }
 3342:             else {
 3343:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3344:             }
 3345:         }
 3346:         if (document.getElementById('nowafproxyrow_$dom')) {
 3347:             if (wafproxy == 1) {
 3348:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3349:             }
 3350:             else {
 3351:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3352:             }
 3353:         }
 3354:     }
 3355:     return;
 3356: }
 3357: // ]]>
 3358: </script>
 3359: 
 3360: ENDSCRIPT
 3361: }
 3362: 
 3363: sub proctoring_javascript {
 3364:     my ($settings) = @_;
 3365:     my (%ordered,$total,%jstext);
 3366:     $total = 0;
 3367:     if (ref($settings) eq 'HASH') {
 3368:         foreach my $item (keys(%{$settings})) {
 3369:             if (ref($settings->{$item}) eq 'HASH') {
 3370:                 my $num = $settings->{$item}{'order'};
 3371:                 $ordered{$num} = $item;
 3372:             }
 3373:         }
 3374:         $total = scalar(keys(%{$settings}));
 3375:     } else {
 3376:         %ordered = (
 3377:                        0 => 'proctorio',
 3378:                        1 => 'examity',
 3379:                    );
 3380:         $total = 2; 
 3381:     }
 3382:     my @jsarray = ();
 3383:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3384:         push(@jsarray,$ordered{$item});
 3385:     }
 3386:     my $jstext = '    var proctors = Array('."'".join("','",@jsarray)."'".');'."\n";
 3387:     return <<"ENDSCRIPT";
 3388: <script type="text/javascript">
 3389: // <![CDATA[
 3390: function reorderProctoring(form,item) {
 3391:     var changedVal;
 3392: $jstext
 3393:     var maxh = $total;
 3394:     var current = new Array;
 3395:     var changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3396:     for (var i=0; i<proctors.length; i++) {
 3397:         var elementName = 'proctoring_pos_'+proctors[i];
 3398:         if (elementName != item) {
 3399:             if (form.elements[elementName]) {
 3400:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3401:                 current[currVal] = elementName;
 3402:             }
 3403:         }
 3404:     }
 3405:     var oldVal;
 3406:     for (var j=0; j<maxh; j++) {
 3407:         if (current[j] == undefined) {
 3408:             oldVal = j;
 3409:         }
 3410:     }
 3411:     if (oldVal < changedVal) {
 3412:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3413:            var elementName = current[k];
 3414:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3415:         }
 3416:     } else {
 3417:         for (var k=changedVal; k<oldVal; k++) {
 3418:             var elementName = current[k];
 3419:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3420:         }
 3421:     }
 3422:     return;
 3423: }
 3424: 
 3425: function toggleProctoring(form,item) {
 3426:     var fieldsets = document.getElementsByClassName('proctoring_'+item);
 3427:     if (fieldsets.length) {
 3428:         var radioname = 'proctoring_available_'+item;
 3429:         var num = form.elements[radioname].length;
 3430:         if (num) {
 3431:             var setvis = '';
 3432:             for (var i=0; i<num; i++) {
 3433:                 if (form.elements[radioname][i].checked) {
 3434:                     if (form.elements[radioname][i].value == '1') {
 3435:                        setvis = 1;
 3436:                        break;
 3437:                     }
 3438:                 }
 3439:             }
 3440:             for (var j=0; j<fieldsets.length; j++) {
 3441:                 if (setvis) {
 3442:                     fieldsets[j].style.display = 'block';
 3443:                 } else {
 3444:                     fieldsets[j].style.display = 'none';
 3445:                 }
 3446:             }
 3447:         }
 3448:     }
 3449:     return;
 3450: }
 3451: 
 3452: // ]]>
 3453: </script>
 3454: 
 3455: ENDSCRIPT
 3456: }
 3457: 
 3458: 
 3459: sub lti_javascript {
 3460:     my ($dom,$settings) = @_;
 3461:     my $togglejs = &lti_toggle_js($dom);
 3462:     my $linkprot_js = &Apache::courseprefs::linkprot_javascript();
 3463:     unless (ref($settings) eq 'HASH') {
 3464:         return $togglejs.'
 3465: <script type="text/javascript">
 3466: // <![CDATA[
 3467: 
 3468: '.$linkprot_js.'
 3469: 
 3470: // ]]>
 3471: </script>
 3472: ';
 3473:     }
 3474:     my (%ordered,$total,%jstext);
 3475:     $total = scalar(keys(%{$settings}));
 3476:     foreach my $item (keys(%{$settings})) {
 3477:         if (ref($settings->{$item}) eq 'HASH') {
 3478:             my $num = $settings->{$item}{'order'};
 3479:             if ($num eq '') {
 3480:                 $num = $total - 1;
 3481:             }
 3482:             $ordered{$num} = $item;
 3483:         }
 3484:     }
 3485:     my @jsarray = ();
 3486:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3487:         push(@jsarray,$ordered{$item});
 3488:     }
 3489:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3490:     return <<"ENDSCRIPT";
 3491: <script type="text/javascript">
 3492: // <![CDATA[
 3493: function reorderLTI(form,item) {
 3494:     var changedVal;
 3495: $jstext
 3496:     var newpos = 'lti_pos_add';
 3497:     var maxh = 1 + $total;
 3498:     var current = new Array;
 3499:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3500:     if (item == newpos) {
 3501:         changedVal = newitemVal;
 3502:     } else {
 3503:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3504:         current[newitemVal] = newpos;
 3505:     }
 3506:     for (var i=0; i<lti.length; i++) {
 3507:         var elementName = 'lti_pos_'+lti[i];
 3508:         if (elementName != item) {
 3509:             if (form.elements[elementName]) {
 3510:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3511:                 current[currVal] = elementName;
 3512:             }
 3513:         }
 3514:     }
 3515:     var oldVal;
 3516:     for (var j=0; j<maxh; j++) {
 3517:         if (current[j] == undefined) {
 3518:             oldVal = j;
 3519:         }
 3520:     }
 3521:     if (oldVal < changedVal) {
 3522:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3523:            var elementName = current[k];
 3524:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3525:         }
 3526:     } else {
 3527:         for (var k=changedVal; k<oldVal; k++) {
 3528:             var elementName = current[k];
 3529:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3530:         }
 3531:     }
 3532:     return;
 3533: }
 3534: 
 3535: $linkprot_js
 3536: 
 3537: // ]]>
 3538: </script>
 3539: 
 3540: $togglejs
 3541: 
 3542: ENDSCRIPT
 3543: }
 3544: 
 3545: sub lti_toggle_js {
 3546:     my ($dom) = @_;
 3547:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3548:                             localauth => 'Local auth argument',
 3549:                             krb       => 'Kerberos domain',
 3550:                          );
 3551:     my $crsincalert = &mt('"User\'s identity sent" needs to be set to "Yes" first,[_1] before setting "Course\'s identity sent" to "Yes"',"\n");
 3552:     &js_escape(\$crsincalert);
 3553:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 3554:     my $primary = &Apache::lonnet::domain($dom,'primary');
 3555:     my $course_servers = "'".join("','",keys(%servers))."'";
 3556:     return <<"ENDSCRIPT";
 3557: <script type="text/javascript">
 3558: // <![CDATA[
 3559: 
 3560: function toggleLTI(form,setting,item) {
 3561:     if ((setting == 'requser') || (setting == 'crsinc')) {
 3562:         var usrfieldsets = document.getElementsByClassName('ltioption_usr_'+item);
 3563:         var setvis = '';
 3564:         var radioname = 'lti_requser_'+item;
 3565:         var num = form.elements[radioname].length;
 3566:         if (num) {
 3567:             for (var i=0; i<num; i++) {
 3568:                 if (form.elements[radioname][i].checked) {
 3569:                     if (form.elements[radioname][i].value == '1') {
 3570:                         setvis = 1;
 3571:                         break;
 3572:                     }
 3573:                 }
 3574:             }
 3575:         }
 3576:         if (usrfieldsets.length) {
 3577:             for (var j=0; j<usrfieldsets.length; j++) {
 3578:                 if (setvis) {
 3579:                     usrfieldsets[j].style.display = 'block';
 3580:                 } else {
 3581:                     usrfieldsets[j].style.display = 'none';
 3582:                 }
 3583:             }
 3584:         }
 3585:         var crsfieldsets = document.getElementsByClassName('ltioption_crs_'+item);
 3586:         if (crsfieldsets.length) {
 3587:             radioname = 'lti_crsinc_'+item;
 3588:             var num = form.elements[radioname].length;
 3589:             if (num) {
 3590:                 var crsvis = '';
 3591:                 for (var i=0; i<num; i++) {
 3592:                     if (form.elements[radioname][i].checked) {
 3593:                         if (form.elements[radioname][i].value == '1') {
 3594:                             if (setvis == '') {
 3595:                                 if (setting == 'crsinc'){
 3596:                                     alert("$crsincalert");
 3597:                                     form.elements[radioname][0].checked = true;
 3598:                                 }
 3599:                             } else {
 3600:                                 crsvis = 1;
 3601:                             }
 3602:                             break;
 3603:                         }
 3604:                     }
 3605:                 }
 3606:                 setvis = crsvis;
 3607:             }
 3608:             for (var j=0; j<crsfieldsets.length; j++) {
 3609:                 if (setvis) {
 3610:                     crsfieldsets[j].style.display = 'block';
 3611:                 } else {
 3612:                     crsfieldsets[j].style.display = 'none';
 3613:                 }
 3614:             }
 3615:         }
 3616:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3617:         var radioname = '';
 3618:         var divid = '';
 3619:         if (setting == 'user') {
 3620:             radioname = 'lti_mapuser_'+item;
 3621:             divid = 'lti_userfield_'+item;
 3622:         } else if (setting == 'crs') {
 3623:             radioname = 'lti_mapcrs_'+item;
 3624:             divid = 'lti_crsfield_'+item;
 3625:         } else if (setting == 'callback') {
 3626:             radioname = 'lti_callback_'+item;
 3627:             divid = 'lti_callbackfield_'+item;
 3628:         } else {
 3629:             radioname = 'lti_passback_'+item;
 3630:             divid =  'lti_passback_'+item;
 3631:         }
 3632:         var num = form.elements[radioname].length;
 3633:         if (num) {
 3634:             var setvis = '';
 3635:             for (var i=0; i<num; i++) {
 3636:                if (form.elements[radioname][i].checked) {
 3637:                    if ((setting == 'passback') || (setting == 'callback')) {
 3638:                        if (form.elements[radioname][i].value == '1') {
 3639:                            if (document.getElementById(divid)) {
 3640:                                document.getElementById(divid).style.display = 'inline-block';
 3641:                            }
 3642:                            setvis = 1;
 3643:                            break;
 3644:                        }
 3645:                    } else {
 3646:                        if (form.elements[radioname][i].value == 'other') {
 3647:                            if (document.getElementById(divid)) {
 3648:                                document.getElementById(divid).style.display = 'inline-block';
 3649:                            }
 3650:                            setvis = 1;
 3651:                            break;
 3652:                        }
 3653:                    }
 3654:                }
 3655:             }
 3656:             if (!setvis) {
 3657:                 if (document.getElementById(divid)) {
 3658:                     document.getElementById(divid).style.display = 'none';
 3659:                 }
 3660:             }
 3661:         }
 3662:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3663:         var numsec = form.elements['lti_crssec_'+item].length;
 3664:         if (numsec) {
 3665:             var setvis = '';
 3666:             for (var i=0; i<numsec; i++) {
 3667:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3668:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3669:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3670:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3671:                             setvis = 1;
 3672:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3673:                             if (numsrcsec) {
 3674:                                 var setsrcvis = '';
 3675:                                 for (var j=0; j<numsrcsec; j++) {
 3676:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3677:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3678:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3679:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3680:                                                 setsrcvis = 1;
 3681:                                             }
 3682:                                         }
 3683:                                     }
 3684:                                 }
 3685:                                 if (!setsrcvis) {
 3686:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3687:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3688:                                     }
 3689:                                 }
 3690:                             }
 3691:                         }
 3692:                     }
 3693:                 }
 3694:             }
 3695:             if (!setvis) {
 3696:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3697:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3698:                 }
 3699:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3700:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3701:                 }
 3702:             }
 3703:         }
 3704:     } else if (setting == 'lcauth') {
 3705:         var numauth = form.elements['lti_lcauth_'+item].length;
 3706:         if (numauth) {
 3707:             for (var i=0; i<numauth; i++) {
 3708:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3709:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3710:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3711:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3712:                         } else {
 3713:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3714:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3715:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3716:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3717:                                 } else {
 3718:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3719:                                 }
 3720:                             }
 3721:                         }
 3722:                     }
 3723:                 }
 3724:             }
 3725:         }
 3726:     } else if (setting == 'lcmenu') {
 3727:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3728:         var divid = 'lti_menufield_'+item;
 3729:         var setvis = '';
 3730:         for (var i=0; i<menus.length; i++) {
 3731:             var radioname = menus[i];
 3732:             var num = form.elements[radioname].length;
 3733:             if (num) {
 3734:                 for (var j=0; j<num; j++) {
 3735:                     if (form.elements[radioname][j].checked) {
 3736:                         if (form.elements[radioname][j].value == '1') {
 3737:                             if (document.getElementById(divid)) {
 3738:                                 document.getElementById(divid).style.display = 'inline-block';
 3739:                             }
 3740:                             setvis = 1;
 3741:                             break;
 3742:                         }
 3743:                     }
 3744:                 }
 3745:             }
 3746:             if (setvis == 1) {
 3747:                 break;
 3748:             }
 3749:         }
 3750:         if (!setvis) {
 3751:             if (document.getElementById(divid)) {
 3752:                 document.getElementById(divid).style.display = 'none';
 3753:             }
 3754:         }
 3755:     }
 3756:     return;
 3757: }
 3758: 
 3759: // ]]>
 3760: </script>
 3761: 
 3762: ENDSCRIPT
 3763: }
 3764: 
 3765: sub autoupdate_javascript {
 3766:     return <<"ENDSCRIPT";
 3767: <script type="text/javascript">
 3768: // <![CDATA[
 3769: function toggleLastActiveDays(form) {
 3770:     var radioname = 'lastactive';
 3771:     var divid = 'lastactive_div';
 3772:     var num = form.elements[radioname].length;
 3773:     if (num) {
 3774:         var setvis = '';
 3775:         for (var i=0; i<num; i++) {
 3776:             if (form.elements[radioname][i].checked) {
 3777:                 if (form.elements[radioname][i].value == '1') {
 3778:                     if (document.getElementById(divid)) {
 3779:                         document.getElementById(divid).style.display = 'inline-block';
 3780:                     }
 3781:                     setvis = 1;
 3782:                 }
 3783:                 break;
 3784:             }
 3785:         }
 3786:         if (!setvis) {
 3787:             if (document.getElementById(divid)) {
 3788:                 document.getElementById(divid).style.display = 'none';
 3789:             }
 3790:         }
 3791:     }
 3792:     return;
 3793: }
 3794: // ]]>
 3795: </script>
 3796: 
 3797: ENDSCRIPT
 3798: }
 3799: 
 3800: sub autoenroll_javascript {
 3801:     return <<"ENDSCRIPT";
 3802: <script type="text/javascript">
 3803: // <![CDATA[
 3804: function toggleFailsafe(form) {
 3805:     var radioname = 'autoenroll_failsafe';
 3806:     var divid = 'autoenroll_failsafe_div';
 3807:     var num = form.elements[radioname].length;
 3808:     if (num) {
 3809:         var setvis = '';
 3810:         for (var i=0; i<num; i++) {
 3811:             if (form.elements[radioname][i].checked) {
 3812:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3813:                     if (document.getElementById(divid)) {
 3814:                         document.getElementById(divid).style.display = 'inline-block';
 3815:                     }
 3816:                     setvis = 1;
 3817:                 }
 3818:                 break;
 3819:             }
 3820:         }
 3821:         if (!setvis) {
 3822:             if (document.getElementById(divid)) {
 3823:                 document.getElementById(divid).style.display = 'none';
 3824:             }
 3825:         }
 3826:     }
 3827:     return;
 3828: }
 3829: // ]]>
 3830: </script>
 3831: 
 3832: ENDSCRIPT
 3833: }
 3834: 
 3835: sub saml_javascript {
 3836:     return <<"ENDSCRIPT";
 3837: <script type="text/javascript">
 3838: // <![CDATA[
 3839: function toggleSamlOptions(form,hostid) {
 3840:     var radioname = 'saml_'+hostid;
 3841:     var tablecellon = 'samloptionson_'+hostid;
 3842:     var tablecelloff = 'samloptionsoff_'+hostid;
 3843:     var num = form.elements[radioname].length;
 3844:     if (num) {
 3845:         var setvis = '';
 3846:         for (var i=0; i<num; i++) {
 3847:             if (form.elements[radioname][i].checked) {
 3848:                 if (form.elements[radioname][i].value == '1') {
 3849:                     if (document.getElementById(tablecellon)) {
 3850:                         document.getElementById(tablecellon).style.display='';
 3851:                     }
 3852:                     if (document.getElementById(tablecelloff)) {
 3853:                         document.getElementById(tablecelloff).style.display='none';
 3854:                     }
 3855:                     setvis = 1;
 3856:                 }
 3857:                 break;
 3858:             }
 3859:         }
 3860:         if (!setvis) {
 3861:             if (document.getElementById(tablecellon)) {
 3862:                 document.getElementById(tablecellon).style.display='none';
 3863:             }
 3864:             if (document.getElementById(tablecelloff)) {
 3865:                 document.getElementById(tablecelloff).style.display='';
 3866:             }
 3867:         }
 3868:     }
 3869:     return;
 3870: }
 3871: // ]]>
 3872: </script>
 3873: 
 3874: ENDSCRIPT
 3875: }
 3876: 
 3877: sub ipaccess_javascript {
 3878:     my ($settings) = @_;
 3879:     my (%ordered,$total,%jstext);
 3880:     $total = 0;
 3881:     if (ref($settings) eq 'HASH') {
 3882:         foreach my $item (keys(%{$settings})) {
 3883:             if (ref($settings->{$item}) eq 'HASH') {
 3884:                 my $num = $settings->{$item}{'order'};
 3885:                 $ordered{$num} = $item;
 3886:             }
 3887:         }
 3888:         $total = scalar(keys(%{$settings}));
 3889:     }
 3890:     my @jsarray = ();
 3891:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3892:         push(@jsarray,$ordered{$item});
 3893:     }
 3894:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3895:     return <<"ENDSCRIPT";
 3896: <script type="text/javascript">
 3897: // <![CDATA[
 3898: function reorderIPaccess(form,item) {
 3899:     var changedVal;
 3900: $jstext
 3901:     var newpos = 'ipaccess_pos_add';
 3902:     var maxh = 1 + $total;
 3903:     var current = new Array;
 3904:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3905:     if (item == newpos) {
 3906:         changedVal = newitemVal;
 3907:     } else {
 3908:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3909:         current[newitemVal] = newpos;
 3910:     }
 3911:     for (var i=0; i<ipaccess.length; i++) {
 3912:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3913:         if (elementName != item) {
 3914:             if (form.elements[elementName]) {
 3915:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3916:                 current[currVal] = elementName;
 3917:             }
 3918:         }
 3919:     }
 3920:     var oldVal;
 3921:     for (var j=0; j<maxh; j++) {
 3922:         if (current[j] == undefined) {
 3923:             oldVal = j;
 3924:         }
 3925:     }
 3926:     if (oldVal < changedVal) {
 3927:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3928:            var elementName = current[k];
 3929:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3930:         }
 3931:     } else {
 3932:         for (var k=changedVal; k<oldVal; k++) {
 3933:             var elementName = current[k];
 3934:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3935:         }
 3936:     }
 3937:     return;
 3938: }
 3939: // ]]>
 3940: </script>
 3941: 
 3942: ENDSCRIPT
 3943: }
 3944: 
 3945: sub print_autoenroll {
 3946:     my ($dom,$settings,$rowtotal) = @_;
 3947:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3948:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 3949:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 3950:     $failsafesty = 'none';
 3951:     %failsafechecked = (
 3952:         off => ' checked="checked"',
 3953:     );
 3954:     if (ref($settings) eq 'HASH') {
 3955:         if (exists($settings->{'run'})) {
 3956:             if ($settings->{'run'} eq '0') {
 3957:                 $runoff = ' checked="checked" ';
 3958:                 $runon = ' ';
 3959:             } else {
 3960:                 $runon = ' checked="checked" ';
 3961:                 $runoff = ' ';
 3962:             }
 3963:         } else {
 3964:             if ($autorun) {
 3965:                 $runon = ' checked="checked" ';
 3966:                 $runoff = ' ';
 3967:             } else {
 3968:                 $runoff = ' checked="checked" ';
 3969:                 $runon = ' ';
 3970:             }
 3971:         }
 3972:         if (exists($settings->{'co-owners'})) {
 3973:             if ($settings->{'co-owners'} eq '0') {
 3974:                 $coownersoff = ' checked="checked" ';
 3975:                 $coownerson = ' ';
 3976:             } else {
 3977:                 $coownerson = ' checked="checked" ';
 3978:                 $coownersoff = ' ';
 3979:             }
 3980:         } else {
 3981:             $coownersoff = ' checked="checked" ';
 3982:             $coownerson = ' ';
 3983:         }
 3984:         if (exists($settings->{'sender_domain'})) {
 3985:             $defdom = $settings->{'sender_domain'};
 3986:         }
 3987:         if (exists($settings->{'failsafe'})) {
 3988:             $failsafe = $settings->{'failsafe'};
 3989:             if ($failsafe eq 'zero') {
 3990:                 $failsafechecked{'zero'} = ' checked="checked"';
 3991:                 $failsafechecked{'off'} = '';
 3992:                 $failsafesty = 'inline-block';
 3993:             } elsif ($failsafe eq 'any') {
 3994:                 $failsafechecked{'any'} = ' checked="checked"';
 3995:                 $failsafechecked{'off'} = '';
 3996:             }
 3997:             $autofailsafe = $settings->{'autofailsafe'};
 3998:         } elsif (exists($settings->{'autofailsafe'})) {
 3999:             $autofailsafe = $settings->{'autofailsafe'};
 4000:             if ($autofailsafe ne '') {
 4001:                 $failsafechecked{'zero'} = ' checked="checked"';
 4002:                 $failsafe = 'zero';
 4003:                 $failsafechecked{'off'} = '';
 4004:             }
 4005:         }
 4006:     } else {
 4007:         if ($autorun) {
 4008:             $runon = ' checked="checked" ';
 4009:             $runoff = ' ';
 4010:         } else {
 4011:             $runoff = ' checked="checked" ';
 4012:             $runon = ' ';
 4013:         }
 4014:     }
 4015:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 4016:     my $notif_sender;
 4017:     if (ref($settings) eq 'HASH') {
 4018:         $notif_sender = $settings->{'sender_uname'};
 4019:     }
 4020:     my $datatable='<tr class="LC_odd_row">'.
 4021:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 4022:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4023:                   '<input type="radio" name="autoenroll_run"'.
 4024:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4025:                   '<label><input type="radio" name="autoenroll_run"'.
 4026:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4027:                   '</tr><tr>'.
 4028:                   '<td>'.&mt('Notification messages - sender').
 4029:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 4030:                   &mt('username').':&nbsp;'.
 4031:                   '<input type="text" name="sender_uname" value="'.
 4032:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 4033:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 4034:                   '<tr class="LC_odd_row">'.
 4035:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 4036:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4037:                   '<input type="radio" name="autoassign_coowners"'.
 4038:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4039:                   '<label><input type="radio" name="autoassign_coowners"'.
 4040:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4041:                   '</tr><tr>'.
 4042:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 4043:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 4044:                   '<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; '.
 4045:                   '<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 />'.
 4046:                   '<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>'.
 4047:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 4048:                   '<span class="LC_nobreak">'.
 4049:                   &mt('Threshold for number of students in section to drop: [_1]',
 4050:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 4051:                   '</span></div></td></tr>';
 4052:     $$rowtotal += 4;
 4053:     return $datatable;
 4054: }
 4055: 
 4056: sub print_autoupdate {
 4057:     my ($position,$dom,$settings,$rowtotal) = @_;
 4058:     my ($enable,$datatable);
 4059:     if ($position eq 'top') {
 4060:         my %choices = &Apache::lonlocal::texthash (
 4061:                           run        => 'Auto-update active?',
 4062:                           classlists => 'Update information in classlists?',
 4063:                           unexpired  => 'Skip updates for users without active or future roles?',
 4064:                           lastactive => 'Skip updates for inactive users?',
 4065:         );
 4066:         my $itemcount = 0;
 4067:         my $updateon = ' ';
 4068:         my $updateoff = ' checked="checked" ';
 4069:         if (ref($settings) eq 'HASH') {
 4070:             if ($settings->{'run'} eq '1') {
 4071:                 $updateon = $updateoff;
 4072:                 $updateoff = ' ';
 4073:             }
 4074:         }
 4075:         $enable = '<tr class="LC_odd_row">'.
 4076:                   '<td>'.$choices{'run'}.'</td>'.
 4077:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4078:                   '<input type="radio" name="autoupdate_run"'.
 4079:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 4080:                   '<label><input type="radio" name="autoupdate_run"'.
 4081:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 4082:                   '</tr>';
 4083:         my @toggles = ('classlists','unexpired');
 4084:         my %defaultchecked = ('classlists' => 'off',
 4085:                               'unexpired'  => 'off'
 4086:                               );
 4087:         $$rowtotal ++;
 4088:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4089:                                                      \%choices,$itemcount,'','','left','no');
 4090:         $datatable = $enable.$datatable;
 4091:         $$rowtotal += $itemcount;
 4092:         my $lastactiveon = ' ';
 4093:         my $lastactiveoff = ' checked="checked" ';
 4094:         my $lastactivestyle = 'none';
 4095:         my $lastactivedays;
 4096:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 4097:         if (ref($settings) eq 'HASH') {
 4098:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 4099:                 $lastactiveon = $lastactiveoff;
 4100:                 $lastactiveoff = ' ';
 4101:                 $lastactivestyle = 'inline-block';
 4102:                 $lastactivedays = $settings->{'lastactive'};
 4103:             }
 4104:         }
 4105:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4106:         $datatable .= '<tr'.$css_class.'>'.
 4107:                       '<td>'.$choices{'lastactive'}.'</td>'.
 4108:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4109:                       '<input type="radio" name="lastactive"'.
 4110:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4111:                       '&nbsp;<label>'.
 4112:                       '<input type="radio" name="lastactive"'.
 4113:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 4114:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 4115:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 4116:                           '<input type="text" size="5" name="lastactivedays" value="'.
 4117:                           $lastactivedays.'" />').
 4118:                       '</span></td>'.
 4119:                       '</tr>';
 4120:         $$rowtotal ++;
 4121:     } elsif ($position eq 'middle') {
 4122:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4123:         my $numinrow = 3;
 4124:         my $locknamesettings;
 4125:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 4126:                                      $dom,$numinrow,$othertitle,
 4127:                                     'lockablenames',$rowtotal);
 4128:         $$rowtotal ++;
 4129:     } else {
 4130:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4131:         my @fields = ('lastname','firstname','middlename','generation',
 4132:                       'permanentemail','id');
 4133:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4134:         my $numrows = 0;
 4135:         if (ref($types) eq 'ARRAY') {
 4136:             if (@{$types} > 0) {
 4137:                 $datatable = 
 4138:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 4139:                                          \@fields,$types,\$numrows);
 4140:                     $$rowtotal += @{$types}; 
 4141:             }
 4142:         }
 4143:         $datatable .= 
 4144:             &usertype_update_row($settings,{'default' => $othertitle},
 4145:                                  \%fieldtitles,\@fields,['default'],
 4146:                                  \$numrows);
 4147:         $$rowtotal ++;     
 4148:     }
 4149:     return $datatable;
 4150: }
 4151: 
 4152: sub print_autocreate {
 4153:     my ($dom,$settings,$rowtotal) = @_;
 4154:     my (%createon,%createoff,%currhash);
 4155:     my @types = ('xml','req');
 4156:     if (ref($settings) eq 'HASH') {
 4157:         foreach my $item (@types) {
 4158:             $createoff{$item} = ' checked="checked" ';
 4159:             $createon{$item} = ' ';
 4160:             if (exists($settings->{$item})) {
 4161:                 if ($settings->{$item}) {
 4162:                     $createon{$item} = ' checked="checked" ';
 4163:                     $createoff{$item} = ' ';
 4164:                 }
 4165:             }
 4166:         }
 4167:         if ($settings->{'xmldc'} ne '') {
 4168:             $currhash{$settings->{'xmldc'}} = 1;
 4169:         }
 4170:     } else {
 4171:         foreach my $item (@types) {
 4172:             $createoff{$item} = ' checked="checked" ';
 4173:             $createon{$item} = ' ';
 4174:         }
 4175:     }
 4176:     $$rowtotal += 2;
 4177:     my $numinrow = 2;
 4178:     my $datatable='<tr class="LC_odd_row">'.
 4179:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 4180:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4181:                   '<input type="radio" name="autocreate_xml"'.
 4182:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4183:                   '<label><input type="radio" name="autocreate_xml"'.
 4184:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 4185:                   '</td></tr><tr>'.
 4186:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 4187:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4188:                   '<input type="radio" name="autocreate_req"'.
 4189:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4190:                   '<label><input type="radio" name="autocreate_req"'.
 4191:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 4192:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 4193:                                                    'autocreate_xmldc',%currhash);
 4194:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 4195:     if ($numdc > 1) {
 4196:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 4197:                       '</td><td class="LC_left_item">';
 4198:     } else {
 4199:         $datatable .= &mt('Course creation processed as:').
 4200:                       '</td><td class="LC_right_item">';
 4201:     }
 4202:     $datatable .= $dctable.'</td></tr>';
 4203:     $$rowtotal += $rows;
 4204:     return $datatable;
 4205: }
 4206: 
 4207: sub print_directorysrch {
 4208:     my ($position,$dom,$settings,$rowtotal) = @_;
 4209:     my $datatable;
 4210:     if ($position eq 'top') {
 4211:         my $instsrchon = ' ';
 4212:         my $instsrchoff = ' checked="checked" ';
 4213:         my ($exacton,$containson,$beginson);
 4214:         my $instlocalon = ' ';
 4215:         my $instlocaloff = ' checked="checked" ';
 4216:         if (ref($settings) eq 'HASH') {
 4217:             if ($settings->{'available'} eq '1') {
 4218:                 $instsrchon = $instsrchoff;
 4219:                 $instsrchoff = ' ';
 4220:             }
 4221:             if ($settings->{'localonly'} eq '1') {
 4222:                 $instlocalon = $instlocaloff;
 4223:                 $instlocaloff = ' ';
 4224:             }
 4225:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 4226:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 4227:                     if ($type eq 'exact') {
 4228:                         $exacton = ' checked="checked" ';
 4229:                     } elsif ($type eq 'contains') {
 4230:                         $containson = ' checked="checked" ';
 4231:                     } elsif ($type eq 'begins') {
 4232:                         $beginson = ' checked="checked" ';
 4233:                     }
 4234:                 }
 4235:             } else {
 4236:                 if ($settings->{'searchtypes'} eq 'exact') {
 4237:                     $exacton = ' checked="checked" ';
 4238:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 4239:                     $containson = ' checked="checked" ';
 4240:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 4241:                     $exacton = ' checked="checked" ';
 4242:                     $containson = ' checked="checked" ';
 4243:                 }
 4244:             }
 4245:         }
 4246:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 4247:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4248: 
 4249:         my $numinrow = 4;
 4250:         my $cansrchrow = 0;
 4251:         $datatable='<tr class="LC_odd_row">'.
 4252:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 4253:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4254:                    '<input type="radio" name="dirsrch_available"'.
 4255:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4256:                    '<label><input type="radio" name="dirsrch_available"'.
 4257:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4258:                    '</tr><tr>'.
 4259:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 4260:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4261:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 4262:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4263:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 4264:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4265:                    '</tr>';
 4266:         $$rowtotal += 2;
 4267:         if (ref($usertypes) eq 'HASH') {
 4268:             if (keys(%{$usertypes}) > 0) {
 4269:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4270:                                              $numinrow,$othertitle,'cansearch',
 4271:                                              $rowtotal);
 4272:                 $cansrchrow = 1;
 4273:             }
 4274:         }
 4275:         if ($cansrchrow) {
 4276:             $$rowtotal ++;
 4277:             $datatable .= '<tr>';
 4278:         } else {
 4279:             $datatable .= '<tr class="LC_odd_row">';
 4280:         }
 4281:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 4282:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 4283:         foreach my $title (@{$titleorder}) {
 4284:             if (defined($searchtitles->{$title})) {
 4285:                 my $check = ' ';
 4286:                 if (ref($settings) eq 'HASH') {
 4287:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 4288:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 4289:                             $check = ' checked="checked" ';
 4290:                         }
 4291:                     }
 4292:                 }
 4293:                 $datatable .= '<td class="LC_left_item">'.
 4294:                               '<span class="LC_nobreak"><label>'.
 4295:                               '<input type="checkbox" name="searchby" '.
 4296:                               'value="'.$title.'"'.$check.'/>'.
 4297:                               $searchtitles->{$title}.'</label></span></td>';
 4298:             }
 4299:         }
 4300:         $datatable .= '</tr></table></td></tr>';
 4301:         $$rowtotal ++;
 4302:         if ($cansrchrow) {
 4303:             $datatable .= '<tr class="LC_odd_row">';
 4304:         } else {
 4305:             $datatable .= '<tr>';
 4306:         }
 4307:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 4308:                       '<td class="LC_left_item" colspan="2">'.
 4309:                       '<span class="LC_nobreak"><label>'.
 4310:                       '<input type="checkbox" name="searchtypes" '.
 4311:                       $exacton.' value="exact" />'.&mt('Exact match').
 4312:                       '</label>&nbsp;'.
 4313:                       '<label><input type="checkbox" name="searchtypes" '.
 4314:                       $beginson.' value="begins" />'.&mt('Begins with').
 4315:                       '</label>&nbsp;'.
 4316:                       '<label><input type="checkbox" name="searchtypes" '.
 4317:                       $containson.' value="contains" />'.&mt('Contains').
 4318:                       '</label></span></td></tr>';
 4319:         $$rowtotal ++;
 4320:     } else {
 4321:         my $domsrchon = ' checked="checked" ';
 4322:         my $domsrchoff = ' ';
 4323:         my $domlocalon = ' ';
 4324:         my $domlocaloff = ' checked="checked" ';
 4325:         if (ref($settings) eq 'HASH') {
 4326:             if ($settings->{'lclocalonly'} eq '1') {
 4327:                 $domlocalon = $domlocaloff;
 4328:                 $domlocaloff = ' ';
 4329:             }
 4330:             if ($settings->{'lcavailable'} eq '0') {
 4331:                 $domsrchoff = $domsrchon;
 4332:                 $domsrchon = ' ';
 4333:             }
 4334:         }
 4335:         $datatable='<tr class="LC_odd_row">'.
 4336:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 4337:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4338:                       '<input type="radio" name="dirsrch_domavailable"'.
 4339:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4340:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 4341:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4342:                       '</tr><tr>'.
 4343:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 4344:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4345:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 4346:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4347:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 4348:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4349:                       '</tr>';
 4350:         $$rowtotal += 2;
 4351:     }
 4352:     return $datatable;
 4353: }
 4354: 
 4355: sub print_contacts {
 4356:     my ($position,$dom,$settings,$rowtotal) = @_;
 4357:     my $datatable;
 4358:     my @contacts = ('adminemail','supportemail');
 4359:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 4360:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 4361:     if ($position eq 'top') {
 4362:         if (ref($settings) eq 'HASH') {
 4363:             foreach my $item (@contacts) {
 4364:                 if (exists($settings->{$item})) {
 4365:                     $to{$item} = $settings->{$item};
 4366:                 }
 4367:             }
 4368:         }
 4369:     } elsif ($position eq 'middle') {
 4370:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 4371:                      'updatesmail','idconflictsmail','hostipmail');
 4372:         foreach my $type (@mailings) {
 4373:             $otheremails{$type} = '';
 4374:         }
 4375:     } elsif ($position eq 'lower') {
 4376:         if (ref($settings) eq 'HASH') {
 4377:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 4378:                 %lonstatus = %{$settings->{'lonstatus'}};
 4379:             }
 4380:         }
 4381:     } else {
 4382:         @mailings = ('helpdeskmail','otherdomsmail');
 4383:         foreach my $type (@mailings) {
 4384:             $otheremails{$type} = '';
 4385:         }
 4386:         $bccemails{'helpdeskmail'} = '';
 4387:         $bccemails{'otherdomsmail'} = '';
 4388:         $includestr{'helpdeskmail'} = '';
 4389:         $includestr{'otherdomsmail'} = '';
 4390:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 4391:     }
 4392:     if (ref($settings) eq 'HASH') {
 4393:         unless (($position eq 'top') || ($position eq 'lower')) {
 4394:             foreach my $type (@mailings) {
 4395:                 if (exists($settings->{$type})) {
 4396:                     if (ref($settings->{$type}) eq 'HASH') {
 4397:                         foreach my $item (@contacts) {
 4398:                             if ($settings->{$type}{$item}) {
 4399:                                 $checked{$type}{$item} = ' checked="checked" ';
 4400:                             }
 4401:                         }
 4402:                         $otheremails{$type} = $settings->{$type}{'others'};
 4403:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4404:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 4405:                             if ($settings->{$type}{'include'} ne '') {
 4406:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4407:                                 $includestr{$type} = &unescape($includestr{$type});
 4408:                             }
 4409:                         }
 4410:                     }
 4411:                 } elsif ($type eq 'lonstatusmail') {
 4412:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4413:                 }
 4414:             }
 4415:         }
 4416:         if ($position eq 'bottom') {
 4417:             foreach my $type (@mailings) {
 4418:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 4419:                 if ($settings->{$type}{'include'} ne '') {
 4420:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4421:                     $includestr{$type} = &unescape($includestr{$type});
 4422:                 }
 4423:             }
 4424:             if (ref($settings->{'helpform'}) eq 'HASH') {
 4425:                 if (ref($fields) eq 'ARRAY') {
 4426:                     foreach my $field (@{$fields}) {
 4427:                         $currfield{$field} = $settings->{'helpform'}{$field};
 4428:                     }
 4429:                 }
 4430:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 4431:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 4432:                 } else {
 4433:                     $maxsize = '1.0';
 4434:                 }
 4435:             } else {
 4436:                 if (ref($fields) eq 'ARRAY') {
 4437:                     foreach my $field (@{$fields}) {
 4438:                         $currfield{$field} = 'yes';
 4439:                     }
 4440:                 }
 4441:                 $maxsize = '1.0';
 4442:             }
 4443:         }
 4444:     } else {
 4445:         if ($position eq 'top') {
 4446:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 4447:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 4448:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 4449:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 4450:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4451:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 4452:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 4453:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 4454:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 4455:         } elsif ($position eq 'bottom') {
 4456:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 4457:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 4458:             if (ref($fields) eq 'ARRAY') {
 4459:                 foreach my $field (@{$fields}) {
 4460:                     $currfield{$field} = 'yes';
 4461:                 }
 4462:             }
 4463:             $maxsize = '1.0';
 4464:         }
 4465:     }
 4466:     my ($titles,$short_titles) = &contact_titles();
 4467:     my $rownum = 0;
 4468:     my $css_class;
 4469:     if ($position eq 'top') {
 4470:         foreach my $item (@contacts) {
 4471:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4472:             $datatable .= '<tr'.$css_class.'>'. 
 4473:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 4474:                           '</span></td><td class="LC_right_item">'.
 4475:                           '<input type="text" name="'.$item.'" value="'.
 4476:                           $to{$item}.'" /></td></tr>';
 4477:             $rownum ++;
 4478:         }
 4479:     } elsif ($position eq 'bottom') {
 4480:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4481:         $datatable .= '<tr'.$css_class.'>'.
 4482:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 4483:                       &mt('(e-mail, subject, and description always shown)').
 4484:                       '</td><td class="LC_left_item">';
 4485:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 4486:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 4487:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 4488:             foreach my $field (@{$fields}) {
 4489:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 4490:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 4491:                     $datatable .= ' '.&mt('(logged-in users)');
 4492:                 }
 4493:                 $datatable .='</td><td>';
 4494:                 my $clickaction;
 4495:                 if ($field eq 'screenshot') {
 4496:                     $clickaction = ' onclick="screenshotSize(this);"';
 4497:                 }
 4498:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4499:                     foreach my $option (@{$possoptions->{$field}}) {
 4500:                         my $checked;
 4501:                         if ($currfield{$field} eq $option) {
 4502:                             $checked = ' checked="checked"';
 4503:                         }
 4504:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4505:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4506:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4507:                                       '</label></span>'.('&nbsp;'x2);
 4508:                     }
 4509:                 }
 4510:                 if ($field eq 'screenshot') {
 4511:                     my $display;
 4512:                     if ($currfield{$field} eq 'no') {
 4513:                         $display = ' style="display:none"';
 4514:                     }
 4515:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4516:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4517:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4518:                 }
 4519:                 $datatable .= '</td></tr>';
 4520:             }
 4521:             $datatable .= '</table>';
 4522:         }
 4523:         $datatable .= '</td></tr>'."\n";
 4524:         $rownum ++;
 4525:     }
 4526:     unless (($position eq 'top') || ($position eq 'lower')) {
 4527:         foreach my $type (@mailings) {
 4528:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4529:             $datatable .= '<tr'.$css_class.'>'.
 4530:                           '<td><span class="LC_nobreak">'.
 4531:                           $titles->{$type}.': </span></td>'.
 4532:                           '<td class="LC_left_item">';
 4533:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4534:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4535:             }
 4536:             $datatable .= '<span class="LC_nobreak">';
 4537:             foreach my $item (@contacts) {
 4538:                 $datatable .= '<label>'.
 4539:                               '<input type="checkbox" name="'.$type.'"'.
 4540:                               $checked{$type}{$item}.
 4541:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4542:                               '</label>&nbsp;';
 4543:             }
 4544:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4545:                           '<input type="text" name="'.$type.'_others" '.
 4546:                           'value="'.$otheremails{$type}.'"  />';
 4547:             my %locchecked;
 4548:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4549:                 foreach my $loc ('s','b') {
 4550:                     if ($includeloc{$type} eq $loc) {
 4551:                         $locchecked{$loc} = ' checked="checked"';
 4552:                         last;
 4553:                     }
 4554:                 }
 4555:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4556:                               '<input type="text" name="'.$type.'_bcc" '.
 4557:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4558:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4559:                               &mt('Text automatically added to e-mail:').' '.
 4560:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4561:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4562:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4563:                               ('&nbsp;'x2).
 4564:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4565:                               '</span></fieldset>';
 4566:             }
 4567:             $datatable .= '</td></tr>'."\n";
 4568:             $rownum ++;
 4569:         }
 4570:     }
 4571:     if ($position eq 'middle') {
 4572:         my %choices;
 4573:         my $corelink = &core_link_msu();
 4574:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4575:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4576:                                         $corelink);
 4577:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4578:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4579:         my %defaultchecked = ('reporterrors'  => 'on',
 4580:                               'reportupdates' => 'on',
 4581:                               'reportstatus'  => 'on');
 4582:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4583:                                                    \%choices,$rownum);
 4584:         $datatable .= $reports;
 4585:     } elsif ($position eq 'lower') {
 4586:         my (%current,%excluded,%weights);
 4587:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4588:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4589:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4590:         } else {
 4591:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4592:         }
 4593:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4594:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4595:         } else {
 4596:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4597:         }
 4598:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4599:             foreach my $type ('E','W','N','U') {
 4600:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4601:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4602:                 } else {
 4603:                     $weights{$type} = $defaults->{$type};
 4604:                 }
 4605:             }
 4606:         } else {
 4607:             foreach my $type ('E','W','N','U') {
 4608:                 $weights{$type} = $defaults->{$type};
 4609:             }
 4610:         }
 4611:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4612:             if (@{$lonstatus{'excluded'}} > 0) {
 4613:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4614:             }
 4615:         }
 4616:         foreach my $item ('errorthreshold','errorsysmail') {
 4617:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4618:             $datatable .= '<tr'.$css_class.'>'.
 4619:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4620:                           $titles->{$item}.
 4621:                           '</span></td><td class="LC_left_item">'.
 4622:                           '<input type="text" name="'.$item.'" value="'.
 4623:                           $current{$item}.'" size="5" /></td></tr>';
 4624:             $rownum ++;
 4625:         }
 4626:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4627:         $datatable .= '<tr'.$css_class.'>'.
 4628:                       '<td class="LC_left_item">'.
 4629:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4630:                       '</span></td><td class="LC_left_item"><table><tr>';
 4631:         foreach my $type ('E','W','N','U') {
 4632:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4633:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4634:                           $weights{$type}.'" size="5" /></td>';
 4635:         }
 4636:         $datatable .= '</tr></table></tr>';
 4637:         $rownum ++;
 4638:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4639:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4640:                       $titles->{'errorexcluded'}.'</td>'.
 4641:                       '<td class="LC_left_item"><table>';
 4642:         my $numinrow = 4;
 4643:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4644:         for (my $i=0; $i<@ids; $i++) {
 4645:             my $rem = $i%($numinrow);
 4646:             if ($rem == 0) {
 4647:                 if ($i > 0) {
 4648:                     $datatable .= '</tr>';
 4649:                 }
 4650:                 $datatable .= '<tr>';
 4651:             }
 4652:             my $check;
 4653:             if ($excluded{$ids[$i]}) {
 4654:                 $check = ' checked="checked" ';
 4655:             }
 4656:             $datatable .= '<td class="LC_left_item">'.
 4657:                           '<span class="LC_nobreak"><label>'.
 4658:                           '<input type="checkbox" name="errorexcluded" '.
 4659:                           'value="'.$ids[$i].'"'.$check.' />'.
 4660:                           $ids[$i].'</label></span></td>';
 4661:         }
 4662:         my $colsleft = $numinrow - @ids%($numinrow);
 4663:         if ($colsleft > 1 ) {
 4664:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4665:                           '&nbsp;</td>';
 4666:         } elsif ($colsleft == 1) {
 4667:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4668:         }
 4669:         $datatable .= '</tr></table></td></tr>';
 4670:         $rownum ++;
 4671:     } elsif ($position eq 'bottom') {
 4672:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4673:         my (@posstypes,%usertypeshash);
 4674:         if (ref($types) eq 'ARRAY') {
 4675:             @posstypes = @{$types};
 4676:         }
 4677:         if (@posstypes) {
 4678:             if (ref($usertypes) eq 'HASH') {
 4679:                 %usertypeshash = %{$usertypes};
 4680:             }
 4681:             my @overridden;
 4682:             my $numinrow = 4;
 4683:             if (ref($settings) eq 'HASH') {
 4684:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4685:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4686:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4687:                             push(@overridden,$key);
 4688:                             foreach my $item (@contacts) {
 4689:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4690:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4691:                                 }
 4692:                             }
 4693:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4694:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4695:                             $includeloc{'override_'.$key} = '';
 4696:                             $includestr{'override_'.$key} = '';
 4697:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4698:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) =
 4699:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4700:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4701:                             }
 4702:                         }
 4703:                     }
 4704:                 }
 4705:             }
 4706:             my $customclass = 'LC_helpdesk_override';
 4707:             my $optionsprefix = 'LC_options_helpdesk_';
 4708: 
 4709:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4710:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4711:                                          $numinrow,$othertitle,'overrides',
 4712:                                          \$rownum,$onclicktypes,$customclass);
 4713:             $rownum ++;
 4714:             $usertypeshash{'default'} = $othertitle;
 4715:             foreach my $status (@posstypes) {
 4716:                 my $css_class;
 4717:                 if ($rownum%2) {
 4718:                     $css_class = 'LC_odd_row ';
 4719:                 }
 4720:                 $css_class .= $customclass;
 4721:                 my $rowid = $optionsprefix.$status;
 4722:                 my $hidden = 1;
 4723:                 my $currstyle = 'display:none';
 4724:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4725:                     $currstyle = 'display:table-row';
 4726:                     $hidden = 0;
 4727:                 }
 4728:                 my $key = 'override_'.$status;
 4729:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4730:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4731:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4732:                                                   \@contacts,$short_titles);
 4733:                 unless ($hidden) {
 4734:                     $rownum ++;
 4735:                 }
 4736:             }
 4737:         }
 4738:     }
 4739:     $$rowtotal += $rownum;
 4740:     return $datatable;
 4741: }
 4742: 
 4743: sub core_link_msu {
 4744:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4745:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4746: }
 4747: 
 4748: sub overridden_helpdesk {
 4749:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4750:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4751:     my $class = 'LC_left_item';
 4752:     if ($css_class) {
 4753:         $css_class = ' class="'.$css_class.'"';
 4754:     }
 4755:     if ($rowid) {
 4756:         $rowid = ' id="'.$rowid.'"';
 4757:     }
 4758:     if ($rowstyle) {
 4759:         $rowstyle = ' style="'.$rowstyle.'"';
 4760:     }
 4761:     my ($output,$description);
 4762:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4763:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4764:               "<td>$description</td>\n".
 4765:               '<td class="'.$class.'" colspan="2">'.
 4766:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4767:               '<span class="LC_nobreak">';
 4768:     if (ref($contacts) eq 'ARRAY') {
 4769:         foreach my $item (@{$contacts}) {
 4770:             my $check;
 4771:             if (ref($checked) eq 'HASH') {
 4772:                $check = $checked->{$item};
 4773:             }
 4774:             my $title;
 4775:             if (ref($short_titles) eq 'HASH') {
 4776:                 $title = $short_titles->{$item};
 4777:             }
 4778:             $output .= '<label>'.
 4779:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4780:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4781:         }
 4782:     }
 4783:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4784:                '<input type="text" name="override_'.$type.'_others" '.
 4785:                'value="'.$otheremails.'"  />';
 4786:     my %locchecked;
 4787:     foreach my $loc ('s','b') {
 4788:         if ($includeloc eq $loc) {
 4789:             $locchecked{$loc} = ' checked="checked"';
 4790:             last;
 4791:         }
 4792:     }
 4793:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4794:                '<input type="text" name="override_'.$type.'_bcc" '.
 4795:                'value="'.$bccemails.'"  /></fieldset>'.
 4796:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4797:                &mt('Text automatically added to e-mail:').' '.
 4798:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4799:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4800:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4801:                ('&nbsp;'x2).
 4802:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4803:                '</span></fieldset>'.
 4804:                '</td></tr>'."\n";
 4805:     return $output;
 4806: }
 4807: 
 4808: sub contacts_javascript {
 4809:     return <<"ENDSCRIPT";
 4810: 
 4811: <script type="text/javascript">
 4812: // <![CDATA[
 4813: 
 4814: function screenshotSize(field) {
 4815:     if (document.getElementById('help_screenshotsize')) {
 4816:         if (field.value == 'no') {
 4817:             document.getElementById('help_screenshotsize').style.display="none";
 4818:         } else {
 4819:             document.getElementById('help_screenshotsize').style.display="";
 4820:         }
 4821:     }
 4822:     return;
 4823: }
 4824: 
 4825: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4826:     if (form.elements[checkbox].length != undefined) {
 4827:         var count = 0;
 4828:         if (docount) {
 4829:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4830:                 if (form.elements[checkbox][i].checked) {
 4831:                     count ++;
 4832:                 }
 4833:             }
 4834:         }
 4835:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4836:             var type = form.elements[checkbox][i].value;
 4837:             if (document.getElementById(prefix+type)) {
 4838:                 if (form.elements[checkbox][i].checked) {
 4839:                     document.getElementById(prefix+type).style.display = 'table-row';
 4840:                     if (count % 2 == 1) {
 4841:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4842:                     } else {
 4843:                         document.getElementById(prefix+type).className = target;
 4844:                     }
 4845:                     count ++;
 4846:                 } else {
 4847:                     document.getElementById(prefix+type).style.display = 'none';
 4848:                 }
 4849:             }
 4850:         }
 4851:     }
 4852:     return;
 4853: }
 4854: 
 4855: // ]]>
 4856: </script>
 4857: 
 4858: ENDSCRIPT
 4859: }
 4860: 
 4861: sub print_helpsettings {
 4862:     my ($position,$dom,$settings,$rowtotal) = @_;
 4863:     my $confname = $dom.'-domainconfig';
 4864:     my $formname = 'display';
 4865:     my ($datatable,$itemcount);
 4866:     if ($position eq 'top') {
 4867:         $itemcount = 1;
 4868:         my (%choices,%defaultchecked,@toggles);
 4869:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4870:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4871:                                      &mt('LON-CAPA bug tracker'),600,500));
 4872:         %defaultchecked = ('submitbugs' => 'on');
 4873:         @toggles = ('submitbugs');
 4874:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4875:                                                      \%choices,$itemcount);
 4876:         $$rowtotal ++;
 4877:     } else {
 4878:         my $css_class;
 4879:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4880:         my (%customroles,%ordered,%current);
 4881:         if (ref($settings) eq 'HASH') {
 4882:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4883:                 %current = %{$settings->{'adhoc'}};
 4884:             }
 4885:         }
 4886:         my $count = 0;
 4887:         foreach my $key (sort(keys(%existing))) {
 4888:             if ($key=~/^rolesdef\_(\w+)$/) {
 4889:                 my $rolename = $1;
 4890:                 my (%privs,$order);
 4891:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4892:                 $customroles{$rolename} = \%privs;
 4893:                 if (ref($current{$rolename}) eq 'HASH') {
 4894:                     $order = $current{$rolename}{'order'};
 4895:                 }
 4896:                 if ($order eq '') {
 4897:                     $order = $count;
 4898:                 }
 4899:                 $ordered{$order} = $rolename;
 4900:                 $count++;
 4901:             }
 4902:         }
 4903:         my $maxnum = scalar(keys(%ordered));
 4904:         my @roles_by_num = ();
 4905:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4906:             push(@roles_by_num,$item);
 4907:         }
 4908:         my $context = 'domprefs';
 4909:         my $crstype = 'Course';
 4910:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4911:         my @accesstypes = ('all','dh','da','none');
 4912:         my ($numstatustypes,@jsarray);
 4913:         if (ref($types) eq 'ARRAY') {
 4914:             if (@{$types} > 0) {
 4915:                 $numstatustypes = scalar(@{$types});
 4916:                 push(@accesstypes,'status');
 4917:                 @jsarray = ('bystatus');
 4918:             }
 4919:         }
 4920:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4921:         if (keys(%domhelpdesk)) {
 4922:             push(@accesstypes,('inc','exc'));
 4923:             push(@jsarray,('notinc','notexc'));
 4924:         }
 4925:         my $hiddenstr = join("','",@jsarray);
 4926:         my $context = 'domprefs';
 4927:         my $crstype = 'Course';
 4928:         my $prefix = 'helproles_';
 4929:         my $add_class = 'LC_hidden';
 4930:         foreach my $num (@roles_by_num) {
 4931:             my $role = $ordered{$num};
 4932:             my ($desc,$access,@statuses);
 4933:             if (ref($current{$role}) eq 'HASH') {
 4934:                 $desc = $current{$role}{'desc'};
 4935:                 $access = $current{$role}{'access'};
 4936:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4937:                     @statuses = @{$current{$role}{'insttypes'}};
 4938:                 }
 4939:             }
 4940:             if ($desc eq '') {
 4941:                 $desc = $role;
 4942:             }
 4943:             my $identifier = 'custhelp'.$num;
 4944:             my %full=();
 4945:             my %levels= (
 4946:                          course => {},
 4947:                          domain => {},
 4948:                          system => {},
 4949:                         );
 4950:             my %levelscurrent=(
 4951:                                course => {},
 4952:                                domain => {},
 4953:                                system => {},
 4954:                               );
 4955:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4956:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4957:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4958:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4959:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 4960:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4961:             for (my $k=0; $k<=$maxnum; $k++) {
 4962:                 my $vpos = $k+1;
 4963:                 my $selstr;
 4964:                 if ($k == $num) {
 4965:                     $selstr = ' selected="selected" ';
 4966:                 }
 4967:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4968:             }
 4969:             $datatable .= '</select>'.('&nbsp;'x2).
 4970:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4971:                           '</td>'.
 4972:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4973:                           &mt('Name shown to users:').
 4974:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4975:                           '</fieldset>'.
 4976:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4977:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4978:                           '<fieldset>'.
 4979:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4980:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4981:                                                                    \%levelscurrent,$identifier,
 4982:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4983:                           '</fieldset></td>';
 4984:             $itemcount ++;
 4985:         }
 4986:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4987:         my $newcust = 'custhelp'.$count;
 4988:         my (%privs,%levelscurrent);
 4989:         my %full=();
 4990:         my %levels= (
 4991:                      course => {},
 4992:                      domain => {},
 4993:                      system => {},
 4994:                     );
 4995:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4996:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4997:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4998:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 4999:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 5000:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 5001:         for (my $k=0; $k<$maxnum+1; $k++) {
 5002:             my $vpos = $k+1;
 5003:             my $selstr;
 5004:             if ($k == $maxnum) {
 5005:                 $selstr = ' selected="selected" ';
 5006:             }
 5007:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5008:         }
 5009:         $datatable .= '</select>&nbsp;'."\n".
 5010:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 5011:                       '</label></span></td>'.
 5012:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5013:                       '<span class="LC_nobreak">'.
 5014:                       &mt('Internal name:').
 5015:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 5016:                       '</span>'.('&nbsp;'x4).
 5017:                       '<span class="LC_nobreak">'.
 5018:                       &mt('Name shown to users:').
 5019:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 5020:                       '</span></fieldset>'.
 5021:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 5022:                                              $usertypes,$types,\%domhelpdesk).
 5023:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 5024:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 5025:                                                                 \@templateroles,$newcust).
 5026:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 5027:                                                                \%levelscurrent,$newcust).
 5028:                       '</fieldset>'.
 5029:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 5030:                       '</td></tr>';
 5031:         $count ++;
 5032:         $$rowtotal += $count;
 5033:     }
 5034:     return $datatable;
 5035: }
 5036: 
 5037: sub adhocbutton {
 5038:     my ($prefix,$num,$field,$visibility) = @_;
 5039:     my %lt = &Apache::lonlocal::texthash(
 5040:                                           show => 'Show details',
 5041:                                           hide => 'Hide details',
 5042:                                         );
 5043:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 5044:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 5045:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 5046:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 5047: }
 5048: 
 5049: sub helpsettings_javascript {
 5050:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 5051:     return unless(ref($roles_by_num) eq 'ARRAY');
 5052:     my %html_js_lt = &Apache::lonlocal::texthash(
 5053:                                           show => 'Show details',
 5054:                                           hide => 'Hide details',
 5055:                                         );
 5056:     &html_escape(\%html_js_lt);
 5057:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 5058:     return <<"ENDSCRIPT";
 5059: <script type="text/javascript">
 5060: // <![CDATA[
 5061: 
 5062: function reorderHelpRoles(form,item) {
 5063:     var changedVal;
 5064: $jstext
 5065:     var newpos = 'helproles_${total}_pos';
 5066:     var maxh = 1 + $total;
 5067:     var current = new Array();
 5068:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 5069:     if (item == newpos) {
 5070:         changedVal = newitemVal;
 5071:     } else {
 5072:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 5073:         current[newitemVal] = newpos;
 5074:     }
 5075:     for (var i=0; i<helproles.length; i++) {
 5076:         var elementName = 'helproles_'+helproles[i]+'_pos';
 5077:         if (elementName != item) {
 5078:             if (form.elements[elementName]) {
 5079:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 5080:                 current[currVal] = elementName;
 5081:             }
 5082:         }
 5083:     }
 5084:     var oldVal;
 5085:     for (var j=0; j<maxh; j++) {
 5086:         if (current[j] == undefined) {
 5087:             oldVal = j;
 5088:         }
 5089:     }
 5090:     if (oldVal < changedVal) {
 5091:         for (var k=oldVal+1; k<=changedVal ; k++) {
 5092:            var elementName = current[k];
 5093:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 5094:         }
 5095:     } else {
 5096:         for (var k=changedVal; k<oldVal; k++) {
 5097:             var elementName = current[k];
 5098:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 5099:         }
 5100:     }
 5101:     return;
 5102: }
 5103: 
 5104: function helpdeskAccess(num) {
 5105:     var curraccess = null;
 5106:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 5107:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 5108:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 5109:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 5110:             }
 5111:         }
 5112:     }
 5113:     var shown = Array();
 5114:     var hidden = Array();
 5115:     if (curraccess == 'none') {
 5116:         hidden = Array('$hiddenstr');
 5117:     } else {
 5118:         if (curraccess == 'status') {
 5119:             shown = Array('bystatus');
 5120:             hidden = Array('notinc','notexc');
 5121:         } else {
 5122:             if (curraccess == 'exc') {
 5123:                 shown = Array('notexc');
 5124:                 hidden = Array('notinc','bystatus');
 5125:             }
 5126:             if (curraccess == 'inc') {
 5127:                 shown = Array('notinc');
 5128:                 hidden = Array('notexc','bystatus');
 5129:             }
 5130:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 5131:                 hidden = Array('notinc','notexc','bystatus');
 5132:             }
 5133:         }
 5134:     }
 5135:     if (hidden.length > 0) {
 5136:         for (var i=0; i<hidden.length; i++) {
 5137:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 5138:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 5139:             }
 5140:         }
 5141:     }
 5142:     if (shown.length > 0) {
 5143:         for (var i=0; i<shown.length; i++) {
 5144:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 5145:                 if (shown[i] == 'privs') {
 5146:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 5147:                 } else {
 5148:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 5149:                 }
 5150:             }
 5151:         }
 5152:     }
 5153:     return;
 5154: }
 5155: 
 5156: function toggleHelpdeskItem(num,field) {
 5157:     if (document.getElementById('helproles_'+num+'_'+field)) {
 5158:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 5159:             document.getElementById('helproles_'+num+'_'+field).className =
 5160:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 5161:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5162:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 5163:             }
 5164:         } else {
 5165:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 5166:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5167:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 5168:             }
 5169:         }
 5170:     }
 5171:     return;
 5172: }
 5173: 
 5174: // ]]>
 5175: </script>
 5176: 
 5177: ENDSCRIPT
 5178: }
 5179: 
 5180: sub helpdeskroles_access {
 5181:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 5182:         $usertypes,$types,$domhelpdesk) = @_;
 5183:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 5184:     my %lt = &Apache::lonlocal::texthash(
 5185:                     'rou'    => 'Role usage',
 5186:                     'whi'    => 'Which helpdesk personnel may use this role?',
 5187:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 5188:                     'dh'     => 'All with domain helpdesk role',
 5189:                     'da'     => 'All with domain helpdesk assistant role',
 5190:                     'none'   => 'None',
 5191:                     'status' => 'Determined based on institutional status',
 5192:                     'inc'    => 'Include all, but exclude specific personnel',
 5193:                     'exc'    => 'Exclude all, but include specific personnel',
 5194:                   );
 5195:     my %usecheck = (
 5196:                      all => ' checked="checked"',
 5197:                    );
 5198:     my %displaydiv = (
 5199:                       status => 'none',
 5200:                       inc    => 'none',
 5201:                       exc    => 'none',
 5202:                       priv   => 'block',
 5203:                      );
 5204:     my $output;
 5205:     if (ref($current) eq 'HASH') {
 5206:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 5207:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 5208:                 $usecheck{$current->{access}} = $usecheck{'all'};
 5209:                 delete($usecheck{'all'});
 5210:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 5211:                     my $access = $1;
 5212:                     $displaydiv{$access} = 'inline';
 5213:                 } elsif ($current->{access} eq 'none') {
 5214:                     $displaydiv{'priv'} = 'none';
 5215:                 }
 5216:             }
 5217:         }
 5218:     }
 5219:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 5220:               '<p>'.$lt{'whi'}.'</p>';
 5221:     foreach my $access (@{$accesstypes}) {
 5222:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 5223:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 5224:                    $lt{$access}.'</label>';
 5225:         if ($access eq 'status') {
 5226:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 5227:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 5228:                                                                  $othertitle,$usertypes,$types).
 5229:                        '</div>';
 5230:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 5231:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 5232:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5233:                        '</div>';
 5234:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 5235:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 5236:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5237:                        '</div>';
 5238:         }
 5239:         $output .= '</p>';
 5240:     }
 5241:     $output .= '</fieldset>';
 5242:     return $output;
 5243: }
 5244: 
 5245: sub radiobutton_prefs {
 5246:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 5247:         $additional,$align,$firstval) = @_;
 5248:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 5249:                    (ref($choices) eq 'HASH'));
 5250: 
 5251:     my (%checkedon,%checkedoff,$datatable,$css_class);
 5252: 
 5253:     foreach my $item (@{$toggles}) {
 5254:         if ($defaultchecked->{$item} eq 'on') {
 5255:             $checkedon{$item} = ' checked="checked" ';
 5256:             $checkedoff{$item} = ' ';
 5257:         } elsif ($defaultchecked->{$item} eq 'off') {
 5258:             $checkedoff{$item} = ' checked="checked" ';
 5259:             $checkedon{$item} = ' ';
 5260:         }
 5261:     }
 5262:     if (ref($settings) eq 'HASH') {
 5263:         foreach my $item (@{$toggles}) {
 5264:             if ($settings->{$item} eq '1') {
 5265:                 $checkedon{$item} =  ' checked="checked" ';
 5266:                 $checkedoff{$item} = ' ';
 5267:             } elsif ($settings->{$item} eq '0') {
 5268:                 $checkedoff{$item} =  ' checked="checked" ';
 5269:                 $checkedon{$item} = ' ';
 5270:             }
 5271:         }
 5272:     }
 5273:     if ($onclick) {
 5274:         $onclick = ' onclick="'.$onclick.'"';
 5275:     }
 5276:     foreach my $item (@{$toggles}) {
 5277:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5278:         $datatable .=
 5279:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 5280:             '<span class="LC_nobreak">'.$choices->{$item}.
 5281:             '</span></td>';
 5282:         if ($align eq 'left') {
 5283:             $datatable .= '<td class="LC_left_item">';
 5284:         } else {
 5285:             $datatable .= '<td class="LC_right_item">';
 5286:         }
 5287:         $datatable .= '<span class="LC_nobreak">';
 5288:         if ($firstval eq 'no') {
 5289:             $datatable .=
 5290:                 '<label><input type="radio" name="'.
 5291:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 5292:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5293:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 5294:         } else {
 5295:             $datatable .=
 5296:                 '<label><input type="radio" name="'.
 5297:                 $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 5298:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5299:                 $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 5300:         }
 5301:         $datatable .= '</span>'.$additional.'</td></tr>';
 5302:         $itemcount ++;
 5303:     }
 5304:     return ($datatable,$itemcount);
 5305: }
 5306: 
 5307: sub print_ltitools {
 5308:     my ($position,$dom,$settings,$rowtotal) = @_;
 5309:     my (%rules,%encrypt,%privkeys,%linkprot);
 5310:     if (ref($settings) eq 'HASH') {
 5311:         if ($position eq 'top') {
 5312:             if (exists($settings->{'encrypt'})) {
 5313:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 5314:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 5315:                         $encrypt{'toolsec_'.$key} = $settings->{'encrypt'}{$key};
 5316:                     }
 5317:                 }
 5318:             }
 5319:             if (exists($settings->{'private'})) {
 5320:                 if (ref($settings->{'private'}) eq 'HASH') {
 5321:                     if (ref($settings->{'private'}) eq 'HASH') {
 5322:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 5323:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 5324:                         }
 5325:                     }
 5326:                 }
 5327:             }
 5328:         } elsif ($position eq 'middle') {
 5329:             if (exists($settings->{'rules'})) {
 5330:                 if (ref($settings->{'rules'}) eq 'HASH') {
 5331:                     %rules = %{$settings->{'rules'}};
 5332:                 }
 5333:             }
 5334:         } else {
 5335:             foreach my $key ('encrypt','private','rules') {
 5336:                 if (exists($settings->{$key})) {
 5337:                     delete($settings->{$key});
 5338:                 }
 5339:             }
 5340:         }
 5341:     }
 5342:     my $datatable;
 5343:     my $itemcount = 1;
 5344:     if ($position eq 'top') {
 5345:         $datatable = &secrets_form($dom,'toolsec',\%encrypt,\%privkeys,$rowtotal);
 5346:     } elsif ($position eq 'middle') {
 5347:         $datatable = &password_rules('toolsecrets',\$itemcount,\%rules);
 5348:         $$rowtotal += $itemcount;
 5349:     } else {
 5350:         $datatable = &Apache::courseprefs::print_ltitools($dom,'',$settings,\$rowtotal,'','','domain');
 5351:     }
 5352:     return $datatable;
 5353: }
 5354: 
 5355: sub ltitools_names {
 5356:     my %lt = &Apache::lonlocal::texthash(
 5357:                                           'title'          => 'Title',
 5358:                                           'version'        => 'Version',
 5359:                                           'msgtype'        => 'Message Type',
 5360:                                           'sigmethod'      => 'Signature Method',
 5361:                                           'url'            => 'URL',
 5362:                                           'key'            => 'Key',
 5363:                                           'lifetime'       => 'Nonce lifetime (s)',
 5364:                                           'secret'         => 'Secret',
 5365:                                           'icon'           => 'Icon',
 5366:                                           'user'           => 'User',
 5367:                                           'fullname'       => 'Full Name',
 5368:                                           'firstname'      => 'First Name',
 5369:                                           'lastname'       => 'Last Name',
 5370:                                           'email'          => 'E-mail',
 5371:                                           'roles'          => 'Role',
 5372:                                           'window'         => 'Window',
 5373:                                           'tab'            => 'Tab',
 5374:                                           'iframe'         => 'iFrame',
 5375:                                           'height'         => 'Height',
 5376:                                           'width'          => 'Width',
 5377:                                           'linktext'       => 'Default Link Text',
 5378:                                           'explanation'    => 'Default Explanation',
 5379:                                           'passback'       => 'Tool can return grades:',
 5380:                                           'roster'         => 'Tool can retrieve roster:',
 5381:                                           'crstarget'      => 'Display target',
 5382:                                           'crslabel'       => 'Course label',
 5383:                                           'crstitle'       => 'Course title',
 5384:                                           'crslinktext'    => 'Link Text',
 5385:                                           'crsexplanation' => 'Explanation',
 5386:                                           'crsappend'      => 'Provider URL',
 5387:                                         );
 5388:     return %lt;
 5389: }
 5390: 
 5391: sub secrets_form {
 5392:     my ($dom,$context,$encrypt,$privkeys,$rowtotal) = @_;
 5393:     my @ids=&Apache::lonnet::current_machine_ids();
 5394:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 5395:     my $primary = &Apache::lonnet::domain($dom,'primary');
 5396:     my ($css_class,$extra,$numshown,$itemcount,$output);
 5397:     $itemcount = 0;
 5398:     foreach my $hostid (sort(keys(%servers))) {
 5399:         my ($showextra,$divsty,$switch);
 5400:         if ($hostid eq $primary) {
 5401:             if ($context eq 'ltisec') {
 5402:                 if (($encrypt->{'ltisec_consumers'}) || ($encrypt->{'ltisec_domlinkprot'})) {
 5403:                     $showextra = 1;
 5404:                 }
 5405:                 if ($encrypt->{'ltisec_crslinkprot'}) {
 5406:                     $showextra = 1;
 5407:                 }
 5408:             } else {
 5409:                 if (($encrypt->{'toolsec_crs'}) || ($encrypt->{'toolsec_dom'})) {
 5410:                     $showextra = 1;
 5411:                 }
 5412:             }
 5413:             unless (grep(/^\Q$hostid\E$/,@ids)) {
 5414:                 $switch = 1;
 5415:             }
 5416:             if ($showextra) {
 5417:                 $numshown ++;
 5418:                 $divsty = 'display:inline-block';
 5419:             } else {
 5420:                 $divsty = 'display:none';
 5421:             }
 5422:             $extra .= '<fieldset id="'.$context.'_info_'.$hostid.'" style="'.$divsty.'">'.
 5423:                       '<legend>'.$hostid.'</legend>';
 5424:             if ($switch) {
 5425:                 my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
 5426:                                    &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 5427:                                    '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 5428:                 if (exists($privkeys->{$hostid})) {
 5429:                     $extra .= '<div id="'.$context.'_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
 5430:                               '<span class="LC_nobreak">'.
 5431:                               &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 5432:                               '<span class="LC_nobreak">'.&mt('Change?').
 5433:                               '<label><input type="radio" value="0" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 5434:                               ('&nbsp;'x2).
 5435:                               '<label><input type="radio" value="1" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" />'.&mt('Yes').
 5436:                               '</label>&nbsp;&nbsp;</span><div id="'.$context.'_divchgprivkey_'.$hostid.'" style="display:none" />'.
 5437:                               '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 5438:                               '</span></div>';
 5439:                 } else {
 5440:                     $extra .= '<span class="LC_nobreak">'.
 5441:                               &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 5442:                               '</span>'."\n";
 5443:                 }
 5444:             } elsif (exists($privkeys->{$hostid})) {
 5445:                 $extra .= '<div id="'.$context.'_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
 5446:                           &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 5447:                           '<span class="LC_nobreak">'.&mt('Change?').
 5448:                           '<label><input type="radio" value="0" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 5449:                           ('&nbsp;'x2).
 5450:                           '<label><input type="radio" value="1" name="'.$context.'_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$context','$hostid'".');" />'.&mt('Yes').
 5451:                           '</label>&nbsp;&nbsp;</span><div id="'.$context.'_divchgprivkey_'.$hostid.'" style="display:none" />'.
 5452:                           '<span class="LC_nobreak">'.&mt('New Key').':'.
 5453:                           '<input type="password" size="20" name="'.$context.'_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
 5454:                           '<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>'.
 5455:                           '</span></div>';
 5456:             } else {
 5457:                 $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
 5458:                           '<input type="password" size="20" name="'.$context.'_privkey_'.$hostid.'" value="" autocomplete="new-password" />'.
 5459:                           '<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>';
 5460:             }
 5461:             $extra .= '</fieldset>';
 5462:         }
 5463:     }
 5464:     my (%choices,@toggles,%defaultchecked);
 5465:     if ($context eq 'ltisec') {
 5466:         %choices = &Apache::lonlocal::texthash (
 5467:                                                   ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
 5468:                                                   ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
 5469:                                                   ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
 5470:                                                );
 5471:         @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
 5472:         %defaultchecked = (
 5473:                            'ltisec_crslinkprot' => 'off',
 5474:                            'ltisec_domlinkprot' => 'off',
 5475:                            'ltisec_consumers'   => 'off',
 5476:                           );
 5477:     } else {
 5478:         %choices = &Apache::lonlocal::texthash (
 5479:                                                   toolsec_crs => 'Encrypt stored external tool secrets defined in courses',
 5480:                                                   toolsec_dom => 'Encrypt stored external tool secrets defined in domain',
 5481:                                                );
 5482:         @toggles = qw(toolsec_crs toolsec_dom);
 5483:         %defaultchecked = (
 5484:                            'toolsec_crs' => 'off',
 5485:                            'toolsec_dom' => 'off',
 5486:                           );
 5487:     }
 5488:     my ($onclick,$itemcount);
 5489:     $onclick = 'javascript:toggleLTIEncKey(this.form,'."'$context'".');';
 5490:     ($output,$itemcount) = &radiobutton_prefs($encrypt,\@toggles,\%defaultchecked,
 5491:                                               \%choices,$itemcount,$onclick,'','left','no');
 5492: 
 5493:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5494:     my $noprivkeysty = 'display:inline-block';
 5495:     if ($numshown) {
 5496:         $noprivkeysty = 'display:none';
 5497:     }
 5498:     $output .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
 5499:                '<td><div id="'.$context.'_noprivkey" style="'.$noprivkeysty.'" >'.
 5500:                '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
 5501:                $extra.
 5502:                '</td></tr>';
 5503:     $itemcount ++;
 5504:     $$rowtotal += $itemcount;
 5505:     return $output;
 5506: }
 5507: 
 5508: sub print_proctoring {
 5509:     my ($dom,$settings,$rowtotal) = @_;
 5510:     my $itemcount = 1;
 5511:     my (%ordered,%providernames,%current,%currentdef);
 5512:     my $confname = $dom.'-domainconfig';
 5513:     my $switchserver = &check_switchserver($dom,$confname);
 5514:     if (ref($settings) eq 'HASH') {
 5515:         foreach my $item (keys(%{$settings})) {
 5516:             if (ref($settings->{$item}) eq 'HASH') {
 5517:                 my $num = $settings->{$item}{'order'};
 5518:                 $ordered{$num} = $item;
 5519:             }
 5520:         }
 5521:     } else {
 5522:         %ordered = (
 5523:                      1 => 'proctorio',
 5524:                      2 => 'examity',
 5525:                    );
 5526:     }
 5527:     %providernames = &proctoring_providernames();
 5528:     my $maxnum = scalar(keys(%ordered));
 5529:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
 5530:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
 5531:     if (ref($requref) eq 'HASH') {
 5532:         %requserfields = %{$requref};
 5533:     }
 5534:     if (ref($opturef) eq 'HASH') {
 5535:         %optuserfields = %{$opturef};
 5536:     }
 5537:     if (ref($defref) eq 'HASH') {
 5538:         %defaults = %{$defref};
 5539:     }
 5540:     if (ref($extref) eq 'HASH') {
 5541:         %extended = %{$extref};
 5542:     }
 5543:     if (ref($crsref) eq 'HASH') {
 5544:         %crsconf = %{$crsref};
 5545:     }
 5546:     if (ref($rolesref) eq 'ARRAY') {
 5547:         @courseroles = @{$rolesref};
 5548:     }
 5549:     if (ref($ltiref) eq 'ARRAY') {
 5550:         @ltiroles = @{$ltiref};
 5551:     }
 5552:     my $datatable;
 5553:     my $css_class;
 5554:     if (keys(%ordered)) {
 5555:         my @items = sort { $a <=> $b } keys(%ordered);
 5556:         for (my $i=0; $i<@items; $i++) {
 5557:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5558:             my $provider = $ordered{$items[$i]};
 5559:             my $optionsty = 'none';
 5560:             my ($available,$version,$lifetime,$imgsrc,$userincdom,$showroles,
 5561:                 %checkedfields,%rolemaps,%inuse,%crsconfig,%current);
 5562:             if (ref($settings) eq 'HASH') {
 5563:                 if (ref($settings->{$provider}) eq 'HASH') {
 5564:                     %current = %{$settings->{$provider}};
 5565:                     if ($current{'available'}) {
 5566:                         $optionsty = 'block';
 5567:                         $available = 1;
 5568:                     }
 5569:                     if ($current{'lifetime'} =~ /^\d+$/) {
 5570:                         $lifetime = $current{'lifetime'};
 5571:                     }
 5572:                     if ($current{'version'} =~ /^\d+\.\d+$/) {
 5573:                         $version = $current{'version'};
 5574:                     }
 5575:                     if ($current{'image'} ne '') {
 5576:                         $imgsrc = '<img src="'.$current{'image'}.'" alt="'.&mt('Proctoring service icon').'" />';
 5577:                     }
 5578:                     if (ref($current{'fields'}) eq 'ARRAY') {
 5579:                         map { $checkedfields{$_} = 1; } @{$current{'fields'}};
 5580:                     }
 5581:                     $userincdom = $current{'incdom'};
 5582:                     if (ref($current{'roles'}) eq 'HASH') {
 5583:                         %rolemaps = %{$current{'roles'}};
 5584:                         $checkedfields{'roles'} = 1;
 5585:                     }
 5586:                     if (ref($current{'defaults'}) eq 'ARRAY') {
 5587:                         foreach my $val (@{$current{'defaults'}}) {
 5588:                             if (grep(/^\Q$val\E$/,@{$defaults{$provider}})) {
 5589:                                 $inuse{$val} = 1;
 5590:                             } else {
 5591:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5592:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5593:                                         if (grep(/^\Q$val\E$/,@{$extended{$provider}{$poss}})) {
 5594:                                             $inuse{$poss} = $val;
 5595:                                             last;
 5596:                                         }
 5597:                                     }
 5598:                                 }
 5599:                             }
 5600:                         }
 5601:                     } elsif (ref($current{'defaults'}) eq 'HASH') {
 5602:                         foreach my $key (keys(%{$current{'defaults'}})) {
 5603:                             my $currval = $current{'defaults'}{$key}; 
 5604:                             if (grep(/^\Q$key\E$/,@{$defaults{$provider}})) {
 5605:                                 $inuse{$key} = 1;
 5606:                             } else {
 5607:                                 my $match;
 5608:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5609:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5610:                                         if (grep(/^\Q$key\E$/,@{$extended{$provider}{$poss}})) {
 5611:                                             $inuse{$poss} = $key;
 5612:                                             last;
 5613:                                         }
 5614:                                     } elsif (ref($extended{$provider}{$poss}) eq 'HASH') {
 5615:                                         foreach my $inner (sort(keys(%{$extended{$provider}{$poss}}))) {
 5616:                                             if (ref($extended{$provider}{$poss}{$inner}) eq 'ARRAY') {
 5617:                                                 if (grep(/^\Q$currval\E$/,@{$extended{$provider}{$poss}{$inner}})) {
 5618:                                                     $currentdef{$inner} = $currval;
 5619:                                                     $match = 1;
 5620:                                                     last;
 5621:                                                 }
 5622:                                             } elsif ($inner eq $key) {
 5623:                                                 $currentdef{$key} = $currval;
 5624:                                                 $match = 1;
 5625:                                                 last;
 5626:                                             }
 5627:                                         }
 5628:                                     }
 5629:                                     last if ($match);
 5630:                                 }
 5631:                             }
 5632:                         }
 5633:                     }
 5634:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
 5635:                         map { $crsconfig{$_} = 1; } @{$current{'crsconf'}};
 5636:                     }
 5637:                 }
 5638:             }
 5639:             my %lt = &proctoring_titles($provider);
 5640:             my %fieldtitles = &proctoring_fieldtitles($provider);
 5641:             my $onclickavailable = ' onclick="toggleProctoring(this.form,'."'$provider'".');"';
 5642:             my %checkedavailable = (
 5643:                                    yes => '',
 5644:                                    no  => ' checked="checked"',
 5645:                                  );
 5646:             if ($available) {
 5647:                 $checkedavailable{'yes'} = $checkedavailable{'no'};
 5648:                 $checkedavailable{'no'} = '';
 5649:             }
 5650:             my $chgstr = ' onchange="javascript:reorderProctoring(this.form,'."'proctoring_pos_".$provider."'".');"';
 5651:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5652:                          .'<select name="proctoring_pos_'.$provider.'"'.$chgstr.'>';
 5653:             for (my $k=0; $k<$maxnum; $k++) {
 5654:                 my $vpos = $k+1;
 5655:                 my $selstr;
 5656:                 if ($k == $i) {
 5657:                     $selstr = ' selected="selected" ';
 5658:                 }
 5659:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5660:             }
 5661:             if ($version eq '') {
 5662:                 if ($provider eq 'proctorio') {
 5663:                     $version = '1.0';
 5664:                 } elsif ($provider eq 'examity') {
 5665:                     $version = '1.1';
 5666:                 }
 5667:             }
 5668:             if ($lifetime eq '') {
 5669:                 $lifetime = '300';
 5670:             }
 5671:             $datatable .=
 5672:                 '</select>'.('&nbsp;'x2).'<b>'.$providernames{$provider}.'</b></span><br />'.
 5673:                 '<span class="LC_nobreak">'.$lt{'avai'}.'&nbsp;'.
 5674:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="1"'.$onclickavailable.$checkedavailable{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5675:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="0"'.$onclickavailable.$checkedavailable{no}.' />'.&mt('No').'</label></span>'."\n".
 5676:                 '</td>'.
 5677:                 '<td colspan="2">'.
 5678:                 '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'base'}.'</legend>'.
 5679:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="proctoring_'.$provider.'_version">'.
 5680:                 '<option value="'.$version.'" selected="selected">'.$version.'</option></select></span> '."\n".
 5681:                 ('&nbsp;'x2).
 5682:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="proctoring_'.$provider.'_sigmethod">'.
 5683:                 '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5684:                 '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5685:                 ('&nbsp;'x2).
 5686:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="proctoring_'.$provider.'_lifetime" value="'.$lifetime.'" /></span> '."\n".
 5687:                 '<br />'.
 5688:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="proctoring_'.$provider.'_url" value="'.$current{'url'}.'" /></span> '."\n".
 5689:                 '<br />'.
 5690:                 '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="proctoring_'.$provider.'_key" value="'.$current{'key'}.'" /></span> '."\n".
 5691:                 ('&nbsp;'x2).
 5692:                 '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="proctoring_'.$provider.'_secret" value="'.$current{'secret'}.'" />'.
 5693:                 '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.proctoring_'.$provider.'_secret.type='."'text'".' } else { this.form.proctoring_'.$provider.'_secret.type='."'password'".' }" />'.$lt{'visible'}.'</label></span><br />'."\n";
 5694:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 5695:             if ($imgsrc) {
 5696:                 $datatable .= $imgsrc.
 5697:                               '<label><input type="checkbox" name="proctoring_image_del"'.
 5698:                               ' value="'.$provider.'" />'.&mt('Delete?').'</label></span> '.
 5699:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:');
 5700:             }
 5701:             $datatable .= '&nbsp;';
 5702:             if ($switchserver) {
 5703:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5704:             } else {
 5705:                 $datatable .= '<input type="file" name="proctoring_image_'.$provider.'" value="" />';
 5706:             }
 5707:             unless ($imgsrc) {
 5708:                 $datatable .= '<br />('.&mt('if larger than 21x21 pixels, image will be scaled').')';
 5709:             }
 5710:             $datatable .= '</fieldset>'."\n";
 5711:             if (ref($requserfields{$provider}) eq 'ARRAY') {
 5712:                 if (@{$requserfields{$provider}} > 0) {
 5713:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'requ'}.'</legend>';
 5714:                     foreach my $field (@{$requserfields{$provider}}) {
 5715:                         $datatable .= '<span class="LC_nobreak">'.
 5716:                                       '<label><input type="checkbox" name="proctoring_reqd_'.$provider.'" value="'.$field.'" checked="checked" disabled="disabled" />'.
 5717:                                       $lt{$field}.'</label>';
 5718:                         if ($field eq 'user') {
 5719:                             my $seluserdom = '';
 5720:                             my $unseluserdom = ' selected="selected"';
 5721:                             if ($userincdom) {
 5722:                                 $seluserdom = $unseluserdom;
 5723:                                 $unseluserdom = '';
 5724:                             }
 5725:                             $datatable .= ':&nbsp;'.
 5726:                                 '<select name="proctoring_userincdom_'.$provider.'">'.
 5727:                                 '<option value="0"'.$unseluserdom.'>'.$lt{'username'}.'</option>'.
 5728:                                 '<option value="1"'.$seluserdom.'>'.$lt{'uname:dom'}.'</option>'.
 5729:                                 '</select>&nbsp;';
 5730:                         } else {
 5731:                             $datatable .= '&nbsp;';
 5732:                             if ($field eq 'roles') {
 5733:                                 $showroles = 1; 
 5734:                             } 
 5735:                         }
 5736:                         $datatable .= '</span> ';
 5737:                     }
 5738:                 }
 5739:                 $datatable .= '</fieldset>'."\n";
 5740:             }
 5741:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
 5742:                 if (@{$optuserfields{$provider}} > 0) {
 5743:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'optu'}.'</legend>'; 
 5744:                     foreach my $field (@{$optuserfields{$provider}}) {
 5745:                         my $checked;
 5746:                         if ($checkedfields{$field}) {
 5747:                             $checked = ' checked="checked"';
 5748:                         }
 5749:                         $datatable .= '<span class="LC_nobreak">'.
 5750:                                       '<label><input type="checkbox" name="proctoring_optional_'.$provider.'" value="'.$field.'"'.$checked.' />'.$lt{$field}.'</label></span>&nbsp; ';
 5751:                     }
 5752:                     $datatable .= '</fieldset>'."\n";
 5753:                 }
 5754:             }
 5755:             if (ref($defaults{$provider}) eq 'ARRAY') {
 5756:                 if (@{$defaults{$provider}}) {
 5757:                     my (%options,@selectboxes);
 5758:                     if (ref($extended{$provider}) eq 'HASH') {
 5759:                         %options = %{$extended{$provider}};
 5760:                     }
 5761:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'defa'}.'</legend>';
 5762:                     my ($rem,$numinrow,$dropdowns);
 5763:                     if ($provider eq 'proctorio') { 
 5764:                         $datatable .= '<table>';
 5765:                         $numinrow = 4;
 5766:                     }
 5767:                     my $i = 0;
 5768:                     foreach my $field (@{$defaults{$provider}}) {
 5769:                         my $checked;
 5770:                         if ($inuse{$field}) {
 5771:                             $checked = ' checked="checked"';
 5772:                         }
 5773:                         if ($provider eq 'examity') {
 5774:                             if ($field eq 'display') {
 5775:                                 $datatable .= '<span class="LC_nobreak">'.&mt('Display target:');
 5776:                                 foreach my $option ('iframe','tab','window') {
 5777:                                     my $checkdisp;
 5778:                                     if ($currentdef{'target'} eq $option) {
 5779:                                         $checkdisp = ' checked="checked"';
 5780:                                     }
 5781:                                     $datatable .= '<label><input type="radio" name="proctoring_target_'.$provider.'" value="'.$option.'"'.$checkdisp.' />'.
 5782:                                     $fieldtitles{$option}.'</label>'.('&nbsp;'x2);
 5783:                                 }
 5784:                                 $datatable .= ('&nbsp;'x4);
 5785:                                 foreach my $dimen ('width','height') {
 5786:                                     $datatable .= '<label>'.$fieldtitles{$dimen}.'&nbsp;'.
 5787:                                                   '<input type="text" name="proctoring_'.$dimen.'_'.$provider.'" size="5" '.
 5788:                                                   'value="'.$currentdef{$dimen}.'" /></label>'.
 5789:                                                   ('&nbsp;'x2);
 5790:                                 }
 5791:                                 $datatable .= '</span><br />'.
 5792:                                               '<div class="LC_left_float">'.$fieldtitles{'linktext'}.'<br />'.
 5793:                                               '<input type="text" name="proctoring_linktext_'.$provider.'" '.
 5794:                                               'size="25" value="'.$currentdef{'linktext'}.'" /></div>'.
 5795:                                               '<div class="LC_left_float">'.$fieldtitles{'explanation'}.'<br />'.
 5796:                                               '<textarea name="proctoring_explanation_'.$provider.'" rows="5" cols="40">'.
 5797:                                               $currentdef{'explanation'}.
 5798:                                               '</textarea></div><div style=""></div><br />';
 5799:                             }
 5800:                         } else {
 5801:                             if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
 5802:                                 my ($output,$selnone);
 5803:                                 unless ($checked) {
 5804:                                     $selnone = ' selected="selected"';
 5805:                                 }
 5806:                                 $output .= '<span class="LC_nobreak">'.$fieldtitles{$field}.': '.
 5807:                                            '<select name="proctoring_defaults_'.$field.'_'.$provider.'">'.
 5808:                                            '<option value=""'.$selnone.'>'.&mt('Not in use').'</option>'; 
 5809:                                 foreach my $option (@{$options{$field}}) {
 5810:                                     my $sel; 
 5811:                                     if ($inuse{$field} eq $option) {
 5812:                                         $sel = ' selected="selected"';
 5813:                                     }
 5814:                                     $output .= '<option value="'.$option.'"'.$sel.'>'.$fieldtitles{$option}.'</option>';
 5815:                                 }
 5816:                                 $output .= '</select></span>';
 5817:                                 push(@selectboxes,$output);
 5818:                             } else {
 5819:                                 $rem = $i%($numinrow);
 5820:                                 if ($rem == 0) {
 5821:                                     if ($i > 0) {
 5822:                                         $datatable .= '</tr>';
 5823:                                     }
 5824:                                     $datatable .= '<tr>';
 5825:                                 }
 5826:                                 $datatable .= '<td class="LC_left_item">'.
 5827:                                               '<span class="LC_nobreak">'.
 5828:                                               '<label><input type="checkbox" name="proctoring_defaults_'.$provider.'" value="'.$field.'"'.$checked.' />'.
 5829:                                               $fieldtitles{$field}.'</label></span></td>';
 5830:                                 $i++;
 5831:                             }
 5832:                         }
 5833:                     }
 5834:                     if ($provider eq 'proctorio') {
 5835:                         if ($numinrow) {
 5836:                             $rem = $i%$numinrow;
 5837:                         }
 5838:                         my $colsleft = $numinrow - $rem;
 5839:                         if ($colsleft > 1) {
 5840:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5841:                         } else {
 5842:                             $datatable .= '<td class="LC_left_item">';
 5843:                         }
 5844:                         $datatable .= '&nbsp;'.
 5845:                                       '</td></tr></table>';
 5846:                         if (@selectboxes) {
 5847:                             $datatable .= '<hr /><table>';
 5848:                             $numinrow = 2;
 5849:                             for (my $i=0; $i<@selectboxes; $i++) {
 5850:                                 $rem = $i%($numinrow);
 5851:                                 if ($rem == 0) {
 5852:                                     if ($i > 0) {
 5853:                                         $datatable .= '</tr>';
 5854:                                     }
 5855:                                     $datatable .= '<tr>';
 5856:                                 }
 5857:                                 $datatable .= '<td class="LC_left_item">'.
 5858:                                               $selectboxes[$i].'</td>';
 5859:                             }
 5860:                             if ($numinrow) {
 5861:                                 $rem = $i%$numinrow;
 5862:                             }
 5863:                             $colsleft = $numinrow - $rem;
 5864:                             if ($colsleft > 1) {
 5865:                                 $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5866:                             } else {
 5867:                                 $datatable .= '<td class="LC_left_item">';
 5868:                             }
 5869:                             $datatable .= '&nbsp;'.
 5870:                                           '</td></tr></table>';
 5871:                         }
 5872:                     }
 5873:                     $datatable .= '</fieldset>';
 5874:                 }
 5875:                 if (ref($crsconf{$provider}) eq 'ARRAY') {
 5876:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5877:                                   '<legend>'.&mt('Configurable in course').'</legend>';
 5878:                     my ($rem,$numinrow);
 5879:                     if ($provider eq 'proctorio') {
 5880:                         $datatable .= '<table>';
 5881:                         $numinrow = 4;
 5882:                     }
 5883:                     my $i = 0;
 5884:                     foreach my $item (@{$crsconf{$provider}}) {
 5885:                         my $name;
 5886:                         if ($provider eq 'examity') {
 5887:                             $name = $lt{'crs'.$item};
 5888:                         } elsif ($provider eq 'proctorio') {
 5889:                             $name = $fieldtitles{$item};
 5890:                             $rem = $i%($numinrow);
 5891:                             if ($rem == 0) {
 5892:                                 if ($i > 0) {
 5893:                                     $datatable .= '</tr>';
 5894:                                 }
 5895:                                 $datatable .= '<tr>';
 5896:                             }
 5897:                             $datatable .= '<td class="LC_left_item>';
 5898:                         }
 5899:                         my $checked;
 5900:                         if ($crsconfig{$item}) {
 5901:                             $checked = ' checked="checked"';
 5902:                         }
 5903:                         $datatable .= '<span class="LC_nobreak"><label>'.
 5904:                                       '<input type="checkbox" name="proctoring_crsconf_'.$provider.'" value="'.$item.'"'.$checked.' />'.
 5905:                                       $name.'</label></span>';
 5906:                         if ($provider eq 'examity') {
 5907:                             $datatable .= '&nbsp; ';
 5908:                         }
 5909:                         $datatable .= "\n";
 5910:                         $i++;
 5911:                     }
 5912:                     if ($provider eq 'proctorio') {
 5913:                         if ($numinrow) {
 5914:                             $rem = $i%$numinrow;
 5915:                         }
 5916:                         my $colsleft = $numinrow - $rem;
 5917:                         if ($colsleft > 1) {
 5918:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5919:                         } else {
 5920:                             $datatable .= '<td class="LC_left_item">';
 5921:                         }
 5922:                         $datatable .= '&nbsp;'.
 5923:                                       '</td></tr></table>';
 5924:                     }
 5925:                     $datatable .= '</fieldset>';
 5926:                 }
 5927:                 if ($showroles) {
 5928:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5929:                                   '<legend>'.&mt('Role mapping').'</legend><table><tr>';
 5930:                     foreach my $role (@courseroles) {
 5931:                         my ($selected,$selectnone);
 5932:                         if (!$rolemaps{$role}) {
 5933:                             $selectnone = ' selected="selected"';
 5934:                         }
 5935:                         $datatable .= '<td style="text-align: center">'.
 5936:                                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5937:                                       '<select name="proctoring_roles_'.$role.'_'.$provider.'">'.
 5938:                                       '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5939:                         foreach my $ltirole (@ltiroles) {
 5940:                             unless ($selectnone) {
 5941:                                 if ($rolemaps{$role} eq $ltirole) {
 5942:                                     $selected = ' selected="selected"';
 5943:                                 } else {
 5944:                                     $selected = '';
 5945:                                 }
 5946:                             }
 5947:                             $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5948:                         }
 5949:                         $datatable .= '</select></td>';
 5950:                     }
 5951:                     $datatable .= '</tr></table></fieldset>'.
 5952:                                   '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5953:                                   '<legend>'.&mt('Custom items sent on launch').'</legend>'.
 5954:                                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5955:                                   '<tr><td></td><td>lms</td>'.
 5956:                                   '<td><input type="text" name="proctoring_customval_lms_'.$provider.'"'.
 5957:                                   ' value="Loncapa" disabled="disabled"/></td></tr>';
 5958:                     if ((ref($settings) eq 'HASH') && (ref($settings->{$provider}) eq 'HASH') &&
 5959:                         (ref($settings->{$provider}->{'custom'}) eq 'HASH')) {
 5960:                         my %custom = %{$settings->{$provider}->{'custom'}};
 5961:                         if (keys(%custom) > 0) {
 5962:                             foreach my $key (sort(keys(%custom))) {
 5963:                                 next if ($key eq 'lms');
 5964:                                 $datatable .= '<tr><td><span class="LC_nobreak">'.
 5965:                                               '<label><input type="checkbox" name="proctoring_customdel_'.$provider.'" value="'.
 5966:                                               $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5967:                                               '<td><input type="text" name="proctoring_customval_'.$key.'_'.$provider.'"'.
 5968:                                               ' value="'.$custom{$key}.'" /></td></tr>';
 5969:                             }
 5970:                         }
 5971:                     }
 5972:                     $datatable .= '<tr><td><span class="LC_nobreak">'.
 5973:                                   '<label><input type="checkbox" name="proctoring_customadd" value="'.$provider.'" />'.
 5974:                                   &mt('Add more').'</label></span></td><td><input type="text" name="proctoring_custom_name_'.$provider.'" />'.
 5975:                                   '</td><td><input type="text" name="proctoring_custom_value_'.$provider.'" /></td></tr>'.
 5976:                                   '</table></fieldset></td></tr>'."\n";
 5977:                 }
 5978:                 $datatable .= '</td></tr>';
 5979:             }
 5980:             $itemcount ++;
 5981:         }
 5982:     }
 5983:     return $datatable;
 5984: }
 5985: 
 5986: sub proctoring_data {
 5987:     my $requserfields = {
 5988:                       proctorio => ['user'],
 5989:                       examity   => ['roles','user'],
 5990:                      };
 5991:     my $optuserfields = {
 5992:                         proctorio => ['fullname'],
 5993:                         examity   => ['fullname','firstname','lastname','email'],
 5994:                      };
 5995:     my $defaults = {
 5996:                   proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 5997:                                 'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 5998:                                 'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 5999:                                 'closetabs','onescreen','print','downloads','cache','rightclick',
 6000:                                 'reentry','calculator','whiteboard'],
 6001:                   examity   => ['display'],
 6002:                 };
 6003:     my $extended = { 
 6004:                   proctorio => {
 6005:                                  verifyid => ['verifyidauto','verifyidlive'],
 6006:                                  fullscreen => ['fullscreenlenient','fullscreenmoderate','fullscreensever'],
 6007:                                  tabslinks => ['notabs','linksonly'],
 6008:                                  reentry => ['noreentry','agentreentry'],
 6009:                                  calculator => ['calculatorbasic','calculatorsci'],
 6010:                                },
 6011:                   examity => {
 6012:                                display => {
 6013:                                            target      => ['iframe','tab','window'],
 6014:                                            width       => '',
 6015:                                            height      => '',
 6016:                                            linktext    => '',
 6017:                                            explanation => '',
 6018:                                           },
 6019:                              },
 6020:                 };
 6021:     my $crsconf = {
 6022:                  proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6023:                                'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6024:                                'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6025:                                'closetabs','onescreen','print','downloads','cache','rightclick',
 6026:                                'reentry','calculator','whiteboard'],
 6027:                  examity => ['label','title','target','linktext','explanation','append'],
 6028:                };
 6029:     my $courseroles = ['cc','in','ta','ep','st'];
 6030:     my $ltiroles = ['Instructor','ContentDeveloper','TeachingAssistant','Learner'];
 6031:     return ($requserfields,$optuserfields,$defaults,$extended,$crsconf,$courseroles,$ltiroles);
 6032: }
 6033: 
 6034: sub proctoring_titles {
 6035:     my ($item) = @_;
 6036:     my (%common_lt,%custom_lt);
 6037:     %common_lt = &Apache::lonlocal::texthash (
 6038:                      'avai'      => 'Available?',
 6039:                      'base'      => 'Basic Settings',
 6040:                      'requ'      => 'User data required to be sent on launch',
 6041:                      'optu'      => 'User data optionally sent on launch',
 6042:                      'udsl'      => 'User data sent on launch',
 6043:                      'defa'      => 'Defaults for items configurable in course',
 6044:                      'sigmethod' => 'Signature Method',
 6045:                      'key'       => 'Key',
 6046:                      'lifetime'  => 'Nonce lifetime (s)',
 6047:                      'secret'    => 'Secret',
 6048:                      'icon'      => 'Icon',
 6049:                      'fullname'  => 'Full Name',
 6050:                      'visible'   => 'Visible input',
 6051:                      'username'  => 'username',
 6052:                      'user'      => 'User',
 6053:                  );
 6054:     if ($item eq 'proctorio') {
 6055:         %custom_lt = &Apache::lonlocal::texthash (
 6056:                          'version'        => 'OAuth version',
 6057:                          'url'            => 'API URL',
 6058:                          'uname:dom'      => 'username-domain',
 6059:         );
 6060:     } elsif ($item eq 'examity') {
 6061:         %custom_lt = &Apache::lonlocal::texthash (
 6062:                          'version'        => 'LTI Version',
 6063:                          'url'            => 'URL',
 6064:                          'uname:dom'      => 'username:domain',
 6065:                          'msgtype'        => 'Message Type',
 6066:                          'firstname'      => 'First Name',
 6067:                          'lastname'       => 'Last Name',
 6068:                          'email'          => 'E-mail',
 6069:                          'roles'          => 'Role',
 6070:                          'crstarget'      => 'Display target',
 6071:                          'crslabel'       => 'Course label',
 6072:                          'crstitle'       => 'Course title', 
 6073:                          'crslinktext'    => 'Link Text',
 6074:                          'crsexplanation' => 'Explanation',
 6075:                          'crsappend'      => 'Provider URL',
 6076:         );
 6077:     }
 6078:     my %lt = (%common_lt,%custom_lt);
 6079:     return %lt;
 6080: }
 6081: 
 6082: sub proctoring_fieldtitles {
 6083:     my ($item) = @_;
 6084:     if ($item eq 'proctorio') {
 6085:         return &Apache::lonlocal::texthash (
 6086:                   'recordvideo' => 'Record video',
 6087:                   'recordaudio' => 'Record audio',
 6088:                   'recordscreen' => 'Record screen',
 6089:                   'recordwebtraffic' => 'Record web traffic',
 6090:                   'recordroomstart' => 'Record room scan',
 6091:                   'verifyvideo' => 'Verify webcam',
 6092:                   'verifyaudio' => 'Verify microphone',
 6093:                   'verifydesktop' => 'Verify desktop recording',
 6094:                   'verifyid' => 'Photo ID verification',
 6095:                   'verifysignature' => 'Require signature',
 6096:                   'fullscreen' => 'Fullscreen',
 6097:                   'clipboard' => 'Disable copy/paste',
 6098:                   'tabslinks' => 'New tabs/windows',
 6099:                   'closetabs' => 'Close other tabs',
 6100:                   'onescreen' => 'Limit to single screen',
 6101:                   'print' => 'Disable Printing',
 6102:                   'downloads' => 'Disable Downloads',
 6103:                   'cache' => 'Empty cache after exam',
 6104:                   'rightclick' => 'Disable right click',
 6105:                   'reentry' => 'Re-entry to exam',
 6106:                   'calculator' => 'Onscreen calculator',
 6107:                   'whiteboard' => 'Onscreen whiteboard',
 6108:                   'verifyidauto' => 'Automated verification',
 6109:                   'verifyidlive' => 'Live agent verification',
 6110:                   'fullscreenlenient' => 'Forced, but can navigate away for up to 30s',
 6111:                   'fullscreenmoderate' => 'Forced, but can navigate away for up to 15s',
 6112:                   'fullscreensever' => 'Forced, navigation away ends exam',
 6113:                   'notabs' => 'Disaallowed',
 6114:                   'linksonly' => 'Allowed from links in exam',
 6115:                   'noreentry' => 'Disallowed',
 6116:                   'agentreentry' => 'Agent required for re-entry',
 6117:                   'calculatorbasic' => 'Basic',
 6118:                   'calculatorsci' => 'Scientific',
 6119:         );
 6120:     } elsif ($item eq 'examity') {
 6121:         return &Apache::lonlocal::texthash (
 6122:                 'target'         => 'Display target',   
 6123:                 'window'         => 'Window',
 6124:                 'tab'            => 'Tab',
 6125:                 'iframe'         => 'iFrame',
 6126:                 'height'         => 'Height (pixels)',
 6127:                 'width'          => 'Width (pixels)',
 6128:                 'linktext'       => 'Default Link Text',
 6129:                 'explanation'    => 'Default Explanation',
 6130:                 'append'         => 'Provider URL',
 6131:         );
 6132:     }
 6133: }
 6134: 
 6135: sub proctoring_providernames {
 6136:     return (
 6137:              proctorio => 'Proctorio',
 6138:              examity   => 'Examity',
 6139:            );
 6140: }
 6141: 
 6142: sub print_lti {
 6143:     my ($position,$dom,$settings,$rowtotal) = @_;
 6144:     my $itemcount = 1;
 6145:     my ($datatable,$css_class);
 6146:     my (%rules,%encrypt,%privkeys,%linkprot);
 6147:     if (ref($settings) eq 'HASH') {
 6148:         if ($position eq 'top') {
 6149:             if (exists($settings->{'encrypt'})) {
 6150:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 6151:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 6152:                         if ($key eq 'consumers') {
 6153:                             $encrypt{'ltisec_'.$key} = $settings->{'encrypt'}{$key};
 6154:                         } else {
 6155:                             $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
 6156:                         }
 6157:                     }
 6158:                 }
 6159:             }
 6160:             if (exists($settings->{'private'})) {
 6161:                 if (ref($settings->{'private'}) eq 'HASH') {
 6162:                     if (ref($settings->{'private'}) eq 'HASH') {
 6163:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 6164:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 6165:                         }
 6166:                     }
 6167:                 }
 6168:             }
 6169:         } elsif ($position eq 'middle') {
 6170:             if (exists($settings->{'rules'})) {
 6171:                 if (ref($settings->{'rules'}) eq 'HASH') {
 6172:                     %rules = %{$settings->{'rules'}};
 6173:                 }
 6174:             }
 6175:         } elsif ($position eq 'lower') {
 6176:             if (exists($settings->{'linkprot'})) {
 6177:                 if (ref($settings->{'linkprot'}) eq 'HASH') {
 6178:                     %linkprot = %{$settings->{'linkprot'}};
 6179:                     if ($linkprot{'lock'}) {
 6180:                         delete($linkprot{'lock'});
 6181:                     }
 6182:                 }
 6183:             }
 6184:         } else {
 6185:             foreach my $key ('encrypt','private','rules','linkprot') {
 6186:                 if (exists($settings->{$key})) {
 6187:                     delete($settings->{$key});
 6188:                 }
 6189:             }
 6190:         }
 6191:     }
 6192:     if ($position eq 'top') {
 6193:         $datatable = &secrets_form($dom,'ltisec',\%encrypt,\%privkeys,$rowtotal);
 6194:     } elsif ($position eq 'middle') {
 6195:         $datatable = &password_rules('ltisecrets',\$itemcount,\%rules);
 6196:         $$rowtotal += $itemcount;
 6197:     } elsif ($position eq 'lower') {
 6198:          $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
 6199:     } else {
 6200:         my ($switchserver,$switchmessage);
 6201:         $switchserver = &check_switchserver($dom);
 6202:         $switchmessage = &mt("submit from domain's primary library server: [_1].",$switchserver);
 6203:         my $maxnum = 0;
 6204:         my %ordered;
 6205:         if (ref($settings) eq 'HASH') {
 6206:             foreach my $item (keys(%{$settings})) {
 6207:                 if (ref($settings->{$item}) eq 'HASH') {
 6208:                     my $num = $settings->{$item}{'order'};
 6209:                     if ($num eq '') {
 6210:                         $num = scalar(keys(%{$settings}));
 6211:                     }
 6212:                     $ordered{$num} = $item;
 6213:                 }
 6214:             }
 6215:         }
 6216:         $maxnum = scalar(keys(%ordered));
 6217:         my %lt = &lti_names();
 6218:         if (keys(%ordered)) {
 6219:             my @items = sort { $a <=> $b } keys(%ordered);
 6220:             for (my $i=0; $i<@items; $i++) {
 6221:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6222:                 my $item = $ordered{$items[$i]};
 6223:                 my ($key,$secret,$usable,$lifetime,$consumer,$requser,$crsinc,$current);
 6224:                 if (ref($settings->{$item}) eq 'HASH') {
 6225:                     $key = $settings->{$item}->{'key'};
 6226:                     $usable = $settings->{$item}->{'usable'};
 6227:                     $lifetime = $settings->{$item}->{'lifetime'};
 6228:                     $consumer = $settings->{$item}->{'consumer'};
 6229:                     $requser = $settings->{$item}->{'requser'};
 6230:                     $crsinc = $settings->{$item}->{'crsinc'};
 6231:                     $current = $settings->{$item};
 6232:                 }
 6233:                 my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 6234:                 my %checkedrequser = (
 6235:                                        yes => ' checked="checked"',
 6236:                                        no  => '',
 6237:                                      );
 6238:                 if (!$requser) {
 6239:                     $checkedrequser{'no'} = $checkedrequser{'yes'};
 6240:                     $checkedrequser{'yes'} = '';
 6241:                 }
 6242:                 my $onclickcrsinc = ' onclick="toggleLTI(this.form,'."'crsinc','$i'".');"';
 6243:                 my %checkedcrsinc = (
 6244:                                       yes => ' checked="checked"',
 6245:                                       no  => '',
 6246:                                     );
 6247:                 if (!$crsinc) {
 6248:                     $checkedcrsinc{'no'} = $checkedcrsinc{'yes'};
 6249:                     $checkedcrsinc{'yes'} = '';
 6250:                 }
 6251:                 my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 6252:                 $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6253:                              .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 6254:                 for (my $k=0; $k<=$maxnum; $k++) {
 6255:                     my $vpos = $k+1;
 6256:                     my $selstr;
 6257:                     if ($k == $i) {
 6258:                         $selstr = ' selected="selected" ';
 6259:                     }
 6260:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6261:                 }
 6262:                 $datatable .= '</select>'.('&nbsp;'x2).
 6263:                     '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 6264:                     &mt('Delete?').'</label></span></td>'.
 6265:                     '<td colspan="2">'.
 6266:                     '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6267:                     '<span class="LC_nobreak">'.$lt{'consumer'}.
 6268:                     ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 6269:                     ('&nbsp;'x2).
 6270:                     '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 6271:                     '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 6272:                     ('&nbsp;'x2).
 6273:                     '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 6274:                     'value="'.$lifetime.'" size="3" /></span><br /><br />';
 6275:                 if ($key ne '') {
 6276:                     $datatable .= '<span class="LC_nobreak">'.$lt{'key'};
 6277:                     if ($switchserver) {
 6278:                         $datatable .= ': ['.&mt('[_1] to view/edit',$switchserver).']';
 6279:                     } else {
 6280:                         $datatable .= ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" autocomplete="off" />';
 6281:                     }
 6282:                     $datatable .= '</span> '.('&nbsp;'x2);
 6283:                 } elsif (!$switchserver) {
 6284:                     $datatable .= '<span class="LC_nobreak">'.$lt{'key'}.':'.
 6285:                                   '<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" autocomplete="off" />'.
 6286:                                   '</span> '.('&nbsp;'x2);
 6287:                 }
 6288:                 if ($switchserver) {
 6289:                     if ($usable ne '') {
 6290:                         $datatable .= '<div id="lti_divcurrsecret_'.$i.'" style="display:inline-block" /><span class="LC_nobreak">'.
 6291:                                       $lt{'secret'}.': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6292:                                       '<span class="LC_nobreak">'.&mt('Change secret?').
 6293:                                       '<label><input type="radio" value="0" name="lti_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','lti'".');" checked="checked" />'.&mt('No').'</label>'.
 6294:                                       ('&nbsp;'x2).
 6295:                                      '<label><input type="radio" value="1" name="lti_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','lti'".');" />'.&mt('Yes').'</label>'.('&nbsp;'x2).
 6296:                                       '</span><div id="lti_divchgsecret_'.$i.'" style="display:none" />'.
 6297:                                       '<span class="LC_nobreak"> - '.$switchmessage.'</span>'.
 6298:                                       '</div>';
 6299:                     } elsif ($key eq '') {
 6300:                         $datatable .= '<span class="LC_nobreak">'.&mt('Key and Secret are required').' - '.$switchmessage.'</span>'."\n";
 6301:                     } else {
 6302:                         $datatable .= '<span class="LC_nobreak">'.&mt('Secret required').' - '.$switchmessage.'</span>'."\n";
 6303:                     }
 6304:                 } else {
 6305:                     if ($usable ne '') {
 6306:                         $datatable .= '<div id="lti_divcurrsecret_'.$i.'" style="display:inline-block" /><span class="LC_nobreak">'.
 6307:                                       $lt{'secret'}.': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6308:                                       '<span class="LC_nobreak">'.&mt('Change?').
 6309:                                       '<label><input type="radio" value="0" name="lti_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','lti'".');" checked="checked" />'.&mt('No').'</label>'.
 6310:                                       ('&nbsp;'x2).
 6311:                                       '<label><input type="radio" value="1" name="lti_changesecret_'.$i.'" onclick="javascript:toggleChgSecret(this.form,'."'$i','secret','lti'".');" />'.&mt('Yes').
 6312:                                       '</label>&nbsp;&nbsp;</span><div id="lti_divchgsecret_'.$i.'" style="display:none" />'.
 6313:                                       '<span class="LC_nobreak">'.&mt('New Secret').':'.
 6314:                                       '<input type="password" size="20" name="lti_secret_'.$i.'" value="" autocomplete="new-password" />'.
 6315:                                       '<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>';
 6316:                     } else {
 6317:                         $datatable .=
 6318:                             '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 6319:                             '<input type="password" size="20" name="lti_secret_'.$i.'" value="" autocomplete="new-password" />'.
 6320:                             '<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>';
 6321:                     }
 6322:                 }
 6323:                 $datatable .= '<br /><br />'.
 6324:                     '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6325:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6326:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 6327:                     '<br /><br />'.
 6328:                     '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6329:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="1"'.$onclickcrsinc.$checkedcrsinc{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6330:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="0"'.$onclickcrsinc.$checkedcrsinc{no}.' />'.&mt('No').'</label></span>'."\n".
 6331:                     ('&nbsp;'x4).
 6332:                     '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 6333:                     '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 6334:                 $itemcount ++;
 6335:             }
 6336:         }
 6337:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6338:         my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 6339:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 6340:                       '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 6341:                       '<select name="lti_pos_add"'.$chgstr.'>';
 6342:         for (my $k=0; $k<$maxnum+1; $k++) {
 6343:             my $vpos = $k+1;
 6344:             my $selstr;
 6345:             if ($k == $maxnum) {
 6346:                 $selstr = ' selected="selected" ';
 6347:             }
 6348:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6349:         }
 6350:         $datatable .= '</select>&nbsp;'."\n".
 6351:                       '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 6352:                       '<td colspan="2">'.
 6353:                       '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6354:                       '<span class="LC_nobreak">'.$lt{'consumer'}.
 6355:                       ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 6356:                       ('&nbsp;'x2).
 6357:                       '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 6358:                       '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 6359:                       ('&nbsp;'x2).
 6360:                       '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span><br /><br />'."\n";
 6361:         if ($switchserver) {
 6362:             $datatable .= '<span class="LC_nobreak">'.&mt('Key and Secret are required').' - '.$switchmessage.'</span>'."\n";
 6363:         } else {
 6364:             $datatable .= '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" autocomplete="off" /></span> '."\n".
 6365:                           ('&nbsp;'x2).
 6366:                           '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" autocomplete="new-password" />'.
 6367:                           '<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";
 6368:         }
 6369:         $datatable .= '<br /><br />'.
 6370:                       '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6371:                       '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6372:                       '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 6373:                       '<br /><br />'.
 6374:                       '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6375:                       '<label><input type="radio" name="lti_crsinc_add" value="1" onclick="toggleLTI(this.form,'."'crsinc','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6376:                       '<label><input type="radio" name="lti_crsinc_add" value="0" onclick="toggleLTI(this.form,'."'crsinc','add'".');" />'.&mt('No').'</label></span>'."\n".
 6377:                       '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 6378:                       '</td>'."\n".
 6379:                       '</tr>'."\n";
 6380:         $itemcount ++;
 6381:     }
 6382:     $$rowtotal += $itemcount;
 6383:     return $datatable;
 6384: }
 6385: 
 6386: sub lti_names {
 6387:     my %lt = &Apache::lonlocal::texthash(
 6388:                                           'version'   => 'LTI Version',
 6389:                                           'url'       => 'URL',
 6390:                                           'key'       => 'Key',
 6391:                                           'lifetime'  => 'Nonce lifetime (s)',
 6392:                                           'consumer'  => 'Consumer',
 6393:                                           'secret'    => 'Secret',
 6394:                                           'requser'   => "User's identity sent",
 6395:                                           'crsinc'    => "Course's identity sent",
 6396:                                           'email'     => 'Email address',
 6397:                                           'sourcedid' => 'User ID',
 6398:                                           'other'     => 'Other',
 6399:                                           'passback'  => 'Can return grades to Consumer:',
 6400:                                           'roster'    => 'Can retrieve roster from Consumer:',
 6401:                                           'topmenu'   => 'Display LON-CAPA page header',
 6402:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 6403:                                         );
 6404:     return %lt;
 6405: }
 6406: 
 6407: sub lti_options {
 6408:     my ($num,$current,$itemcount,%lt) = @_;
 6409:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 6410:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 6411:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 6412:     $checked{'storecrs'}{'Y'} = ' checked="checked"';
 6413:     $checked{'makecrs'}{'N'} = ' checked="checked"';
 6414:     $checked{'mapcrstype'} = {};
 6415:     $checked{'makeuser'} = {};
 6416:     $checked{'selfenroll'} = {};
 6417:     $checked{'crssec'} = {};
 6418:     $checked{'crssecsrc'} = {};
 6419:     $checked{'lcauth'} = {};
 6420:     $checked{'menuitem'} = {};
 6421:     if ($num eq 'add') {
 6422:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 6423:     }
 6424:     my $userfieldsty = 'none';
 6425:     my $crsfieldsty = 'none';
 6426:     my $crssecfieldsty = 'none';
 6427:     my $secsrcfieldsty = 'none';
 6428:     my $callbacksty = 'none';
 6429:     my $passbacksty = 'none';
 6430:     my $optionsty = 'block';
 6431:     my $crssty = 'block';
 6432:     my $lcauthparm;
 6433:     my $lcauthparmstyle = 'display:none';
 6434:     my $lcauthparmtext;
 6435:     my $menusty;
 6436:     my $numinrow = 4;
 6437:     my %menutitles = &ltimenu_titles();
 6438: 
 6439:     if (ref($current) eq 'HASH') {
 6440:         if (!$current->{'requser'}) {
 6441:             $optionsty = 'none';
 6442:             $crssty = 'none';
 6443:         } elsif (!$current->{'crsinc'}) {
 6444:             $crssty = 'none';
 6445:         }
 6446:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 6447:             $checked{'mapuser'}{'sourcedid'} = '';
 6448:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 6449:                 $checked{'mapuser'}{'email'} = ' checked="checked"';
 6450:             } else {
 6451:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 6452:                 $userfield = $current->{'mapuser'};
 6453:                 $userfieldsty = 'inline-block';
 6454:             }
 6455:         }
 6456:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 6457:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 6458:             if ($current->{'mapcrs'} eq 'context_id') {
 6459:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"';
 6460:             } else {
 6461:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 6462:                 $cidfield = $current->{'mapcrs'};
 6463:                 $crsfieldsty = 'inline-block';
 6464:             }
 6465:         }
 6466:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 6467:             foreach my $type (@{$current->{'mapcrstype'}}) {
 6468:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 6469:             }
 6470:         }
 6471:         if (!$current->{'storecrs'}) {
 6472:             $checked{'storecrs'}{'N'} = $checked{'storecrs'}{'Y'};
 6473:             $checked{'storecrs'}{'Y'} = '';
 6474:         }
 6475:         if ($current->{'makecrs'}) {
 6476:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 6477:         }
 6478:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 6479:             foreach my $role (@{$current->{'makeuser'}}) {
 6480:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 6481:             }
 6482:         }
 6483:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 6484:             $checked{'lcauth'}{$1} = ' checked="checked"';
 6485:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 6486:                 $lcauthparm = $current->{'lcauthparm'};
 6487:                 $lcauthparmstyle = 'display:table-row';
 6488:                 if ($current->{'lcauth'} eq 'localauth') {
 6489:                     $lcauthparmtext = &mt('Local auth argument');
 6490:                 } else {
 6491:                     $lcauthparmtext = &mt('Kerberos domain');
 6492:                 }
 6493:             }
 6494:         }
 6495:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 6496:             foreach my $role (@{$current->{'selfenroll'}}) {
 6497:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 6498:             }
 6499:         }
 6500:         if (ref($current->{'maproles'}) eq 'HASH') {
 6501:             %rolemaps = %{$current->{'maproles'}};
 6502:         }
 6503:         if ($current->{'section'} ne '') {
 6504:             $checked{'crssec'}{'Y'} = '  checked="checked"';
 6505:             $crssecfieldsty = 'inline-block';
 6506:             if ($current->{'section'} eq 'course_section_sourcedid') {
 6507:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 6508:             } else {
 6509:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 6510:                 $crssecsrc = $current->{'section'};
 6511:                 $secsrcfieldsty = 'inline-block';
 6512:             }
 6513:         } else {
 6514:             $checked{'crssec'}{'N'} = ' checked="checked"';
 6515:         }
 6516:         if ($current->{'callback'} ne '') {
 6517:             $callback = $current->{'callback'};
 6518:             $checked{'callback'}{'Y'} = ' checked="checked"';
 6519:             $callbacksty = 'inline-block';
 6520:         } else {
 6521:             $checked{'callback'}{'N'} = ' checked="checked"';
 6522:         }
 6523:         if ($current->{'topmenu'}) {
 6524:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 6525:         } else {
 6526:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 6527:         }
 6528:         if ($current->{'inlinemenu'}) {
 6529:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 6530:         } else {
 6531:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 6532:         }
 6533:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 6534:             $menusty = 'inline-block';
 6535:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 6536:                 foreach my $item (@{$current->{'lcmenu'}}) {
 6537:                     if (exists($menutitles{$item})) {
 6538:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 6539:                     }
 6540:                 }
 6541:             }
 6542:         } else {
 6543:             $menusty = 'none';
 6544:         }
 6545:     } else {
 6546:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 6547:         $checked{'crssec'}{'N'} = ' checked="checked"';
 6548:         $checked{'callback'}{'N'} = ' checked="checked"';
 6549:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 6550:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 6551:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 6552:         $menusty = 'inline-block';
 6553:     }
 6554:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 6555:     my %coursetypetitles = &Apache::lonlocal::texthash (
 6556:                                official   => 'Official',
 6557:                                unofficial => 'Unofficial',
 6558:                                community  => 'Community',
 6559:                                textbook   => 'Textbook',
 6560:                                placement  => 'Placement Test',
 6561:                                lti        => 'LTI Provider',
 6562:     );
 6563:     my @authtypes = ('internal','krb4','krb5','localauth');
 6564:     my %shortauth = (
 6565:                      internal => 'int',
 6566:                      krb4 => 'krb4',
 6567:                      krb5 => 'krb5',
 6568:                      localauth  => 'loc'
 6569:                     );
 6570:     my %authnames = &authtype_names();
 6571:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 6572:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 6573:     my @courseroles = ('cc','in','ta','ep','st');
 6574:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 6575:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 6576:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 6577:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 6578:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 6579:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 6580:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 6581:     my $output = '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Logout options').'</legend>'.
 6582:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback to logout LON-CAPA on log out from Consumer').':&nbsp;'.
 6583:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 6584:                  $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6585:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 6586:                  $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 6587:                  '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 6588:                  '<span class="LC_nobreak">'.&mt('Parameter').': '.
 6589:                  '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 6590:                  '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 6591:                  '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 6592:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 6593:     foreach my $option ('sourcedid','email','other') {
 6594:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 6595:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 6596:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6597:     }
 6598:     $output .= '</span></div>'.
 6599:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 6600:                '<input type="text" name="lti_customuser_'.$num.'" '.
 6601:                'value="'.$userfield.'" /></div></fieldset>'.
 6602:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 6603:     foreach my $ltirole (@ltiroles) {
 6604:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 6605:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';
 6606:     }
 6607:     $output .= '</fieldset>'.
 6608:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 6609:                '<table>'.
 6610:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 6611:                '</table>'.
 6612:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 6613:                '<td class="LC_left_item">';
 6614:     foreach my $auth ('lti',@authtypes) {
 6615:         my $authtext;
 6616:         if ($auth eq 'lti') {
 6617:             $authtext = &mt('None');
 6618:         } else {
 6619:             $authtext = $authnames{$shortauth{$auth}};
 6620:         }
 6621:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 6622:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 6623:                    $authtext.'</label></span> &nbsp;';
 6624:     }
 6625:     $output .= '</td></tr>'.
 6626:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 6627:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 6628:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 6629:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 6630:                '</table></fieldset>'.
 6631:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.
 6632:                &mt('LON-CAPA menu items (Course Coordinator can override)').'</legend>'.
 6633:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 6634:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 6635:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6636:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 6637:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 6638:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6639:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 6640:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 6641:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6642:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 6643:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 6644:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6645:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 6646:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 6647:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 6648:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 6649:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 6650:                    ('&nbsp;'x2);
 6651:     }
 6652:     $output .= '</span></div></fieldset>'.
 6653:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 6654:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 6655:                &mt('Unique course identifier').':&nbsp;';
 6656:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 6657:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 6658:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 6659:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6660:     }
 6661:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 6662:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 6663:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6664:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 6665:     foreach my $type (@coursetypes) {
 6666:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 6667:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 6668:                    ('&nbsp;'x2);
 6669:     }
 6670:     $output .= '</span><br /><br />'.
 6671:                '<span class="LC_nobreak">'.&mt('Store mapping of course identifier to LON-CAPA CourseID').':&nbsp;'.
 6672:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="0"'.
 6673:                $checked{'storecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6674:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="1"'.
 6675:                $checked{'storecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 6676:                '</fieldset>'.
 6677:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 6678:     foreach my $ltirole (@lticourseroles) {
 6679:         my ($selected,$selectnone);
 6680:         if ($rolemaps{$ltirole} eq '') {
 6681:             $selectnone = ' selected="selected"';
 6682:         }
 6683:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 6684:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 6685:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 6686:         foreach my $role (@courseroles) {
 6687:             unless ($selectnone) {
 6688:                 if ($rolemaps{$ltirole} eq $role) {
 6689:                     $selected = ' selected="selected"';
 6690:                 } else {
 6691:                     $selected = '';
 6692:                 }
 6693:             }
 6694:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 6695:                        &Apache::lonnet::plaintext($role,'Course').
 6696:                        '</option>';
 6697:         }
 6698:         $output .= '</select></td>';
 6699:     }
 6700:     $output .= '</tr></table></fieldset>'.
 6701:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Creating courses').'</legend>'.
 6702:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 6703:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 6704:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6705:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 6706:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 6707:                '</fieldset>'.
 6708:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 6709:     foreach my $lticrsrole (@lticourseroles) {
 6710:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 6711:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 6712:     }
 6713:     $output .= '</fieldset>'.
 6714:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Course options').'</legend>'.
 6715:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 6716:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 6717:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6718:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 6719:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 6720:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 6721:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 6722:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 6723:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 6724:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 6725:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 6726:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 6727:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 6728:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 6729:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 6730:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 6731:     foreach my $extra ('roster','passback') {
 6732:         my $checkedon = '';
 6733:         my $checkedoff = ' checked="checked"';
 6734:         if ($extra eq 'passback') {
 6735:             $pb1p1chk = ' checked="checked"';
 6736:             $pb1p0chk = '';
 6737:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"';
 6738:         } else {
 6739:             $onclickpb = '';
 6740:         }
 6741:         if (ref($current) eq 'HASH') {
 6742:             if (($current->{$extra})) {
 6743:                 $checkedon = $checkedoff;
 6744:                 $checkedoff = '';
 6745:                 if ($extra eq 'passback') {
 6746:                     $passbacksty = 'inline-block';
 6747:                 }
 6748:                 if ($current->{'passbackformat'} eq '1.0') {
 6749:                     $pb1p0chk =  ' checked="checked"';
 6750:                     $pb1p1chk = '';
 6751:                 }
 6752:             }
 6753:         }
 6754:         $output .= $lt{$extra}.'&nbsp;'.
 6755:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 6756:                    &mt('No').'</label>'.('&nbsp;'x2).
 6757:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 6758:                    &mt('Yes').'</label><br />';
 6759:     }
 6760:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 6761:                '<span class="LC_nobreak">'.&mt('Grade format').
 6762:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 6763:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 6764:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 6765:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 6766:                '<div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>';
 6767:     $output .= '</span></div></fieldset>';
 6768: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 6769: #
 6770: #    $output .= '</fieldset>'.
 6771: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 6772:     return $output;
 6773: }
 6774: 
 6775: sub ltimenu_titles {
 6776:     return &Apache::lonlocal::texthash(
 6777:                                         fullname    => 'Full name',
 6778:                                         coursetitle => 'Course title',
 6779:                                         role        => 'Role',
 6780:                                         logout      => 'Logout',
 6781:                                         grades      => 'Grades',
 6782:     );
 6783: }
 6784: 
 6785: sub check_switchserver {
 6786:     my ($home) = @_;
 6787:     my $switchserver;
 6788:     if ($home ne '') {
 6789:         my $allowed;
 6790:         my @ids=&Apache::lonnet::current_machine_ids();
 6791:         foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 6792:         if (!$allowed) {
 6793:             $switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role='.
 6794:                           &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 6795:                           '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 6796:         }
 6797:     }
 6798:     return $switchserver;
 6799: }
 6800: 
 6801: sub print_coursedefaults {
 6802:     my ($position,$dom,$settings,$rowtotal) = @_;
 6803:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 6804:     my $itemcount = 1;
 6805:     my %choices =  &Apache::lonlocal::texthash (
 6806:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 6807:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 6808:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 6809:         coursecredits        => 'Credits can be specified for courses',
 6810:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 6811:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 6812:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 6813:         texengine            => 'Default method to display mathematics',
 6814:         postsubmit           => 'Disable submit button/keypress following student submission',
 6815:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 6816:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 6817:         ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
 6818:         domexttool           => 'External Tools defined in the domain may be used in courses/communities (by type)',
 6819:         exttool              => 'External Tools can be defined and configured in courses/communities (by type)',
 6820:     );
 6821:     my %staticdefaults = (
 6822:                            anonsurvey_threshold => 10,
 6823:                            uploadquota          => 500,
 6824:                            postsubmit           => 60,
 6825:                            mysqltables          => 172800,
 6826:                            domexttool           => 1,
 6827:                            exttool              => 0,
 6828:                          );
 6829:     if ($position eq 'top') {
 6830:         %defaultchecked = (
 6831:                             'canuse_pdfforms' => 'off',
 6832:                             'uselcmath'       => 'on',
 6833:                             'usejsme'         => 'on',
 6834:                             'inline_chem'     => 'on',
 6835:                             'canclone'        => 'none',
 6836:                           );
 6837:         @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem');
 6838:         my $deftex = $Apache::lonnet::deftex;
 6839:         if (ref($settings) eq 'HASH') {
 6840:             if ($settings->{'texengine'}) {
 6841:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 6842:                     $deftex = $settings->{'texengine'};
 6843:                 }
 6844:             }
 6845:         }
 6846:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6847:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 6848:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 6849:                        '</span></td><td class="LC_right_item">'.
 6850:                        '<select name="texengine">'."\n";
 6851:         my %texoptions = (
 6852:                             MathJax  => 'MathJax',
 6853:                             mimetex  => &mt('Convert to Images'),
 6854:                             tth      => &mt('TeX to HTML'),
 6855:                          );
 6856:         foreach my $renderer ('MathJax','mimetex','tth') {
 6857:             my $selected = '';
 6858:             if ($renderer eq $deftex) {
 6859:                 $selected = ' selected="selected"';
 6860:             }
 6861:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 6862:         }
 6863:         $mathdisp .= '</select></td></tr>'."\n";
 6864:         $itemcount ++;
 6865:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 6866:                                                      \%choices,$itemcount);
 6867:         $datatable = $mathdisp.$datatable;
 6868:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6869:         $datatable .=
 6870:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 6871:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 6872:             '</span></td><td class="LC_left_item">';
 6873:         my $currcanclone = 'none';
 6874:         my $onclick;
 6875:         my @cloneoptions = ('none','domain');
 6876:         my %clonetitles = &Apache::lonlocal::texthash (
 6877:                              none     => 'No additional course requesters',
 6878:                              domain   => "Any course requester in course's domain",
 6879:                              instcode => 'Course requests for official courses ...',
 6880:                           );
 6881:         my (%codedefaults,@code_order,@posscodes);
 6882:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 6883:                                                     \@code_order) eq 'ok') {
 6884:             if (@code_order > 0) {
 6885:                 push(@cloneoptions,'instcode');
 6886:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 6887:             }
 6888:         }
 6889:         if (ref($settings) eq 'HASH') {
 6890:             if ($settings->{'canclone'}) {
 6891:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 6892:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 6893:                         if (@code_order > 0) {
 6894:                             $currcanclone = 'instcode';
 6895:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 6896:                         }
 6897:                     }
 6898:                 } elsif ($settings->{'canclone'} eq 'domain') {
 6899:                     $currcanclone = $settings->{'canclone'};
 6900:                 }
 6901:             }
 6902:         }
 6903:         foreach my $option (@cloneoptions) {
 6904:             my ($checked,$additional);
 6905:             if ($currcanclone eq $option) {
 6906:                 $checked = ' checked="checked"';
 6907:             }
 6908:             if ($option eq 'instcode') {
 6909:                 if (@code_order) {
 6910:                     my $show = 'none';
 6911:                     if ($checked) {
 6912:                         $show = 'block';
 6913:                     }
 6914:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 6915:                                   &mt('Institutional codes for new and cloned course have identical:').
 6916:                                   '<br />';
 6917:                     foreach my $item (@code_order) {
 6918:                         my $codechk;
 6919:                         if ($checked) {
 6920:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 6921:                                 $codechk = ' checked="checked"';
 6922:                             }
 6923:                         }
 6924:                         $additional .= '<label>'.
 6925:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 6926:                                        $item.'</label>';
 6927:                     }
 6928:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 6929:                 }
 6930:             }
 6931:             $datatable .=
 6932:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 6933:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 6934:                 '</label>&nbsp;'.$additional.'</span><br />';
 6935:         }
 6936:         $datatable .= '</td>'.
 6937:                       '</tr>';
 6938:         $itemcount ++;
 6939:     } else {
 6940:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6941:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 6942:         my $currusecredits = 0;
 6943:         my $postsubmitclient = 1;
 6944:         my $ltiauth = 0;
 6945:         my %domexttool;
 6946:         my %exttool;
 6947:         my @types = ('official','unofficial','community','textbook','placement');
 6948:         if (ref($settings) eq 'HASH') {
 6949:             if ($settings->{'ltiauth'}) {
 6950:                 $ltiauth = 1;
 6951:             }
 6952:             if (ref($settings->{'domexttool'}) eq 'HASH') {
 6953:                 foreach my $type (@types) {
 6954:                     if ($settings->{'domexttool'}->{$type}) {
 6955:                         $domexttool{$type} = ' checked="checked"';
 6956:                     }
 6957:                 }
 6958:             } else {
 6959:                 foreach my $type (@types) {
 6960:                     if ($staticdefaults{'domexttool'}) {
 6961:                         $domexttool{$type} = ' checked="checked"';
 6962:                     }
 6963:                 }
 6964:             }
 6965:             if (ref($settings->{'exttool'}) eq 'HASH') {
 6966:                 foreach my $type (@types) {
 6967:                     if ($settings->{'exttool'}->{$type}) {
 6968:                         $exttool{$type} = ' checked="checked"';
 6969:                     }
 6970:                 }
 6971:             }
 6972:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 6973:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 6974:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 6975:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 6976:                 }
 6977:             }
 6978:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 6979:                 foreach my $type (@types) {
 6980:                     next if ($type eq 'community');
 6981:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 6982:                     if ($defcredits{$type} ne '') {
 6983:                         $currusecredits = 1;
 6984:                     }
 6985:                 }
 6986:             }
 6987:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 6988:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 6989:                     $postsubmitclient = 0;
 6990:                     foreach my $type (@types) {
 6991:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6992:                     }
 6993:                 } else {
 6994:                     foreach my $type (@types) {
 6995:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 6996:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 6997:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 6998:                             } else {
 6999:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7000:                             }
 7001:                         } else {
 7002:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7003:                         }
 7004:                     }
 7005:                 }
 7006:             } else {
 7007:                 foreach my $type (@types) {
 7008:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7009:                 }
 7010:             }
 7011:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 7012:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 7013:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 7014:                 }
 7015:             } else {
 7016:                 foreach my $type (@types) {
 7017:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 7018:                 }
 7019:             }
 7020:         } else {
 7021:             foreach my $type (@types) {
 7022:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7023:                 if ($staticdefaults{'domexttool'}) {
 7024:                     $domexttool{$type} = ' checked="checked"';
 7025:                 }
 7026:             }
 7027:         }
 7028:         if (!$currdefresponder) {
 7029:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 7030:         } elsif ($currdefresponder < 1) {
 7031:             $currdefresponder = 1;
 7032:         }
 7033:         foreach my $type (@types) {
 7034:             if ($curruploadquota{$type} eq '') {
 7035:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 7036:             }
 7037:         }
 7038:         $datatable .=
 7039:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7040:                 $choices{'anonsurvey_threshold'}.
 7041:                 '</span></td>'.
 7042:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 7043:                 '<input type="text" name="anonsurvey_threshold"'.
 7044:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 7045:                 '</td></tr>'."\n";
 7046:         $itemcount ++;
 7047:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7048:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7049:                       $choices{'uploadquota'}.
 7050:                       '</span></td>'.
 7051:                       '<td style="text-align: right" class="LC_right_item">'.
 7052:                       '<table><tr>';
 7053:         foreach my $type (@types) {
 7054:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7055:                            '<input type="text" name="uploadquota_'.$type.'"'.
 7056:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 7057:         }
 7058:         $datatable .= '</tr></table></td></tr>'."\n";
 7059:         $itemcount ++;
 7060:         my $onclick = "toggleDisplay(this.form,'credits');";
 7061:         my $display = 'none';
 7062:         if ($currusecredits) {
 7063:             $display = 'block';
 7064:         }
 7065:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 7066:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 7067:         foreach my $type (@types) {
 7068:             next if ($type eq 'community');
 7069:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7070:                            '<input type="text" name="'.$type.'_credits"'.
 7071:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 7072:         }
 7073:         $additional .= '</tr></table></div>'."\n";
 7074:         %defaultchecked = ('coursecredits' => 'off');
 7075:         @toggles = ('coursecredits');
 7076:         my $current = {
 7077:                         'coursecredits' => $currusecredits,
 7078:                       };
 7079:         (my $table,$itemcount) =
 7080:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7081:                                \%choices,$itemcount,$onclick,$additional,'left');
 7082:         $datatable .= $table;
 7083:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 7084:         my $display = 'none';
 7085:         if ($postsubmitclient) {
 7086:             $display = 'block';
 7087:         }
 7088:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 7089:                       &mt('Number of seconds submit is disabled').'<br />'.
 7090:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 7091:                       '<table><tr>';
 7092:         foreach my $type (@types) {
 7093:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7094:                            '<input type="text" name="'.$type.'_timeout" value="'.
 7095:                            $deftimeout{$type}.'" size="5" /></td>';
 7096:         }
 7097:         $additional .= '</tr></table></div>'."\n";
 7098:         %defaultchecked = ('postsubmit' => 'on');
 7099:         @toggles = ('postsubmit');
 7100:         $current = {
 7101:                        'postsubmit' => $postsubmitclient,
 7102:                    };
 7103:         ($table,$itemcount) =
 7104:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7105:                                \%choices,$itemcount,$onclick,$additional,'left');
 7106:         $datatable .= $table;
 7107:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7108:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7109:                       $choices{'mysqltables'}.
 7110:                       '</span></td>'.
 7111:                       '<td style="text-align: right" class="LC_right_item">'.
 7112:                       '<table><tr>';
 7113:         foreach my $type (@types) {
 7114:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7115:                            '<input type="text" name="mysqltables_'.$type.'"'.
 7116:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 7117:         }
 7118:         $datatable .= '</tr></table></td></tr>'."\n";
 7119:         $itemcount ++;
 7120:         %defaultchecked = ('ltiauth' => 'off');
 7121:         @toggles = ('ltiauth');
 7122:         $current = {
 7123:                        'ltiauth' => $ltiauth,
 7124:                    };
 7125:         ($table,$itemcount) =
 7126:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7127:                                \%choices,$itemcount,undef,undef,'left');
 7128:         $datatable .= $table;
 7129:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7130:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7131:                       $choices{'domexttool'}.
 7132:                       '</span></td>'.
 7133:                       '<td style="text-align: right" class="LC_right_item">'.
 7134:                       '<table><tr>';
 7135:         foreach my $type (@types) {
 7136:             $datatable .= '<td style="text-align: left">'.
 7137:                           '<span class="LC_nobreak">'.
 7138:                           '<input type="checkbox" name="domexttool"'.
 7139:                           ' value="'.$type.'"'.$domexttool{$type}.' />'.
 7140:                           &mt($type).'</span></td>'."\n";
 7141:         }
 7142:         $datatable .= '</tr></table></td></tr>'."\n";
 7143:         $itemcount ++;
 7144:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7145:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7146:                       $choices{'exttool'}.
 7147:                       '</span></td>'.
 7148:                       '<td style="text-align: right" class="LC_right_item">'.
 7149:                       '<table><tr>';
 7150:         foreach my $type (@types) {
 7151:             $datatable .= '<td style="text-align: left">'.
 7152:                           '<span class="LC_nobreak">'.
 7153:                           '<input type="checkbox" name="exttool"'.
 7154:                           ' value="'.$type.'"'.$exttool{$type}.' />'.
 7155:                           &mt($type).'</span></td>'."\n";
 7156:         }
 7157:         $datatable .= '</tr></table></td></tr>'."\n";
 7158:     }
 7159:     $$rowtotal += $itemcount;
 7160:     return $datatable;
 7161: }
 7162: 
 7163: sub print_selfenrollment {
 7164:     my ($position,$dom,$settings,$rowtotal) = @_;
 7165:     my ($css_class,$datatable);
 7166:     my $itemcount = 1;
 7167:     my @types = ('official','unofficial','community','textbook','placement');
 7168:     if (($position eq 'top') || ($position eq 'middle')) {
 7169:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 7170:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 7171:         my @rows;
 7172:         my $key;
 7173:         if ($position eq 'top') {
 7174:             $key = 'admin'; 
 7175:             if (ref($rowsref) eq 'ARRAY') {
 7176:                 @rows = @{$rowsref};
 7177:             }
 7178:         } elsif ($position eq 'middle') {
 7179:             $key = 'default';
 7180:             @rows = ('types','registered','approval','limit');
 7181:         }
 7182:         foreach my $row (@rows) {
 7183:             if (defined($titlesref->{$row})) {
 7184:                 $itemcount ++;
 7185:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7186:                 $datatable .= '<tr'.$css_class.'>'.
 7187:                               '<td>'.$titlesref->{$row}.'</td>'.
 7188:                               '<td class="LC_left_item">'.
 7189:                               '<table><tr>';
 7190:                 my (%current,%currentcap);
 7191:                 if (ref($settings) eq 'HASH') {
 7192:                     if (ref($settings->{$key}) eq 'HASH') {
 7193:                         foreach my $type (@types) {
 7194:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7195:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 7196:                             }
 7197:                             if (($row eq 'limit') && ($key eq 'default')) {
 7198:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7199:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 7200:                                 }
 7201:                             }
 7202:                         }
 7203:                     }
 7204:                 }
 7205:                 my %roles = (
 7206:                              '0' => &Apache::lonnet::plaintext('dc'),
 7207:                             ); 
 7208:             
 7209:                 foreach my $type (@types) {
 7210:                     unless (($row eq 'registered') && ($key eq 'default')) {
 7211:                         $datatable .= '<th>'.&mt($type).'</th>';
 7212:                     }
 7213:                 }
 7214:                 unless (($row eq 'registered') && ($key eq 'default')) {
 7215:                     $datatable .= '</tr><tr>';
 7216:                 }
 7217:                 foreach my $type (@types) {
 7218:                     if ($type eq 'community') {
 7219:                         $roles{'1'} = &mt('Community personnel');
 7220:                     } else {
 7221:                         $roles{'1'} = &mt('Course personnel');
 7222:                     }
 7223:                     $datatable .= '<td style="vertical-align: top">';
 7224:                     if ($position eq 'top') {
 7225:                         my %checked;
 7226:                         if ($current{$type} eq '0') {
 7227:                             $checked{'0'} = ' checked="checked"';
 7228:                         } else {
 7229:                             $checked{'1'} = ' checked="checked"';
 7230:                         }
 7231:                         foreach my $role ('1','0') {
 7232:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7233:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 7234:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 7235:                                           $roles{$role}.'</label></span> ';
 7236:                         }
 7237:                     } else {
 7238:                         if ($row eq 'types') {
 7239:                             my %checked;
 7240:                             if ($current{$type} =~ /^(all|dom)$/) {
 7241:                                 $checked{$1} = ' checked="checked"';
 7242:                             } else {
 7243:                                 $checked{''} = ' checked="checked"';
 7244:                             }
 7245:                             foreach my $val ('','dom','all') {
 7246:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7247:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7248:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7249:                             }
 7250:                         } elsif ($row eq 'registered') {
 7251:                             my %checked;
 7252:                             if ($current{$type} eq '1') {
 7253:                                 $checked{'1'} = ' checked="checked"';
 7254:                             } else {
 7255:                                 $checked{'0'} = ' checked="checked"';
 7256:                             }
 7257:                             foreach my $val ('0','1') {
 7258:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7259:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7260:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7261:                             }
 7262:                         } elsif ($row eq 'approval') {
 7263:                             my %checked;
 7264:                             if ($current{$type} =~ /^([12])$/) {
 7265:                                 $checked{$1} = ' checked="checked"';
 7266:                             } else {
 7267:                                 $checked{'0'} = ' checked="checked"';
 7268:                             }
 7269:                             for my $val (0..2) {
 7270:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7271:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7272:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7273:                             }
 7274:                         } elsif ($row eq 'limit') {
 7275:                             my %checked;
 7276:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 7277:                                 $checked{$1} = ' checked="checked"';
 7278:                             } else {
 7279:                                 $checked{'none'} = ' checked="checked"';
 7280:                             }
 7281:                             my $cap;
 7282:                             if ($currentcap{$type} =~ /^\d+$/) {
 7283:                                 $cap = $currentcap{$type};
 7284:                             }
 7285:                             foreach my $val ('none','allstudents','selfenrolled') {
 7286:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7287:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7288:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7289:                             }
 7290:                             $datatable .= '<br />'.
 7291:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 7292:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 7293:                                           '</span>'; 
 7294:                         }
 7295:                     }
 7296:                     $datatable .= '</td>';
 7297:                 }
 7298:                 $datatable .= '</tr>';
 7299:             }
 7300:             $datatable .= '</table></td></tr>';
 7301:         }
 7302:     } elsif ($position eq 'bottom') {
 7303:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 7304:     }
 7305:     $$rowtotal += $itemcount;
 7306:     return $datatable;
 7307: }
 7308: 
 7309: sub print_validation_rows {
 7310:     my ($caller,$dom,$settings,$rowtotal) = @_;
 7311:     my ($itemsref,$namesref,$fieldsref);
 7312:     if ($caller eq 'selfenroll') { 
 7313:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 7314:     } elsif ($caller eq 'requestcourses') {
 7315:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 7316:     }
 7317:     my %currvalidation;
 7318:     if (ref($settings) eq 'HASH') {
 7319:         if (ref($settings->{'validation'}) eq 'HASH') {
 7320:             %currvalidation = %{$settings->{'validation'}};
 7321:         }
 7322:     }
 7323:     my $datatable;
 7324:     my $itemcount = 0;
 7325:     foreach my $item (@{$itemsref}) {
 7326:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7327:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7328:                       $namesref->{$item}.
 7329:                       '</span></td>'.
 7330:                       '<td class="LC_left_item">';
 7331:         if (($item eq 'url') || ($item eq 'button')) {
 7332:             $datatable .= '<span class="LC_nobreak">'.
 7333:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 7334:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 7335:         } elsif ($item eq 'fields') {
 7336:             my @currfields;
 7337:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 7338:                 @currfields = @{$currvalidation{$item}};
 7339:             }
 7340:             foreach my $field (@{$fieldsref}) {
 7341:                 my $check = '';
 7342:                 if (grep(/^\Q$field\E$/,@currfields)) {
 7343:                     $check = ' checked="checked"';
 7344:                 }
 7345:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7346:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 7347:                               ' value="'.$field.'"'.$check.' />'.$field.
 7348:                               '</label></span> ';
 7349:             }
 7350:         } elsif ($item eq 'markup') {
 7351:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 7352:                            $currvalidation{$item}.
 7353:                               '</textarea>';
 7354:         }
 7355:         $datatable .= '</td></tr>'."\n";
 7356:         if (ref($rowtotal)) {
 7357:             $itemcount ++;
 7358:         }
 7359:     }
 7360:     if ($caller eq 'requestcourses') {
 7361:         my %currhash;
 7362:         if (ref($settings) eq 'HASH') {
 7363:             if (ref($settings->{'validation'}) eq 'HASH') {
 7364:                 if ($settings->{'validation'}{'dc'} ne '') {
 7365:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 7366:                 }
 7367:             }
 7368:         }
 7369:         my $numinrow = 2;
 7370:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 7371:                                                        'validationdc',%currhash);
 7372:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7373:         $datatable .= '<tr'.$css_class.'><td>';
 7374:         if ($numdc > 1) {
 7375:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 7376:         } else {
 7377:             $datatable .=  &mt('Course creation processed as: ');
 7378:         }
 7379:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 7380:         $itemcount ++;
 7381:     }
 7382:     if (ref($rowtotal)) {
 7383:         $$rowtotal += $itemcount;
 7384:     }
 7385:     return $datatable;
 7386: }
 7387: 
 7388: sub print_privacy {
 7389:     my ($position,$dom,$settings,$rowtotal) = @_;
 7390:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 7391:     my $itemcount = 0;
 7392:     if ($position eq 'top') {
 7393:         $numinrow = 2;
 7394:     } else {
 7395:         @items = ('domain','author','course','community');
 7396:         %names = &Apache::lonlocal::texthash (
 7397:                      domain => 'Assigned domain role(s)',
 7398:                      author => 'Assigned co-author role(s)',
 7399:                      course => 'Assigned course role(s)',
 7400:                      community => 'Assigned community role(s)',
 7401:                  );
 7402:         $numinrow = 4;
 7403:         ($othertitle,$usertypes,$types) =
 7404:             &Apache::loncommon::sorted_inst_types($dom);
 7405:     }
 7406:     if (($position eq 'top') || ($position eq 'middle')) {
 7407:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7408:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7409:         if ($position eq 'top') {
 7410:             my %curr;
 7411:             my @options = ('none','user','domain','auto');
 7412:             my %titles = &Apache::lonlocal::texthash (
 7413:                 none   => 'Not allowed',
 7414:                 user   => 'User authorizes',
 7415:                 domain => 'DC authorizes',
 7416:                 auto   => 'Unrestricted',
 7417:                 instdom => 'Other domain shares institution/provider',
 7418:                 extdom => 'Other domain has different institution/provider',
 7419:                 notify => 'Notify when role needs authorization',
 7420:             );
 7421:             my %names = &Apache::lonlocal::texthash (
 7422:                 domain => 'Domain role',
 7423:                 author => 'Co-author role',
 7424:                 course => 'Course role',
 7425:                 community => 'Community role',
 7426:             );
 7427:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7428:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7429:             foreach my $domtype ('instdom','extdom') {
 7430:                 my (%checked,$skip);
 7431:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7432:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 7433:                               '<td class="LC_left_item">';
 7434:                 if ($domtype eq 'instdom') {
 7435:                     unless (@instdoms > 1) {
 7436:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 7437:                         $skip = 1;
 7438:                     }
 7439:                 } elsif ($domtype eq 'extdom') {
 7440:                     if (keys(%by_location) == 0) {
 7441:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 7442:                         $skip = 1;
 7443:                     }
 7444:                 }
 7445:                 unless ($skip) {
 7446:                     foreach my $roletype ('domain','author','course','community') {
 7447:                         $checked{'auto'} = ' checked="checked"';
 7448:                         if (ref($settings) eq 'HASH') {
 7449:                             if (ref($settings->{approval}) eq 'HASH') {
 7450:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 7451:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 7452:                                         $checked{$1} = ' checked="checked"';
 7453:                                         $checked{'auto'} = '';
 7454:                                     }
 7455:                                 }
 7456:                             }
 7457:                         }
 7458:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 7459:                         foreach my $option (@options) {
 7460:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7461:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 7462:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7463:                                           '</label></span>&nbsp; ';
 7464:                         }
 7465:                         $datatable .= '</fieldset>';
 7466:                     }
 7467:                 }
 7468:                 $datatable .= '</td></tr>';
 7469:                 $itemcount ++;
 7470:             }
 7471:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7472:             $datatable .= '<tr'.$css_class.'><td>'.$titles{'notify'}.'</td>'.
 7473:                           '<td class="LC_left_item">';
 7474:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7475:                 my %curr;
 7476:                 if (ref($settings) eq 'HASH') {
 7477:                     if ($settings->{'notify'} ne '') {
 7478:                         map {$curr{$_}=1;} split(/,/,$settings->{'notify'});
 7479:                     }
 7480:                 }
 7481:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7482:                 my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 7483:                                                              'privacy_notify',%curr);
 7484:                 if ($numdc > 0) {
 7485:                     $datatable .= $table;
 7486:                 } else {
 7487:                     $datatable .= &mt('There are no active Domain Coordinators');
 7488:                 }
 7489:             } else {
 7490:                 $datatable .= &mt('Nothing to set here, as there are no other domains');
 7491:             }
 7492:             $datatable .='</td></tr>';
 7493:         } elsif ($position eq 'middle') {
 7494:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7495:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7496:                     foreach my $item (@{$types}) {
 7497:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 7498:                                                                $numinrow,$itemcount,'','','','','',
 7499:                                                                '',$usertypes->{$item});
 7500:                         $itemcount ++;
 7501:                     }
 7502:                 }
 7503:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 7504:                                                        $numinrow,$itemcount,'','','','','',
 7505:                                                        '',$othertitle);
 7506:                 $itemcount ++;
 7507:             } else {
 7508:                 my (@insttypes,%insttitles);
 7509:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7510:                     @insttypes = @{$types};
 7511:                     %insttitles = %{$usertypes};
 7512:                 }
 7513:                 foreach my $item (@insttypes,'default') {
 7514:                     my $title;
 7515:                     if ($item eq 'default') {
 7516:                         $title = $othertitle;
 7517:                     } else {
 7518:                         $title = $insttitles{$item};
 7519:                     }
 7520:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7521:                     $datatable .= '<tr'.$css_class.'>'.
 7522:                                   '<td class="LC_left_item">'.$title.'</td>'.
 7523:                                   '<td class="LC_left_item">'.
 7524:                                   &mt('Nothing to set here, as there are no other domains').
 7525:                                   '</td></tr>';
 7526:                     $itemcount ++;
 7527:                 }
 7528:             }
 7529:         }
 7530:     } else {
 7531:         my $prefix;
 7532:         if ($position eq 'lower') {
 7533:             $prefix = 'priv';
 7534:         } else {
 7535:             $prefix = 'unpriv';
 7536:         }
 7537:         foreach my $item (@items) {
 7538:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 7539:                                                    $numinrow,$itemcount,'','','','','',
 7540:                                                    '',$names{$item});
 7541:             $itemcount ++;
 7542:         }
 7543:     }
 7544:     if (ref($rowtotal)) {
 7545:         $$rowtotal += $itemcount;
 7546:     }
 7547:     return $datatable;
 7548: }
 7549: 
 7550: sub print_passwords {
 7551:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 7552:     my ($datatable,$css_class);
 7553:     my $itemcount = 0;
 7554:     my %titles = &Apache::lonlocal::texthash (
 7555:         captcha        => '"Forgot Password" CAPTCHA validation',
 7556:         link           => 'Reset link expiration (hours)',
 7557:         case           => 'Case-sensitive usernames/e-mail',
 7558:         prelink        => 'Information required (form 1)',
 7559:         postlink       => 'Information required (form 2)',
 7560:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 7561:         customtext     => 'Domain specific text (HTML)',
 7562:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 7563:         intauth_check  => 'Check bcrypt cost if authenticated',
 7564:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 7565:         permanent      => 'Permanent e-mail address',
 7566:         critical       => 'Critical notification address',
 7567:         notify         => 'Notification address',
 7568:         min            => 'Minimum password length',
 7569:         max            => 'Maximum password length',
 7570:         chars          => 'Required characters',
 7571:         expire         => 'Password expiration (days)',
 7572:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 7573:     );
 7574:     if ($position eq 'top') {
 7575:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7576:         my $shownlinklife = 2;
 7577:         my $prelink = 'both';
 7578:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 7579:         if (ref($settings) eq 'HASH') {
 7580:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 7581:                 $shownlinklife = $settings->{resetlink};
 7582:             }
 7583:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 7584:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 7585:             }
 7586:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 7587:                 $prelink = $settings->{resetprelink};
 7588:             }
 7589:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 7590:                 %postlink = %{$settings->{resetpostlink}};
 7591:             }
 7592:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 7593:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 7594:             }
 7595:             if ($settings->{resetremove}) {
 7596:                 $nostdtext = 1;
 7597:             }
 7598:             if ($settings->{resetcustom}) {
 7599:                 $customurl = $settings->{resetcustom};
 7600:             }
 7601:         } else {
 7602:             if (ref($types) eq 'ARRAY') {
 7603:                 foreach my $item (@{$types}) {
 7604:                     $casesens{$item} = 1;
 7605:                     $postlink{$item} = ['username','email'];
 7606:                 }
 7607:             }
 7608:             $casesens{'default'} = 1;
 7609:             $postlink{'default'} = ['username','email'];
 7610:             $prelink = 'both';
 7611:             %emailsrc = (
 7612:                           permanent => 1,
 7613:                           critical  => 1,
 7614:                           notify    => 1,
 7615:             );
 7616:         }
 7617:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 7618:         $itemcount ++;
 7619:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7620:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 7621:                       '<td class="LC_left_item">'.
 7622:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 7623:                       'name="passwords_link" size="3" /></td></tr>';
 7624:         $itemcount ++;
 7625:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7626:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 7627:                       '<td class="LC_left_item">';
 7628:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7629:             foreach my $item (@{$types}) {
 7630:                 my $checkedcase;
 7631:                 if ($casesens{$item}) {
 7632:                     $checkedcase = ' checked="checked"';
 7633:                 }
 7634:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7635:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 7636:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 7637:                               '</span>&nbsp;&nbsp; ';
 7638:             }
 7639:         }
 7640:         my $checkedcase;
 7641:         if ($casesens{'default'}) {
 7642:             $checkedcase = ' checked="checked"';
 7643:         }
 7644:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7645:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 7646:                       $othertitle.'</label></span></td>';
 7647:         $itemcount ++;
 7648:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7649:         my %checkedpre = (
 7650:                              both => ' checked="checked"',
 7651:                              either => '',
 7652:                          );
 7653:         if ($prelink eq 'either') {
 7654:             $checkedpre{either} = ' checked="checked"';
 7655:             $checkedpre{both} = '';
 7656:         }
 7657:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 7658:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7659:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 7660:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 7661:                       '<span class="LC_nobreak"><label>'.
 7662:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 7663:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 7664:         $itemcount ++;
 7665:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7666:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 7667:                       '<td class="LC_left_item">';
 7668:         my %postlinked;
 7669:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7670:             foreach my $item (@{$types}) {
 7671:                 undef(%postlinked);
 7672:                 $datatable .= '<fieldset style="display: inline-block;">'.
 7673:                               '<legend>'.$usertypes->{$item}.'</legend>';
 7674:                 if (ref($postlink{$item}) eq 'ARRAY') {
 7675:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 7676:                 }
 7677:                 foreach my $field ('email','username') {
 7678:                     my $checked;
 7679:                     if ($postlinked{$field}) {
 7680:                         $checked = ' checked="checked"';
 7681:                     }
 7682:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7683:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 7684:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 7685:                                   '<span>&nbsp;&nbsp; ';
 7686:                 }
 7687:                 $datatable .= '</fieldset>';
 7688:             }
 7689:         }
 7690:         if (ref($postlink{'default'}) eq 'ARRAY') {
 7691:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 7692:         }
 7693:         $datatable .= '<fieldset style="display: inline-block;">'.
 7694:                       '<legend>'.$othertitle.'</legend>';
 7695:         foreach my $field ('email','username') {
 7696:             my $checked;
 7697:             if ($postlinked{$field}) {
 7698:                 $checked = ' checked="checked"';
 7699:             }
 7700:             $datatable .= '<span class="LC_nobreak"><label>'.
 7701:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 7702:                           $field.'"'.$checked.' />'.$field.'</label>'.
 7703:                           '<span>&nbsp;&nbsp; ';
 7704:         }
 7705:         $datatable .= '</fieldset></td></tr>';
 7706:         $itemcount ++;
 7707:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7708:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 7709:                       '<td class="LC_left_item">';
 7710:         foreach my $type ('permanent','critical','notify') {
 7711:             my $checkedemail;
 7712:             if ($emailsrc{$type}) {
 7713:                 $checkedemail = ' checked="checked"';
 7714:             }
 7715:             $datatable .= '<span class="LC_nobreak"><label>'.
 7716:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 7717:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 7718:                           '<span>&nbsp;&nbsp; ';
 7719:         }
 7720:         $datatable .= '</td></tr>';
 7721:         $itemcount ++;
 7722:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7723:         my $switchserver = &check_switchserver($dom,$confname);
 7724:         my ($showstd,$noshowstd);
 7725:         if ($nostdtext) {
 7726:             $noshowstd = ' checked="checked"';
 7727:         } else {
 7728:             $showstd = ' checked="checked"';
 7729:         }
 7730:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 7731:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7732:                       &mt('Retain standard text:').
 7733:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 7734:                       &mt('Yes').'</label>'.'&nbsp;'.
 7735:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 7736:                       &mt('No').'</label></span><br />'.
 7737:                       '<span class="LC_fontsize_small">'.
 7738:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 7739:                       &mt('Include custom text:');
 7740:         if ($customurl) {
 7741:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 7742:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 7743:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 7744:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 7745:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 7746:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 7747:         }
 7748:         if ($switchserver) {
 7749:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 7750:         } else {
 7751:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 7752:                          '<input type="file" name="passwords_customfile" /></span>';
 7753:         }
 7754:         $datatable .= '</td></tr>';
 7755:     } elsif ($position eq 'middle') {
 7756:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 7757:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 7758:         my %defaults;
 7759:         if (ref($domconf{'defaults'}) eq 'HASH') {
 7760:             %defaults = %{$domconf{'defaults'}};
 7761:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 7762:                 $defaults{'intauth_cost'} = 10;
 7763:             }
 7764:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 7765:                 $defaults{'intauth_check'} = 0;
 7766:             }
 7767:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 7768:                 $defaults{'intauth_switch'} = 0;
 7769:             }
 7770:         } else {
 7771:             %defaults = (
 7772:                           'intauth_cost'   => 10,
 7773:                           'intauth_check'  => 0,
 7774:                           'intauth_switch' => 0,
 7775:                         );
 7776:         }
 7777:         foreach my $item (@items) {
 7778:             if ($itemcount%2) {
 7779:                 $css_class = '';
 7780:             } else {
 7781:                 $css_class = ' class="LC_odd_row" ';
 7782:             }
 7783:             $datatable .= '<tr'.$css_class.'>'.
 7784:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 7785:                           '</span></td><td class="LC_left_item" colspan="3">';
 7786:             if ($item eq 'intauth_switch') {
 7787:                 my @options = (0,1,2);
 7788:                 my %optiondesc = &Apache::lonlocal::texthash (
 7789:                                    0 => 'No',
 7790:                                    1 => 'Yes',
 7791:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 7792:                                  );
 7793:                 $datatable .= '<table width="100%">';
 7794:                 foreach my $option (@options) {
 7795:                     my $checked = ' ';
 7796:                     if ($defaults{$item} eq $option) {
 7797:                         $checked = ' checked="checked"';
 7798:                     }
 7799:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 7800:                                   '<label><input type="radio" name="'.$item.
 7801:                                   '" value="'.$option.'"'.$checked.' />'.
 7802:                                   $optiondesc{$option}.'</label></span></td></tr>';
 7803:                 }
 7804:                 $datatable .= '</table>';
 7805:             } elsif ($item eq 'intauth_check') {
 7806:                 my @options = (0,1,2);
 7807:                 my %optiondesc = &Apache::lonlocal::texthash (
 7808:                                    0 => 'No',
 7809:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 7810:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 7811:                                  );
 7812:                 $datatable .= '<table width="100%">';
 7813:                 foreach my $option (@options) {
 7814:                     my $checked = ' ';
 7815:                     my $onclick;
 7816:                     if ($defaults{$item} eq $option) {
 7817:                         $checked = ' checked="checked"';
 7818:                     }
 7819:                     if ($option == 2) {
 7820:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 7821:                     }
 7822:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 7823:                                   '<label><input type="radio" name="'.$item.
 7824:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 7825:                                   $optiondesc{$option}.'</label></span></td></tr>';
 7826:                 }
 7827:                 $datatable .= '</table>';
 7828:             } else {
 7829:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 7830:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 7831:             }
 7832:             $datatable .= '</td></tr>';
 7833:             $itemcount ++;
 7834:         }
 7835:     } elsif ($position eq 'lower') {
 7836:         $datatable .= &password_rules('passwords',\$itemcount,$settings);
 7837:     } else {
 7838:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7839:         my %ownerchg = (
 7840:                           by  => {},
 7841:                           for => {},
 7842:                        );
 7843:         my %ownertitles = &Apache::lonlocal::texthash (
 7844:                             by  => 'Course owner status(es) allowed',
 7845:                             for => 'Student status(es) allowed',
 7846:                           );
 7847:         if (ref($settings) eq 'HASH') {
 7848:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 7849:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 7850:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 7851:                 }
 7852:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 7853:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 7854:                 }
 7855:             }
 7856:         }
 7857:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7858:         $datatable .= '<tr '.$css_class.'>'.
 7859:                       '<td>'.
 7860:                       &mt('Requirements').'<ul>'.
 7861:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 7862:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 7863:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 7864:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 7865:                       '</ul>'.
 7866:                       '</td>'.
 7867:                       '<td class="LC_left_item">';
 7868:         foreach my $item ('by','for') {
 7869:             $datatable .= '<fieldset style="display: inline-block;">'.
 7870:                           '<legend>'.$ownertitles{$item}.'</legend>';
 7871:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7872:                 foreach my $type (@{$types}) {
 7873:                     my $checked;
 7874:                     if ($ownerchg{$item}{$type}) {
 7875:                         $checked = ' checked="checked"';
 7876:                     }
 7877:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7878:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 7879:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 7880:                                   '</span>&nbsp;&nbsp; ';
 7881:                 }
 7882:             }
 7883:             my $checked;
 7884:             if ($ownerchg{$item}{'default'}) {
 7885:                 $checked = ' checked="checked"';
 7886:             }
 7887:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7888:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 7889:                           $othertitle.'</label></span></fieldset>';
 7890:         }
 7891:         $datatable .= '</td></tr>';
 7892:     }
 7893:     return $datatable;
 7894: }
 7895: 
 7896: sub password_rules {
 7897:     my ($prefix,$itemcountref,$settings) = @_;
 7898:     my ($min,$max,%chars,$expire,$numsaved,$numinrow);
 7899:     my %titles;
 7900:     if ($prefix eq 'passwords') {
 7901:         %titles = &Apache::lonlocal::texthash (
 7902:             min            => 'Minimum password length',
 7903:             max            => 'Maximum password length',
 7904:             chars          => 'Required characters',
 7905:         );
 7906:     } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
 7907:         %titles = &Apache::lonlocal::texthash (
 7908:             min            => 'Minimum secret length',
 7909:             max            => 'Maximum secret length',
 7910:             chars          => 'Required characters',
 7911:         );
 7912:     }
 7913:     $min = $Apache::lonnet::passwdmin;
 7914:     my $datatable;
 7915:     my $itemcount;
 7916:     if (ref($itemcountref)) {
 7917:         $itemcount = $$itemcountref;
 7918:     }
 7919:     if (ref($settings) eq 'HASH') {
 7920:         if ($settings->{min}) {
 7921:             $min = $settings->{min};
 7922:         }
 7923:         if ($settings->{max}) {
 7924:             $max = $settings->{max};
 7925:         }
 7926:         if (ref($settings->{chars}) eq 'ARRAY') {
 7927:             map { $chars{$_} = 1; } (@{$settings->{chars}});
 7928:         }
 7929:         if ($prefix eq 'passwords') {
 7930:             if ($settings->{expire}) {
 7931:                 $expire = $settings->{expire};
 7932:             }
 7933:             if ($settings->{numsaved}) {
 7934:                 $numsaved = $settings->{numsaved};
 7935:             }
 7936:         }
 7937:     }
 7938:     my %rulenames = &Apache::lonlocal::texthash(
 7939:                                                  uc => 'At least one upper case letter',
 7940:                                                  lc => 'At least one lower case letter',
 7941:                                                  num => 'At least one number',
 7942:                                                  spec => 'At least one non-alphanumeric',
 7943:                                                );
 7944:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7945:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 7946:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 7947:                   '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
 7948:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 7949:                   '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 7950:                   '</span></td></tr>';
 7951:     $itemcount ++;
 7952:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7953:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 7954:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 7955:                   '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
 7956:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 7957:                   '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 7958:                   '</span></td></tr>';
 7959:     $itemcount ++;
 7960:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7961:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 7962:                   '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 7963:                   '</span></td>';
 7964:     my $numinrow = 2;
 7965:     my @possrules = ('uc','lc','num','spec');
 7966:     $datatable .= '<td class="LC_left_item"><table>';
 7967:     for (my $i=0; $i<@possrules; $i++) {
 7968:         my ($rem,$checked);
 7969:         if ($chars{$possrules[$i]}) {
 7970:             $checked = ' checked="checked"';
 7971:         }
 7972:         $rem = $i%($numinrow);
 7973:         if ($rem == 0) {
 7974:             if ($i > 0) {
 7975:                 $datatable .= '</tr>';
 7976:             }
 7977:             $datatable .= '<tr>';
 7978:         }
 7979:         $datatable .= '<td><span class="LC_nobreak"><label>'.
 7980:                       '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 7981:                       $rulenames{$possrules[$i]}.'</label></span></td>';
 7982:     }
 7983:     my $rem = @possrules%($numinrow);
 7984:     my $colsleft = $numinrow - $rem;
 7985:     if ($colsleft > 1 ) {
 7986:         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7987:                       '&nbsp;</td>';
 7988:     } elsif ($colsleft == 1) {
 7989:         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7990:     }
 7991:     $datatable .='</table></td></tr>';
 7992:     $itemcount ++;
 7993:     if ($prefix eq 'passwords') {
 7994:         $titles{'expire'} = &mt('Password expiration (days)');
 7995:         $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
 7996:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7997:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 7998:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7999:                       '<input type="text" name="'.$prefix.'_expire" value="'.$expire.'" size="4" '.
 8000:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8001:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 8002:                       '</span></td></tr>';
 8003:         $itemcount ++;
 8004:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8005:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 8006:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8007:                       '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
 8008:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8009:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 8010:                       '</span></td></tr>';
 8011:         $itemcount ++;
 8012:     }
 8013:     if (ref($itemcountref)) {
 8014:         $$itemcountref += $itemcount;
 8015:     }
 8016:     return $datatable;
 8017: }
 8018: 
 8019: sub print_wafproxy {
 8020:     my ($position,$dom,$settings,$rowtotal) = @_;
 8021:     my $css_class;
 8022:     my $itemcount = 0;
 8023:     my $datatable;
 8024:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8025:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 8026:     my %lt = &wafproxy_titles();
 8027:     foreach my $server (sort(keys(%servers))) {
 8028:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 8029:         next if ($serverhome eq '');
 8030:         my $serverdom;
 8031:         if ($serverhome ne $server) {
 8032:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 8033:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 8034:                 $othercontrol{$server} = $serverdom;
 8035:             }
 8036:         } else {
 8037:             $serverdom = &Apache::lonnet::host_domain($server);
 8038:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 8039:             if ($serverdom ne $dom) {
 8040:                 $othercontrol{$server} = $serverdom;
 8041:             } else {
 8042:                 $setdom = 1;
 8043:                 if (ref($settings) eq 'HASH') {
 8044:                     if (ref($settings->{'alias'}) eq 'HASH') {
 8045:                         $aliases{$dom} = $settings->{'alias'};
 8046:                         if ($aliases{$dom} ne '') {
 8047:                             $showdom = 1;
 8048:                         }
 8049:                     }
 8050:                     if (ref($settings->{'saml'}) eq 'HASH') {
 8051:                         $saml{$dom} = $settings->{'saml'};
 8052:                     }
 8053:                 }
 8054:             }
 8055:         }
 8056:     }
 8057:     if ($setdom) {
 8058:         %{$values{$dom}} = ();
 8059:         if (ref($settings) eq 'HASH') {
 8060:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8061:                 $values{$dom}{$item} = $settings->{$item};
 8062:             }
 8063:         }
 8064:     }
 8065:     if (keys(%othercontrol)) {
 8066:         %otherdoms = reverse(%othercontrol);
 8067:         foreach my $domain (keys(%otherdoms)) {
 8068:             %{$values{$domain}} = ();
 8069:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 8070:             if (ref($config{'wafproxy'}) eq 'HASH') {
 8071:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 8072:                 if (exists($config{'wafproxy'}{'saml'})) {
 8073:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 8074:                 }
 8075:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8076:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 8077:                 }
 8078:             }
 8079:         }
 8080:     }
 8081:     if ($position eq 'top') {
 8082:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8083:         my %aliasinfo;
 8084:         foreach my $server (sort(keys(%servers))) {
 8085:             $itemcount ++;
 8086:             my $dom_in_effect;
 8087:             my $aliasrows = '<tr>'.
 8088:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8089:                             &mt('Hostname').':&nbsp;'.
 8090:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 8091:             if ($othercontrol{$server}) {
 8092:                 $dom_in_effect = $othercontrol{$server};
 8093:                 my ($current,$forsaml);
 8094:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 8095:                     $current = $aliases{$dom_in_effect}{$server};
 8096:                 }
 8097:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 8098:                     if ($saml{$dom_in_effect}{$server}) {
 8099:                         $forsaml = 1;
 8100:                     }
 8101:                 }
 8102:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8103:                               &mt('Alias').':&nbsp';
 8104:                 if ($current) {
 8105:                     $aliasrows .= $current;
 8106:                     if ($forsaml) {
 8107:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 8108:                     }
 8109:                 } else {
 8110:                     $aliasrows .= &mt('None');
 8111:                 }
 8112:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 8113:                               &mt('controlled by domain: [_1]',
 8114:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 8115:             } else {
 8116:                 $dom_in_effect = $dom;
 8117:                 my ($current,$samlon,$samloff);
 8118:                 $samloff = ' checked="checked"';
 8119:                 if (ref($aliases{$dom}) eq 'HASH') {
 8120:                     if ($aliases{$dom}{$server}) {
 8121:                         $current = $aliases{$dom}{$server};
 8122:                     }
 8123:                 }
 8124:                 if (ref($saml{$dom}) eq 'HASH') {
 8125:                     if ($saml{$dom}{$server}) {
 8126:                         $samlon = $samloff;
 8127:                         undef($samloff);
 8128:                     }
 8129:                 }
 8130:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8131:                               &mt('Alias').':&nbsp;'.
 8132:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 8133:                               'value="'.$current.'" size="30" />'.
 8134:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 8135:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 8136:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 8137:                               &mt('No').'</label>&nbsp;<label>'.
 8138:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 8139:                               &mt('Yes').'</label></span>'.
 8140:                               '</td>';
 8141:             }
 8142:             $aliasrows .= '</tr>';
 8143:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 8144:         }
 8145:         if ($aliasinfo{$dom}) {
 8146:             my ($onclick,$wafon,$wafoff,$showtable);
 8147:             $onclick = ' onclick="javascript:toggleWAF();"';
 8148:             $wafoff = ' checked="checked"';
 8149:             $showtable = ' style="display:none";';
 8150:             if ($showdom) {
 8151:                 $wafon = $wafoff;
 8152:                 $wafoff = '';
 8153:                 $showtable = ' style="display:inline;"';
 8154:             }
 8155:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8156:             $datatable = '<tr'.$css_class.'>'.
 8157:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 8158:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 8159:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 8160:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 8161:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 8162:                          &mt('No').'</label></span></td>'.
 8163:                          '<td class="LC_left_item">'.
 8164:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 8165:                          '</table></td></tr>';
 8166:             $itemcount++;
 8167:         }
 8168:         if (keys(%otherdoms)) {
 8169:             foreach my $key (sort(keys(%otherdoms))) {
 8170:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8171:                 $datatable .= '<tr'.$css_class.'>'.
 8172:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 8173:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 8174:                               '</table></td></tr>';
 8175:                 $itemcount++;
 8176:             }
 8177:         }
 8178:     } else {
 8179:         my %ip_methods = &remoteip_methods();
 8180:         if ($setdom) {
 8181:             $itemcount ++;
 8182:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8183:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 8184:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 8185:             $wafstyle = ' style="display:none;"';
 8186:             $nowafstyle = ' style="display:table-row;"';
 8187:             $currwafdisplay = ' style="display: none"';
 8188:             $wafrangestyle = ' style="display: none"';
 8189:             $curr_remotip = 'n';
 8190:             $ssltossl = ' checked="checked"';
 8191:             if ($showdom) {
 8192:                 $wafstyle = ' style="display:table-row;"';
 8193:                 $nowafstyle =  ' style="display:none;"';
 8194:                 if (keys(%{$values{$dom}})) {
 8195:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 8196:                         $curr_remotip = $values{$dom}{remoteip};
 8197:                     }
 8198:                     if ($curr_remotip eq 'h') {
 8199:                         $currwafdisplay = ' style="display:table-row"';
 8200:                         $wafrangestyle = ' style="display:inline-block;"';
 8201:                     }
 8202:                     if ($values{$dom}{'sslopt'}) {
 8203:                         $alltossl = ' checked="checked"';
 8204:                         $ssltossl = '';
 8205:                     }
 8206:                 }
 8207:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 8208:                     $vpndircheck = ' checked="checked"';
 8209:                     $currwafvpn = ' style="display:table-row;"';
 8210:                     $wafrangestyle = ' style="display:inline-block;"';
 8211:                 } else {
 8212:                     $vpnaliascheck = ' checked="checked"';
 8213:                     $currwafvpn = ' style="display:none;"';
 8214:                 }
 8215:             }
 8216:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8217:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 8218:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 8219:                           '</tr>'.
 8220:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8221:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 8222:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 8223:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 8224:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 8225:                           '<td class="LC_left_item"><table>'.
 8226:                           '<tr>'.
 8227:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 8228:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 8229:             foreach my $option ('m','h','n') {
 8230:                 my $sel;
 8231:                 if ($option eq $curr_remotip) {
 8232:                    $sel = ' selected="selected"';
 8233:                 }
 8234:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 8235:                               $ip_methods{$option}.'</option>';
 8236:             }
 8237:             $datatable .= '</select></td></tr>'."\n".
 8238:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 8239:                           $lt{'ipheader'}.':&nbsp;'.
 8240:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 8241:                           'name="wafproxy_ipheader" />'.
 8242:                           '</td></tr>'."\n".
 8243:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 8244:                           $lt{'trusted'}.':<br />'.
 8245:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 8246:                           $values{$dom}{'trusted'}.'</textarea>'.
 8247:                           '</td></tr>'."\n".
 8248:                           '<tr><td><hr /></td></tr>'."\n".
 8249:                           '<tr>'.
 8250:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 8251:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 8252:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 8253:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 8254:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 8255:             foreach my $item ('vpnint','vpnext') {
 8256:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 8257:                               '<td valign="top">'.$lt{$item}.':<br />'.
 8258:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 8259:                               $values{$dom}{$item}.'</textarea>'.
 8260:                               '</td></tr>'."\n";
 8261:             }
 8262:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 8263:                           '<tr>'.
 8264:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 8265:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 8266:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 8267:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 8268:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 8269:                           '</table></td></tr>';
 8270:         }
 8271:         if (keys(%otherdoms)) {
 8272:             foreach my $domain (sort(keys(%otherdoms))) {
 8273:                 $itemcount ++;
 8274:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8275:                 $datatable .= '<tr'.$css_class.'>'.
 8276:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 8277:                               '<td class="LC_left_item"><table>';
 8278:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 8279:                     my $showval = &mt('None');
 8280:                     if ($item eq 'ssl') {
 8281:                         $showval = $lt{'ssltossl'};
 8282:                     }
 8283:                     if ($values{$domain}{$item}) {
 8284:                         $showval = $values{$domain}{$item};
 8285:                         if ($item eq 'ssl') {
 8286:                             $showval = $lt{'alltossl'};
 8287:                         } elsif ($item eq 'remoteip') {
 8288:                             $showval = $ip_methods{$values{$domain}{$item}};
 8289:                         }
 8290:                     }
 8291:                     $datatable .= '<tr>'.
 8292:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 8293:                 }
 8294:                 $datatable .= '</table></td></tr>';
 8295:             }
 8296:         }
 8297:     }
 8298:     $$rowtotal += $itemcount;
 8299:     return $datatable;
 8300: }
 8301: 
 8302: sub wafproxy_titles {
 8303:     return &Apache::lonlocal::texthash(
 8304:                remoteip   => "Method for determining user's IP",
 8305:                ipheader   => 'Request header containing remote IP',
 8306:                trusted    => 'Trusted IP range(s)',
 8307:                vpnaccess  => 'Access from institutional VPN',
 8308:                vpndirect  => 'via regular hostname (no WAF)',
 8309:                vpnaliased => 'via aliased hostname (WAF)',
 8310:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 8311:                vpnext     => 'IP Range(s) for backend WAF connections',
 8312:                sslopt     => 'Forwarding http/https',
 8313:                alltossl   => 'WAF forwards both http and https requests to https',
 8314:                ssltossl   => 'WAF forwards http requests to http and https to https',
 8315:            );
 8316: }
 8317: 
 8318: sub remoteip_methods {
 8319:     return &Apache::lonlocal::texthash(
 8320:               m => 'Use Apache mod_remoteip',
 8321:               h => 'Use headers parsed by LON-CAPA',
 8322:               n => 'Not in use',
 8323:            );
 8324: }
 8325: 
 8326: sub print_usersessions {
 8327:     my ($position,$dom,$settings,$rowtotal) = @_;
 8328:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 8329:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8330:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8331: 
 8332:     my @alldoms = &Apache::lonnet::all_domains();
 8333:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8334:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8335:     my %altids = &id_for_thisdom(%servers);
 8336:     if ($position eq 'top') {
 8337:         if (keys(%serverhomes) > 1) {
 8338:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 8339:             my ($curroffloadnow,$curroffloadoth);
 8340:             if (ref($settings) eq 'HASH') {
 8341:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 8342:                     $curroffloadnow = $settings->{'offloadnow'};
 8343:                 }
 8344:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 8345:                     $curroffloadoth = $settings->{'offloadoth'};
 8346:                 }
 8347:             }
 8348:             my $other_insts = scalar(keys(%by_location));
 8349:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 8350:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 8351:         } else {
 8352:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 8353:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 8354:                           '</td></tr>';
 8355:         }
 8356:     } else {
 8357:         my %titles = &usersession_titles();
 8358:         my ($prefix,@types);
 8359:         if ($position eq 'bottom') {
 8360:             $prefix = 'remote';
 8361:             @types = ('version','excludedomain','includedomain');
 8362:         } else {
 8363:             $prefix = 'hosted';
 8364:             @types = ('excludedomain','includedomain');
 8365:         }
 8366:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8367:     }
 8368:     $$rowtotal += $itemcount;
 8369:     return $datatable;
 8370: }
 8371: 
 8372: sub rules_by_location {
 8373:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 8374:     my ($datatable,$itemcount,$css_class);
 8375:     if (keys(%{$by_location}) == 0) {
 8376:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8377:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 8378:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 8379:                      '</td></tr>';
 8380:         $itemcount = 1;
 8381:     } else {
 8382:         $itemcount = 0;
 8383:         my $numinrow = 5;
 8384:         my (%current,%checkedon,%checkedoff);
 8385:         my @locations = sort(keys(%{$by_location}));
 8386:         foreach my $type (@{$types}) {
 8387:             $checkedon{$type} = '';
 8388:             $checkedoff{$type} = ' checked="checked"';
 8389:         }
 8390:         if (ref($settings) eq 'HASH') {
 8391:             if (ref($settings->{$prefix}) eq 'HASH') {
 8392:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 8393:                     $current{$key} = $settings->{$prefix}{$key};
 8394:                     if ($key eq 'version') {
 8395:                         if ($current{$key} ne '') {
 8396:                             $checkedon{$key} = ' checked="checked"';
 8397:                             $checkedoff{$key} = '';
 8398:                         }
 8399:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 8400:                         $checkedon{$key} = ' checked="checked"';
 8401:                         $checkedoff{$key} = '';
 8402:                     }
 8403:                 }
 8404:             }
 8405:         }
 8406:         foreach my $type (@{$types}) {
 8407:             next if ($type ne 'version' && !@locations);
 8408:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8409:             $datatable .= '<tr'.$css_class.'>
 8410:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 8411:                            <span class="LC_nobreak">&nbsp;
 8412:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 8413:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 8414:             if ($type eq 'version') {
 8415:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 8416:                 my $selector = '<select name="'.$prefix.'_version">';
 8417:                 foreach my $version (@lcversions) {
 8418:                     my $selected = '';
 8419:                     if ($current{'version'} eq $version) {
 8420:                         $selected = ' selected="selected"';
 8421:                     }
 8422:                     $selector .= ' <option value="'.$version.'"'.
 8423:                                  $selected.'>'.$version.'</option>';
 8424:                 }
 8425:                 $selector .= '</select> ';
 8426:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 8427:             } else {
 8428:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 8429:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 8430:                              ' />'.('&nbsp;'x2).
 8431:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 8432:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 8433:                              "\n".
 8434:                              '</div><div><table>';
 8435:                 my $rem;
 8436:                 for (my $i=0; $i<@locations; $i++) {
 8437:                     my ($showloc,$value,$checkedtype);
 8438:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 8439:                         my $ip = $by_location->{$locations[$i]}->[0];
 8440:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8441:                             $value = join(':',@{$by_ip->{$ip}});
 8442:                             $showloc = join(', ',@{$by_ip->{$ip}});
 8443:                             if (ref($current{$type}) eq 'ARRAY') {
 8444:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 8445:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 8446:                                         $checkedtype = ' checked="checked"';
 8447:                                         last;
 8448:                                     }
 8449:                                 }
 8450:                             }
 8451:                         }
 8452:                     }
 8453:                     $rem = $i%($numinrow);
 8454:                     if ($rem == 0) {
 8455:                         if ($i > 0) {
 8456:                             $datatable .= '</tr>';
 8457:                         }
 8458:                         $datatable .= '<tr>';
 8459:                     }
 8460:                     $datatable .= '<td class="LC_left_item">'.
 8461:                                   '<span class="LC_nobreak"><label>'.
 8462:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 8463:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 8464:                                   '</label></span></td>';
 8465:                 }
 8466:                 $rem = @locations%($numinrow);
 8467:                 my $colsleft = $numinrow - $rem;
 8468:                 if ($colsleft > 1 ) {
 8469:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8470:                                   '&nbsp;</td>';
 8471:                 } elsif ($colsleft == 1) {
 8472:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8473:                 }
 8474:                 $datatable .= '</tr></table>';
 8475:             }
 8476:             $datatable .= '</td></tr>';
 8477:             $itemcount ++;
 8478:         }
 8479:     }
 8480:     return ($datatable,$itemcount);
 8481: }
 8482: 
 8483: sub print_ssl {
 8484:     my ($position,$dom,$settings,$rowtotal) = @_;
 8485:     my ($css_class,$datatable);
 8486:     my $itemcount = 1;
 8487:     if ($position eq 'top') {
 8488:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8489:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8490:         my $same_institution;
 8491:         if ($intdom ne '') {
 8492:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 8493:             if (ref($internet_names) eq 'ARRAY') {
 8494:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8495:                     $same_institution = 1;
 8496:                 }
 8497:             }
 8498:         }
 8499:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8500:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 8501:         if ($same_institution) {
 8502:             my %domservers = &Apache::lonnet::get_servers($dom);
 8503:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 8504:         } else {
 8505:             $datatable .= &mt("You need to be logged into one of your own domain's servers to display information about the status of LON-CAPA SSL certificates.");
 8506:         }
 8507:         $datatable .= '</td></tr>';
 8508:         $itemcount ++;
 8509:     } else {
 8510:         my %titles = &ssl_titles();
 8511:         my (%by_ip,%by_location,@intdoms,@instdoms);
 8512:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8513:         my @alldoms = &Apache::lonnet::all_domains();
 8514:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8515:         my @domservers = &Apache::lonnet::get_servers($dom);
 8516:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8517:         my %altids = &id_for_thisdom(%servers);
 8518:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 8519:             my $legacy;
 8520:             unless (ref($settings) eq 'HASH') {
 8521:                 my $name;
 8522:                 if ($position eq 'connto') {
 8523:                     $name = 'loncAllowInsecure';
 8524:                 } else {
 8525:                     $name = 'londAllowInsecure';
 8526:                 }
 8527:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 8528:                 my @ids=&Apache::lonnet::current_machine_ids();
 8529:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 8530:                     my %what = (
 8531:                                    $name => 1,
 8532:                                );
 8533:                     my ($result,$returnhash) =
 8534:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 8535:                     if ($result eq 'ok') {
 8536:                         if (ref($returnhash) eq 'HASH') {
 8537:                             $legacy = $returnhash->{$name};
 8538:                         }
 8539:                     }
 8540:                 } else {
 8541:                     $legacy = $Apache::lonnet::perlvar{$name};
 8542:                 }
 8543:             }
 8544:             foreach my $type ('dom','intdom','other') {
 8545:                 my %checked;
 8546:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8547:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 8548:                               '<td class="LC_right_item">';
 8549:                 my $skip; 
 8550:                 if ($type eq 'dom') {
 8551:                     unless (keys(%servers) > 1) {
 8552:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 8553:                         $skip = 1;
 8554:                     }
 8555:                 }
 8556:                 if ($type eq 'intdom') {
 8557:                     unless (@instdoms > 1) {
 8558:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 8559:                         $skip = 1;
 8560:                     } 
 8561:                 } elsif ($type eq 'other') {
 8562:                     if (keys(%by_location) == 0) {
 8563:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 8564:                         $skip = 1;
 8565:                     }
 8566:                 }
 8567:                 unless ($skip) {
 8568:                     $checked{'yes'} = ' checked="checked"'; 
 8569:                     if (ref($settings) eq 'HASH') {
 8570:                         if (ref($settings->{$position}) eq 'HASH') {
 8571:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 8572:                                 $checked{$1} = $checked{'yes'};
 8573:                                 delete($checked{'yes'}); 
 8574:                             }
 8575:                         }
 8576:                     } else {
 8577:                         if ($legacy == 0) {
 8578:                             $checked{'req'} = $checked{'yes'};
 8579:                             delete($checked{'yes'});    
 8580:                         }
 8581:                     }
 8582:                     foreach my $option ('no','yes','req') {
 8583:                         $datatable .= '<span class="LC_nobreak"><label>'.
 8584:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 8585:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 8586:                                       '</label></span>'.('&nbsp;'x2);
 8587:                     }
 8588:                 }
 8589:                 $datatable .= '</td></tr>';
 8590:                 $itemcount ++; 
 8591:             }
 8592:         } else {
 8593:             my $prefix = 'replication';
 8594:             my @types = ('certreq','nocertreq');
 8595:             if (keys(%by_location) == 0) {
 8596:                 $datatable .= '<tr'.$css_class.'><td>'.
 8597:                               &mt('Nothing to set here, as there are no other institutions').
 8598:                               '</td></tr>';
 8599:                 $itemcount ++;
 8600:             } else {
 8601:                 ($datatable,$itemcount) = 
 8602:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8603:             }
 8604:         }
 8605:     }
 8606:     $$rowtotal += $itemcount;
 8607:     return $datatable;
 8608: }
 8609: 
 8610: sub ssl_titles {
 8611:     return &Apache::lonlocal::texthash (
 8612:                dom           => 'LON-CAPA servers/VMs from same domain',
 8613:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 8614:                other         => 'External LON-CAPA servers/VMs',
 8615:                connto        => 'Connections to other servers',
 8616:                connfrom      => 'Connections from other servers',
 8617:                replication   => 'Replicating content to other institutions',
 8618:                certreq       => 'Client certificate required, but specific domains exempt',
 8619:                nocertreq     => 'No client certificate required, except for specific domains',
 8620:                no            => 'SSL not used',
 8621:                yes           => 'SSL Optional (used if available)',
 8622:                req           => 'SSL Required',
 8623:     );
 8624: }
 8625: 
 8626: sub print_trust {
 8627:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 8628:     my ($css_class,$datatable,%checked,%choices);
 8629:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8630:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8631:     my $itemcount = 1;
 8632:     my %titles = &trust_titles();
 8633:     my @types = ('exc','inc');
 8634:     if ($prefix eq 'top') {
 8635:         $prefix = 'content';
 8636:     } elsif ($prefix eq 'bottom') {
 8637:         $prefix = 'msg';
 8638:     }
 8639:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8640:     $$rowtotal += $itemcount;
 8641:     return $datatable;
 8642: }
 8643: 
 8644: sub trust_titles {
 8645:     return &Apache::lonlocal::texthash(
 8646:                content  => "Access to this domain's content by others",
 8647:                shared   => "Access to other domain's content by this domain",
 8648:                enroll   => "Enrollment in this domain's courses by others", 
 8649:                othcoau  => "Co-author roles in this domain for others",
 8650:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 8651:                domroles => "Domain roles in this domain assignable to others",
 8652:                catalog  => "Course Catalog for this domain displayed elsewhere",
 8653:                reqcrs   => "Requests for creation of courses in this domain by others",
 8654:                msg      => "Users in other domains can send messages to this domain",
 8655:                exc      => "Allow all, but exclude specific domains",
 8656:                inc      => "Deny all, but include specific domains",
 8657:            );
 8658: } 
 8659: 
 8660: sub build_location_hashes {
 8661:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 8662:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 8663:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 8664:     my %iphost = &Apache::lonnet::get_iphost();
 8665:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 8666:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 8667:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 8668:         foreach my $id (@{$iphost{$primary_ip}}) {
 8669:             my $intdom = &Apache::lonnet::internet_dom($id);
 8670:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 8671:                 push(@{$intdoms},$intdom);
 8672:             }
 8673:         }
 8674:     }
 8675:     foreach my $ip (keys(%iphost)) {
 8676:         if (ref($iphost{$ip}) eq 'ARRAY') {
 8677:             foreach my $id (@{$iphost{$ip}}) {
 8678:                 my $location = &Apache::lonnet::internet_dom($id);
 8679:                 if ($location) {
 8680:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 8681:                         my $dom = &Apache::lonnet::host_domain($id);
 8682:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 8683:                             push(@{$instdoms},$dom);
 8684:                         }
 8685:                         next;
 8686:                     }
 8687:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8688:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 8689:                             push(@{$by_ip->{$ip}},$location);
 8690:                         }
 8691:                     } else {
 8692:                         $by_ip->{$ip} = [$location];
 8693:                     }
 8694:                 }
 8695:             }
 8696:         }
 8697:     }
 8698:     foreach my $ip (sort(keys(%{$by_ip}))) {
 8699:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8700:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 8701:             my $first = $by_ip->{$ip}->[0];
 8702:             if (ref($by_location->{$first}) eq 'ARRAY') {
 8703:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 8704:                     push(@{$by_location->{$first}},$ip);
 8705:                 }
 8706:             } else {
 8707:                 $by_location->{$first} = [$ip];
 8708:             }
 8709:         }
 8710:     }
 8711:     return;
 8712: }
 8713: 
 8714: sub current_offloads_to {
 8715:     my ($dom,$settings,$servers) = @_;
 8716:     my (%spareid,%otherdomconfigs);
 8717:     if (ref($servers) eq 'HASH') {
 8718:         foreach my $lonhost (sort(keys(%{$servers}))) {
 8719:             my $gotspares;
 8720:             if (ref($settings) eq 'HASH') {
 8721:                 if (ref($settings->{'spares'}) eq 'HASH') {
 8722:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 8723:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 8724:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 8725:                         $gotspares = 1;
 8726:                     }
 8727:                 }
 8728:             }
 8729:             unless ($gotspares) {
 8730:                 my $gotspares;
 8731:                 my $serverhomeID =
 8732:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 8733:                 my $serverhomedom =
 8734:                     &Apache::lonnet::host_domain($serverhomeID);
 8735:                 if ($serverhomedom ne $dom) {
 8736:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 8737:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 8738:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 8739:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 8740:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 8741:                                 $gotspares = 1;
 8742:                             }
 8743:                         }
 8744:                     } else {
 8745:                         $otherdomconfigs{$serverhomedom} =
 8746:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 8747:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 8748:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 8749:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 8750:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 8751:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 8752:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 8753:                                         $gotspares = 1;
 8754:                                     }
 8755:                                 }
 8756:                             }
 8757:                         }
 8758:                     }
 8759:                 }
 8760:             }
 8761:             unless ($gotspares) {
 8762:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 8763:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 8764:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 8765:                } else {
 8766:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 8767:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 8768:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 8769:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 8770:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 8771:                     } else {
 8772:                         my %what = (
 8773:                              spareid => 1,
 8774:                         );
 8775:                         my ($result,$returnhash) = 
 8776:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 8777:                         if ($result eq 'ok') { 
 8778:                             if (ref($returnhash) eq 'HASH') {
 8779:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 8780:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 8781:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 8782:                                 }
 8783:                             }
 8784:                         }
 8785:                     }
 8786:                 }
 8787:             }
 8788:         }
 8789:     }
 8790:     return %spareid;
 8791: }
 8792: 
 8793: sub spares_row {
 8794:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 8795:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 8796:     my $css_class;
 8797:     my $numinrow = 4;
 8798:     my $itemcount = 1;
 8799:     my $datatable;
 8800:     my %typetitles = &sparestype_titles();
 8801:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8802:         foreach my $server (sort(keys(%{$servers}))) {
 8803:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 8804:             my ($othercontrol,$serverdom);
 8805:             if ($serverhome ne $server) {
 8806:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 8807:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8808:             } else {
 8809:                 $serverdom = &Apache::lonnet::host_domain($server);
 8810:                 if ($serverdom ne $dom) {
 8811:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8812:                 }
 8813:             }
 8814:             next unless (ref($spareid->{$server}) eq 'HASH');
 8815:             my ($checkednow,$checkedoth);
 8816:             if (ref($curroffloadnow) eq 'HASH') {
 8817:                 if ($curroffloadnow->{$server}) {
 8818:                     $checkednow = ' checked="checked"';
 8819:                 }
 8820:             }
 8821:             if (ref($curroffloadoth) eq 'HASH') {
 8822:                 if ($curroffloadoth->{$server}) {
 8823:                     $checkedoth = ' checked="checked"';
 8824:                 }
 8825:             }
 8826:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8827:             $datatable .= '<tr'.$css_class.'>
 8828:                            <td rowspan="2">
 8829:                             <span class="LC_nobreak">'.
 8830:                           &mt('[_1] when busy, offloads to:'
 8831:                               ,'<b>'.$server.'</b>').'</span><br />'.
 8832:                           '<span class="LC_nobreak">'."\n".
 8833:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 8834:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 8835:                           "\n";
 8836:             if ($other_insts) {
 8837:                 $datatable .= '<br />'.
 8838:                               '<span class="LC_nobreak">'."\n".
 8839:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 8840:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 8841:                           "\n";
 8842:             }
 8843:             my (%current,%canselect);
 8844:             my @choices = 
 8845:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 8846:             foreach my $type ('primary','default') {
 8847:                 if (ref($spareid->{$server}) eq 'HASH') {
 8848:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 8849:                         my @spares = @{$spareid->{$server}{$type}};
 8850:                         if (@spares > 0) {
 8851:                             if ($othercontrol) {
 8852:                                 $current{$type} = join(', ',@spares);
 8853:                             } else {
 8854:                                 $current{$type} .= '<table>';
 8855:                                 my $numspares = scalar(@spares);
 8856:                                 for (my $i=0;  $i<@spares; $i++) {
 8857:                                     my $rem = $i%($numinrow);
 8858:                                     if ($rem == 0) {
 8859:                                         if ($i > 0) {
 8860:                                             $current{$type} .= '</tr>';
 8861:                                         }
 8862:                                         $current{$type} .= '<tr>';
 8863:                                     }
 8864:                                     $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;'.
 8865:                                                        $spareid->{$server}{$type}[$i].
 8866:                                                        '</label></td>'."\n";
 8867:                                 }
 8868:                                 my $rem = @spares%($numinrow);
 8869:                                 my $colsleft = $numinrow - $rem;
 8870:                                 if ($colsleft > 1 ) {
 8871:                                     $current{$type} .= '<td colspan="'.$colsleft.
 8872:                                                        '" class="LC_left_item">'.
 8873:                                                        '&nbsp;</td>';
 8874:                                 } elsif ($colsleft == 1) {
 8875:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 8876:                                 }
 8877:                                 $current{$type} .= '</tr></table>';
 8878:                             }
 8879:                         }
 8880:                     }
 8881:                     if ($current{$type} eq '') {
 8882:                         $current{$type} = &mt('None specified');
 8883:                     }
 8884:                     if ($othercontrol) {
 8885:                         if ($type eq 'primary') {
 8886:                             $canselect{$type} = $othercontrol;
 8887:                         }
 8888:                     } else {
 8889:                         $canselect{$type} = 
 8890:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 8891:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 8892:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 8893:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 8894:                         if (@choices > 0) {
 8895:                             foreach my $lonhost (@choices) {
 8896:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 8897:                             }
 8898:                         }
 8899:                         $canselect{$type} .= '</select>'."\n";
 8900:                     }
 8901:                 } else {
 8902:                     $current{$type} = &mt('Could not be determined');
 8903:                     if ($type eq 'primary') {
 8904:                         $canselect{$type} =  $othercontrol;
 8905:                     }
 8906:                 }
 8907:                 if ($type eq 'default') {
 8908:                     $datatable .= '<tr'.$css_class.'>';
 8909:                 }
 8910:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 8911:                               '<td>'.$current{$type}.'</td>'."\n".
 8912:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 8913:             }
 8914:             $itemcount ++;
 8915:         }
 8916:     }
 8917:     $$rowtotal += $itemcount;
 8918:     return $datatable;
 8919: }
 8920: 
 8921: sub possible_newspares {
 8922:     my ($server,$currspares,$serverhomes,$altids) = @_;
 8923:     my $serverhostname = &Apache::lonnet::hostname($server);
 8924:     my %excluded;
 8925:     if ($serverhostname ne '') {
 8926:         %excluded = (
 8927:                        $serverhostname => 1,
 8928:                     );
 8929:     }
 8930:     if (ref($currspares) eq 'HASH') {
 8931:         foreach my $type (keys(%{$currspares})) {
 8932:             if (ref($currspares->{$type}) eq 'ARRAY') {
 8933:                 if (@{$currspares->{$type}} > 0) {
 8934:                     foreach my $curr (@{$currspares->{$type}}) {
 8935:                         my $hostname = &Apache::lonnet::hostname($curr);
 8936:                         $excluded{$hostname} = 1;
 8937:                     }
 8938:                 }
 8939:             }
 8940:         }
 8941:     }
 8942:     my @choices;
 8943:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8944:         if (keys(%{$serverhomes}) > 1) {
 8945:             foreach my $name (sort(keys(%{$serverhomes}))) {
 8946:                 unless ($excluded{$name}) {
 8947:                     if (exists($altids->{$serverhomes->{$name}})) {
 8948:                         push(@choices,$altids->{$serverhomes->{$name}});
 8949:                     } else {
 8950:                         push(@choices,$serverhomes->{$name});
 8951:                     }
 8952:                 }
 8953:             }
 8954:         }
 8955:     }
 8956:     return sort(@choices);
 8957: }
 8958: 
 8959: sub print_loadbalancing {
 8960:     my ($dom,$settings,$rowtotal) = @_;
 8961:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8962:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8963:     my $numinrow = 1;
 8964:     my $datatable;
 8965:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8966:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 8967:     if (ref($settings) eq 'HASH') {
 8968:         %existing = %{$settings};
 8969:     }
 8970:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 8971:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 8972:                                   \%currtargets,\%currrules,\%currcookies);
 8973:     } else {
 8974:         return;
 8975:     }
 8976:     my ($othertitle,$usertypes,$types) =
 8977:         &Apache::loncommon::sorted_inst_types($dom);
 8978:     my $rownum = 8;
 8979:     if (ref($types) eq 'ARRAY') {
 8980:         $rownum += scalar(@{$types});
 8981:     }
 8982:     my @css_class = ('LC_odd_row','LC_even_row');
 8983:     my $balnum = 0;
 8984:     my $islast;
 8985:     my (@toshow,$disabledtext);
 8986:     if (keys(%currbalancer) > 0) {
 8987:         @toshow = sort(keys(%currbalancer));
 8988:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 8989:             push(@toshow,'');
 8990:         }
 8991:     } else {
 8992:         @toshow = ('');
 8993:         $disabledtext = &mt('No existing load balancer');
 8994:     }
 8995:     foreach my $lonhost (@toshow) {
 8996:         if ($balnum == scalar(@toshow)-1) {
 8997:             $islast = 1;
 8998:         } else {
 8999:             $islast = 0;
 9000:         }
 9001:         my $cssidx = $balnum%2;
 9002:         my $targets_div_style = 'display: none';
 9003:         my $disabled_div_style = 'display: block';
 9004:         my $homedom_div_style = 'display: none';
 9005:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 9006:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9007:                       '<p>';
 9008:         if ($lonhost eq '') {
 9009:             $datatable .= '<span class="LC_nobreak">';
 9010:             if (keys(%currbalancer) > 0) {
 9011:                 $datatable .= &mt('Add balancer:');
 9012:             } else {
 9013:                 $datatable .= &mt('Enable balancer:');
 9014:             }
 9015:             $datatable .= '&nbsp;'.
 9016:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 9017:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 9018:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 9019:                           '<option value="" selected="selected">'.&mt('None').
 9020:                           '</option>'."\n";
 9021:             foreach my $server (sort(keys(%servers))) {
 9022:                 next if ($currbalancer{$server});
 9023:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 9024:             }
 9025:             $datatable .=
 9026:                 '</select>'."\n".
 9027:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 9028:         } else {
 9029:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 9030:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 9031:                            &mt('Stop balancing').'</label>'.
 9032:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 9033:             $targets_div_style = 'display: block';
 9034:             $disabled_div_style = 'display: none';
 9035:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 9036:                 $homedom_div_style = 'display: block';
 9037:             }
 9038:         }
 9039:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9040:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 9041:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 9042:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 9043:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 9044:         my @sparestypes = ('primary','default');
 9045:         my %typetitles = &sparestype_titles();
 9046:         my %hostherechecked = (
 9047:                                   no => ' checked="checked"',
 9048:                               );
 9049:         my %balcookiechecked = (
 9050:                                   no => ' checked="checked"',
 9051:                                );
 9052:         foreach my $sparetype (@sparestypes) {
 9053:             my $targettable;
 9054:             for (my $i=0; $i<$numspares; $i++) {
 9055:                 my $checked;
 9056:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 9057:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9058:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9059:                             $checked = ' checked="checked"';
 9060:                         }
 9061:                     }
 9062:                 }
 9063:                 my ($chkboxval,$disabled);
 9064:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 9065:                     $chkboxval = $spares[$i];
 9066:                 }
 9067:                 if (exists($currbalancer{$spares[$i]})) {
 9068:                     $disabled = ' disabled="disabled"';
 9069:                 }
 9070:                 $targettable .=
 9071:                     '<td><span class="LC_nobreak"><label>'.
 9072:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 9073:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 9074:                     '</span></label></span></td>';
 9075:                 my $rem = $i%($numinrow);
 9076:                 if ($rem == 0) {
 9077:                     if (($i > 0) && ($i < $numspares-1)) {
 9078:                         $targettable .= '</tr>';
 9079:                     }
 9080:                     if ($i < $numspares-1) {
 9081:                         $targettable .= '<tr>';
 9082:                     }
 9083:                 }
 9084:             }
 9085:             if ($targettable ne '') {
 9086:                 my $rem = $numspares%($numinrow);
 9087:                 my $colsleft = $numinrow - $rem;
 9088:                 if ($colsleft > 1 ) {
 9089:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9090:                                     '&nbsp;</td>';
 9091:                 } elsif ($colsleft == 1) {
 9092:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 9093:                 }
 9094:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 9095:                                '<table><tr>'.$targettable.'</tr></table><br />';
 9096:             }
 9097:             $hostherechecked{$sparetype} = '';
 9098:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 9099:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9100:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9101:                         $hostherechecked{$sparetype} = ' checked="checked"';
 9102:                         $hostherechecked{'no'} = '';
 9103:                     }
 9104:                 }
 9105:             }
 9106:         }
 9107:         if ($currcookies{$lonhost}) {
 9108:             %balcookiechecked = (
 9109:                                     yes => ' checked="checked"',
 9110:                                 );
 9111:         }
 9112:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 9113:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 9114:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 9115:         foreach my $sparetype (@sparestypes) {
 9116:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 9117:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 9118:                           '</i></label><br />';
 9119:         }
 9120:         $datatable .= &mt('Use balancer cookie').'<br />'.
 9121:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 9122:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 9123:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 9124:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 9125:                       '</div></td></tr>'.
 9126:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 9127:                                            $othertitle,$usertypes,$types,\%servers,
 9128:                                            \%currbalancer,$lonhost,
 9129:                                            $targets_div_style,$homedom_div_style,
 9130:                                            $css_class[$cssidx],$balnum,$islast);
 9131:         $$rowtotal += $rownum;
 9132:         $balnum ++;
 9133:     }
 9134:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 9135:     return $datatable;
 9136: }
 9137: 
 9138: sub get_loadbalancers_config {
 9139:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 9140:     return unless ((ref($servers) eq 'HASH') &&
 9141:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 9142:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 9143:                    (ref($currcookies) eq 'HASH'));
 9144:     if (keys(%{$existing}) > 0) {
 9145:         my $oldlonhost;
 9146:         foreach my $key (sort(keys(%{$existing}))) {
 9147:             if ($key eq 'lonhost') {
 9148:                 $oldlonhost = $existing->{'lonhost'};
 9149:                 $currbalancer->{$oldlonhost} = 1;
 9150:             } elsif ($key eq 'targets') {
 9151:                 if ($oldlonhost) {
 9152:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 9153:                 }
 9154:             } elsif ($key eq 'rules') {
 9155:                 if ($oldlonhost) {
 9156:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 9157:                 }
 9158:             } elsif (ref($existing->{$key}) eq 'HASH') {
 9159:                 $currbalancer->{$key} = 1;
 9160:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 9161:                 $currrules->{$key} = $existing->{$key}{'rules'};
 9162:                 if ($existing->{$key}{'cookie'}) {
 9163:                     $currcookies->{$key} = 1;
 9164:                 }
 9165:             }
 9166:         }
 9167:     } else {
 9168:         my ($balancerref,$targetsref) =
 9169:                 &Apache::lonnet::get_lonbalancer_config($servers);
 9170:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 9171:             foreach my $server (sort(keys(%{$balancerref}))) {
 9172:                 $currbalancer->{$server} = 1;
 9173:                 $currtargets->{$server} = $targetsref->{$server};
 9174:             }
 9175:         }
 9176:     }
 9177:     return;
 9178: }
 9179: 
 9180: sub loadbalancing_rules {
 9181:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 9182:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 9183:         $css_class,$balnum,$islast) = @_;
 9184:     my $output;
 9185:     my $num = 0;
 9186:     my ($alltypes,$othertypes,$titles) =
 9187:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 9188:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 9189:         foreach my $type (@{$alltypes}) {
 9190:             $num ++;
 9191:             my $current;
 9192:             if (ref($currrules) eq 'HASH') {
 9193:                 $current = $currrules->{$type};
 9194:             }
 9195:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9196:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 9197:                     $current = '';
 9198:                 }
 9199:             }
 9200:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 9201:                                              $servers,$currbalancer,$lonhost,$dom,
 9202:                                              $targets_div_style,$homedom_div_style,
 9203:                                              $css_class,$balnum,$num,$islast);
 9204:         }
 9205:     }
 9206:     return $output;
 9207: }
 9208: 
 9209: sub loadbalancing_titles {
 9210:     my ($dom,$intdom,$usertypes,$types) = @_;
 9211:     my %othertypes = (
 9212:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 9213:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 9214:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 9215:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 9216:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 9217:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 9218:                      );
 9219:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 9220:     my @available;
 9221:     if (ref($types) eq 'ARRAY') {
 9222:         @available = @{$types};
 9223:     }
 9224:     unless (grep(/^default$/,@available)) {
 9225:         push(@available,'default');
 9226:     }
 9227:     unshift(@alltypes,@available);
 9228:     my %titles;
 9229:     foreach my $type (@alltypes) {
 9230:         if ($type =~ /^_LC_/) {
 9231:             $titles{$type} = $othertypes{$type};
 9232:         } elsif ($type eq 'default') {
 9233:             $titles{$type} = &mt('All users from [_1]',$dom);
 9234:             if (ref($types) eq 'ARRAY') {
 9235:                 if (@{$types} > 0) {
 9236:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 9237:                 }
 9238:             }
 9239:         } elsif (ref($usertypes) eq 'HASH') {
 9240:             $titles{$type} = $usertypes->{$type};
 9241:         }
 9242:     }
 9243:     return (\@alltypes,\%othertypes,\%titles);
 9244: }
 9245: 
 9246: sub loadbalance_rule_row {
 9247:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 9248:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 9249:     my @rulenames;
 9250:     my %ruletitles = &offloadtype_text();
 9251:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 9252:         @rulenames = ('balancer','offloadedto','specific');
 9253:     } else {
 9254:         @rulenames = ('default','homeserver');
 9255:         if ($type eq '_LC_external') {
 9256:             push(@rulenames,'externalbalancer');
 9257:         } else {
 9258:             push(@rulenames,'specific');
 9259:         }
 9260:         push(@rulenames,'none');
 9261:     }
 9262:     my $style = $targets_div_style;
 9263:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9264:         $style = $homedom_div_style;
 9265:     }
 9266:     my $space;
 9267:     if ($islast && $num == 1) {
 9268:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 9269:     }
 9270:     my $output =
 9271:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 9272:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 9273:         '<td valaign="top">'.$space.
 9274:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 9275:     for (my $i=0; $i<@rulenames; $i++) {
 9276:         my $rule = $rulenames[$i];
 9277:         my ($checked,$extra);
 9278:         if ($rulenames[$i] eq 'default') {
 9279:             $rule = '';
 9280:         }
 9281:         if ($rulenames[$i] eq 'specific') {
 9282:             if (ref($servers) eq 'HASH') {
 9283:                 my $default;
 9284:                 if (($current ne '') && (exists($servers->{$current}))) {
 9285:                     $checked = ' checked="checked"';
 9286:                 }
 9287:                 unless ($checked) {
 9288:                     $default = ' selected="selected"';
 9289:                 }
 9290:                 $extra =
 9291:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9292:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9293:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 9294:                     '<option value=""'.$default.'></option>'."\n";
 9295:                 foreach my $server (sort(keys(%{$servers}))) {
 9296:                     if (ref($currbalancer) eq 'HASH') {
 9297:                         next if (exists($currbalancer->{$server}));
 9298:                     }
 9299:                     my $selected;
 9300:                     if ($server eq $current) {
 9301:                         $selected = ' selected="selected"';
 9302:                     }
 9303:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 9304:                 }
 9305:                 $extra .= '</select>';
 9306:             }
 9307:         } elsif ($rule eq $current) {
 9308:             $checked = ' checked="checked"';
 9309:         }
 9310:         $output .= '<span class="LC_nobreak"><label>'.
 9311:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 9312:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 9313:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 9314:                    ')"'.$checked.' />&nbsp;';
 9315:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 9316:             $output .= $ruletitles{'particular'};
 9317:         } else {
 9318:             $output .= $ruletitles{$rulenames[$i]};
 9319:         }
 9320:         $output .= '</label>'.$extra.'</span><br />'."\n";
 9321:     }
 9322:     $output .= '</div></td></tr>'."\n";
 9323:     return $output;
 9324: }
 9325: 
 9326: sub offloadtype_text {
 9327:     my %ruletitles = &Apache::lonlocal::texthash (
 9328:            'default'          => 'Offloads to default destinations',
 9329:            'homeserver'       => "Offloads to user's home server",
 9330:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 9331:            'specific'         => 'Offloads to specific server',
 9332:            'none'             => 'No offload',
 9333:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 9334:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 9335:            'particular'       => 'Session hosted (after re-auth) on server:',
 9336:     );
 9337:     return %ruletitles;
 9338: }
 9339: 
 9340: sub sparestype_titles {
 9341:     my %typestitles = &Apache::lonlocal::texthash (
 9342:                           'primary' => 'primary',
 9343:                           'default' => 'default',
 9344:                       );
 9345:     return %typestitles;
 9346: }
 9347: 
 9348: sub contact_titles {
 9349:     my %titles = &Apache::lonlocal::texthash (
 9350:                    'supportemail'    => 'Support E-mail address',
 9351:                    'adminemail'      => 'Default Server Admin E-mail address',
 9352:                    'errormail'       => 'Error reports to be e-mailed to',
 9353:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 9354:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 9355:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 9356:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 9357:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 9358:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 9359:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 9360:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 9361:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 9362:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 9363:                    'errorweights'    => 'Weights used to compute error count',
 9364:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 9365:                  );
 9366:     my %short_titles = &Apache::lonlocal::texthash (
 9367:                            adminemail   => 'Admin E-mail address',
 9368:                            supportemail => 'Support E-mail',
 9369:                        );   
 9370:     return (\%titles,\%short_titles);
 9371: }
 9372: 
 9373: sub helpform_fields {
 9374:     my %titles =  &Apache::lonlocal::texthash (
 9375:                        'username'   => 'Name',
 9376:                        'user'       => 'Username/domain',
 9377:                        'phone'      => 'Phone',
 9378:                        'cc'         => 'Cc e-mail',
 9379:                        'course'     => 'Course Details',
 9380:                        'section'    => 'Sections',
 9381:                        'screenshot' => 'File upload',
 9382:     );
 9383:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 9384:     my %possoptions = (
 9385:                         username     => ['yes','no','req'],
 9386:                         phone        => ['yes','no','req'],
 9387:                         user         => ['yes','no'],
 9388:                         cc           => ['yes','no'],
 9389:                         course       => ['yes','no'],
 9390:                         section      => ['yes','no'],
 9391:                         screenshot   => ['yes','no'],
 9392:                       );
 9393:     my %fieldoptions = &Apache::lonlocal::texthash (
 9394:                          'yes'  => 'Optional',
 9395:                          'req'  => 'Required',
 9396:                          'no'   => "Not shown",
 9397:     );
 9398:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 9399: }
 9400: 
 9401: sub tool_titles {
 9402:     my %titles = &Apache::lonlocal::texthash (
 9403:                      aboutme    => 'Personal web page',
 9404:                      blog       => 'Blog',
 9405:                      webdav     => 'WebDAV',
 9406:                      portfolio  => 'Portfolio',
 9407:                      timezone   => 'Can set time zone',
 9408:                      official   => 'Official courses (with institutional codes)',
 9409:                      unofficial => 'Unofficial courses',
 9410:                      community  => 'Communities',
 9411:                      textbook   => 'Textbook courses',
 9412:                      placement  => 'Placement tests',
 9413:                  );
 9414:     return %titles;
 9415: }
 9416: 
 9417: sub courserequest_titles {
 9418:     my %titles = &Apache::lonlocal::texthash (
 9419:                                    official   => 'Official',
 9420:                                    unofficial => 'Unofficial',
 9421:                                    community  => 'Communities',
 9422:                                    textbook   => 'Textbook',
 9423:                                    placement  => 'Placement tests',
 9424:                                    lti        => 'LTI Provider',
 9425:                                    norequest  => 'Not allowed',
 9426:                                    approval   => 'Approval by DC',
 9427:                                    validate   => 'With validation',
 9428:                                    autolimit  => 'Numerical limit',
 9429:                                    unlimited  => '(blank for unlimited)',
 9430:                  );
 9431:     return %titles;
 9432: }
 9433: 
 9434: sub authorrequest_titles {
 9435:     my %titles = &Apache::lonlocal::texthash (
 9436:                                    norequest  => 'Not allowed',
 9437:                                    approval   => 'Approval by Dom. Coord.',
 9438:                                    automatic  => 'Automatic approval',
 9439:                  );
 9440:     return %titles;
 9441: }
 9442: 
 9443: sub courserequest_conditions {
 9444:     my %conditions = &Apache::lonlocal::texthash (
 9445:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 9446:        validate   => '(Processing of request subject to institutional validation).',
 9447:                  );
 9448:     return %conditions;
 9449: }
 9450: 
 9451: 
 9452: sub print_usercreation {
 9453:     my ($position,$dom,$settings,$rowtotal) = @_;
 9454:     my $numinrow = 4;
 9455:     my $datatable;
 9456:     if ($position eq 'top') {
 9457:         $$rowtotal ++;
 9458:         my $rowcount = 0;
 9459:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 9460:         if (ref($rules) eq 'HASH') {
 9461:             if (keys(%{$rules}) > 0) {
 9462:                 $datatable .= &user_formats_row('username',$settings,$rules,
 9463:                                                 $ruleorder,$numinrow,$rowcount);
 9464:                 $$rowtotal ++;
 9465:                 $rowcount ++;
 9466:             }
 9467:         }
 9468:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 9469:         if (ref($idrules) eq 'HASH') {
 9470:             if (keys(%{$idrules}) > 0) {
 9471:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 9472:                                                 $idruleorder,$numinrow,$rowcount);
 9473:                 $$rowtotal ++;
 9474:                 $rowcount ++;
 9475:             }
 9476:         }
 9477:         if ($rowcount == 0) {
 9478:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 9479:             $$rowtotal ++;
 9480:             $rowcount ++;
 9481:         }
 9482:     } elsif ($position eq 'middle') {
 9483:         my @creators = ('author','course','requestcrs');
 9484:         my ($rules,$ruleorder) =
 9485:             &Apache::lonnet::inst_userrules($dom,'username');
 9486:         my %lt = &usercreation_types();
 9487:         my %checked;
 9488:         if (ref($settings) eq 'HASH') {
 9489:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 9490:                 foreach my $item (@creators) {
 9491:                     $checked{$item} = $settings->{'cancreate'}{$item};
 9492:                 }
 9493:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 9494:                 foreach my $item (@creators) {
 9495:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 9496:                         $checked{$item} = 'none';
 9497:                     }
 9498:                 }
 9499:             }
 9500:         }
 9501:         my $rownum = 0;
 9502:         foreach my $item (@creators) {
 9503:             $rownum ++;
 9504:             if ($checked{$item} eq '') {
 9505:                 $checked{$item} = 'any';
 9506:             }
 9507:             my $css_class;
 9508:             if ($rownum%2) {
 9509:                 $css_class = '';
 9510:             } else {
 9511:                 $css_class = ' class="LC_odd_row" ';
 9512:             }
 9513:             $datatable .= '<tr'.$css_class.'>'.
 9514:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 9515:                          '</span></td><td style="text-align: right">';
 9516:             my @options = ('any');
 9517:             if (ref($rules) eq 'HASH') {
 9518:                 if (keys(%{$rules}) > 0) {
 9519:                     push(@options,('official','unofficial'));
 9520:                 }
 9521:             }
 9522:             push(@options,'none');
 9523:             foreach my $option (@options) {
 9524:                 my $type = 'radio';
 9525:                 my $check = ' ';
 9526:                 if ($checked{$item} eq $option) {
 9527:                     $check = ' checked="checked" ';
 9528:                 } 
 9529:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9530:                               '<input type="'.$type.'" name="can_createuser_'.
 9531:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 9532:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 9533:             }
 9534:             $datatable .= '</td></tr>';
 9535:         }
 9536:     } else {
 9537:         my @contexts = ('author','course','domain');
 9538:         my @authtypes = ('int','krb4','krb5','loc','lti');
 9539:         my %checked;
 9540:         if (ref($settings) eq 'HASH') {
 9541:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 9542:                 foreach my $item (@contexts) {
 9543:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 9544:                         foreach my $auth (@authtypes) {
 9545:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 9546:                                 $checked{$item}{$auth} = ' checked="checked" ';
 9547:                             }
 9548:                         }
 9549:                     }
 9550:                 }
 9551:             }
 9552:         } else {
 9553:             foreach my $item (@contexts) {
 9554:                 foreach my $auth (@authtypes) {
 9555:                     $checked{$item}{$auth} = ' checked="checked" ';
 9556:                 }
 9557:             }
 9558:         }
 9559:         my %title = &context_names();
 9560:         my %authname = &authtype_names();
 9561:         my $rownum = 0;
 9562:         my $css_class; 
 9563:         foreach my $item (@contexts) {
 9564:             if ($rownum%2) {
 9565:                 $css_class = '';
 9566:             } else {
 9567:                 $css_class = ' class="LC_odd_row" ';
 9568:             }
 9569:             $datatable .=   '<tr'.$css_class.'>'.
 9570:                             '<td>'.$title{$item}.
 9571:                             '</td><td class="LC_left_item">'.
 9572:                             '<span class="LC_nobreak">';
 9573:             foreach my $auth (@authtypes) {
 9574:                 $datatable .= '<label>'. 
 9575:                               '<input type="checkbox" name="'.$item.'_auth" '.
 9576:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 9577:                               $authname{$auth}.'</label>&nbsp;';
 9578:             }
 9579:             $datatable .= '</span></td></tr>';
 9580:             $rownum ++;
 9581:         }
 9582:         $$rowtotal += $rownum;
 9583:     }
 9584:     return $datatable;
 9585: }
 9586: 
 9587: sub print_selfcreation {
 9588:     my ($position,$dom,$settings,$rowtotal) = @_;
 9589:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 9590:         $emaildomain,$datatable);
 9591:     if (ref($settings) eq 'HASH') {
 9592:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 9593:             $createsettings = $settings->{'cancreate'};
 9594:             if (ref($createsettings) eq 'HASH') {
 9595:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 9596:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 9597:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 9598:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 9599:                         @selfcreate = ('email','login','sso');
 9600:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 9601:                         @selfcreate = ($createsettings->{'selfcreate'});
 9602:                     }
 9603:                 }
 9604:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 9605:                     $processing = $createsettings->{'selfcreateprocessing'};
 9606:                 }
 9607:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 9608:                     $emailoptions = $createsettings->{'emailoptions'};
 9609:                 }
 9610:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 9611:                     $emailverified = $createsettings->{'emailverified'};
 9612:                 }
 9613:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 9614:                     $emaildomain = $createsettings->{'emaildomain'};
 9615:                 }
 9616:             }
 9617:         }
 9618:     }
 9619:     my %radiohash;
 9620:     my $numinrow = 4;
 9621:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 9622:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9623:     if ($position eq 'top') {
 9624:         my %choices = &Apache::lonlocal::texthash (
 9625:                                                       cancreate_login      => 'Institutional Login',
 9626:                                                       cancreate_sso        => 'Institutional Single Sign On',
 9627:                                                   );
 9628:         my @toggles = sort(keys(%choices));
 9629:         my %defaultchecked = (
 9630:                                'cancreate_login' => 'off',
 9631:                                'cancreate_sso'   => 'off',
 9632:                              );
 9633:         my ($onclick,$itemcount);
 9634:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9635:                                                      \%choices,$itemcount,$onclick);
 9636:         $$rowtotal += $itemcount;
 9637: 
 9638:         if (ref($usertypes) eq 'HASH') {
 9639:             if (keys(%{$usertypes}) > 0) {
 9640:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 9641:                                              $dom,$numinrow,$othertitle,
 9642:                                              'statustocreate',$rowtotal);
 9643:                 $$rowtotal ++;
 9644:             }
 9645:         }
 9646:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 9647:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9648:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 9649:         my $rem;
 9650:         my $numperrow = 2;
 9651:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 9652:         $datatable .= '<tr'.$css_class.'>'.
 9653:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 9654:                      '<td class="LC_left_item">'."\n".
 9655:                      '<table>'."\n";
 9656:         for (my $i=0; $i<@fields; $i++) {
 9657:             $rem = $i%($numperrow);
 9658:             if ($rem == 0) {
 9659:                 if ($i > 0) {
 9660:                     $datatable .= '</tr>';
 9661:                 }
 9662:                 $datatable .= '<tr>';
 9663:             }
 9664:             my $currval;
 9665:             if (ref($createsettings) eq 'HASH') {
 9666:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 9667:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 9668:                 }
 9669:             }
 9670:             $datatable .= '<td class="LC_left_item">'.
 9671:                           '<span class="LC_nobreak">'.
 9672:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 9673:                           'value="'.$currval.'" size="10" />&nbsp;'.
 9674:                           $fieldtitles{$fields[$i]}.'</span></td>';
 9675:         }
 9676:         my $colsleft = $numperrow - $rem;
 9677:         if ($colsleft > 1 ) {
 9678:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9679:                          '&nbsp;</td>';
 9680:         } elsif ($colsleft == 1) {
 9681:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 9682:         }
 9683:         $datatable .= '</tr></table></td></tr>';
 9684:         $$rowtotal ++;
 9685:     } elsif ($position eq 'middle') {
 9686:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 9687:         my @posstypes;
 9688:         if (ref($types) eq 'ARRAY') {
 9689:             @posstypes = @{$types};
 9690:         }
 9691:         unless (grep(/^default$/,@posstypes)) {
 9692:             push(@posstypes,'default');
 9693:         }
 9694:         my %usertypeshash;
 9695:         if (ref($usertypes) eq 'HASH') {
 9696:             %usertypeshash = %{$usertypes};
 9697:         }
 9698:         $usertypeshash{'default'} = $othertitle;
 9699:         foreach my $status (@posstypes) {
 9700:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 9701:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 9702:             $$rowtotal ++;
 9703:         }
 9704:     } else {
 9705:         my %choices = &Apache::lonlocal::texthash (
 9706:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 9707:                                                   );
 9708:         my @toggles = sort(keys(%choices));
 9709:         my %defaultchecked = (
 9710:                                'cancreate_email' => 'off',
 9711:                              );
 9712:         my $customclass = 'LC_selfcreate_email';
 9713:         my $classprefix = 'LC_canmodify_emailusername_';
 9714:         my $optionsprefix = 'LC_options_emailusername_';
 9715:         my $display = 'none';
 9716:         my $rowstyle = 'display:none';
 9717:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 9718:             $display = 'block';
 9719:             $rowstyle = 'display:table-row';
 9720:         }
 9721:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 9722:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9723:                                                      \%choices,$$rowtotal,$onclick);
 9724:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 9725:                                          $rowstyle);
 9726:         $$rowtotal ++;
 9727:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 9728:                                       $rowstyle);
 9729:         $$rowtotal ++;
 9730:         my (@ordered,@posstypes,%usertypeshash);
 9731:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 9732:         my ($emailrules,$emailruleorder) =
 9733:             &Apache::lonnet::inst_userrules($dom,'email');
 9734:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 9735:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 9736:         if (ref($types) eq 'ARRAY') {
 9737:             @posstypes = @{$types};
 9738:         }
 9739:         if (@posstypes) {
 9740:             unless (grep(/^default$/,@posstypes)) {
 9741:                 push(@posstypes,'default');
 9742:             }
 9743:             if (ref($usertypes) eq 'HASH') {
 9744:                 %usertypeshash = %{$usertypes};
 9745:             }
 9746:             my $currassign;
 9747:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 9748:                 $currassign = {
 9749:                                   selfassign => $domdefaults{'inststatusguest'},
 9750:                               };
 9751:                 @ordered = @{$domdefaults{'inststatusguest'}};
 9752:             } else {
 9753:                 $currassign = { selfassign => [] };
 9754:             }
 9755:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 9756:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 9757:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 9758:                                          $numinrow,$othertitle,'selfassign',
 9759:                                          $rowtotal,$onclicktypes,$customclass,
 9760:                                          $rowstyle);
 9761:             $$rowtotal ++;
 9762:             $usertypeshash{'default'} = $othertitle;
 9763:             foreach my $status (@posstypes) {
 9764:                 my $css_class;
 9765:                 if ($$rowtotal%2) {
 9766:                     $css_class = 'LC_odd_row ';
 9767:                 }
 9768:                 $css_class .= $customclass;
 9769:                 my $rowid = $optionsprefix.$status;
 9770:                 my $hidden = 1;
 9771:                 my $currstyle = 'display:none';
 9772:                 if (grep(/^\Q$status\E$/,@ordered)) {
 9773:                     $currstyle = $rowstyle;
 9774:                     $hidden = 0;
 9775:                 }
 9776:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9777:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 9778:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 9779:                 unless ($hidden) {
 9780:                     $$rowtotal ++;
 9781:                 }
 9782:             }
 9783:         } else {
 9784:             my $css_class;
 9785:             if ($$rowtotal%2) {
 9786:                 $css_class = 'LC_odd_row ';
 9787:             }
 9788:             $css_class .= $customclass;
 9789:             $usertypeshash{'default'} = $othertitle;
 9790:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9791:                                          $emailrules,$emailruleorder,$settings,'default','',
 9792:                                          $othertitle,$css_class,$rowstyle,$intdom);
 9793:             $$rowtotal ++;
 9794:         }
 9795:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 9796:         $numinrow = 1;
 9797:         if (@posstypes) {
 9798:             foreach my $status (@posstypes) {
 9799:                 my $rowid = $classprefix.$status;
 9800:                 my $datarowstyle = 'display:none';
 9801:                 if (grep(/^\Q$status\E$/,@ordered)) {
 9802:                     $datarowstyle = $rowstyle;
 9803:                 }
 9804:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 9805:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9806:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 9807:                 unless ($datarowstyle eq 'display:none') {
 9808:                     $$rowtotal ++;
 9809:                 }
 9810:             }
 9811:         } else {
 9812:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 9813:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9814:                                                    $infotitles,'',$customclass,$rowstyle);
 9815:         }
 9816:     }
 9817:     return $datatable;
 9818: }
 9819: 
 9820: sub selfcreate_javascript {
 9821:     return <<"ENDSCRIPT";
 9822: 
 9823: <script type="text/javascript">
 9824: // <![CDATA[
 9825: 
 9826: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 9827:     var x = document.getElementsByClassName(target);
 9828:     var insttypes = 0;
 9829:     var insttypeRegExp = new RegExp(prefix);
 9830:     if ((x.length != undefined) && (x.length > 0)) {
 9831:         if (form.elements[radio].length != undefined) {
 9832:             for (var i=0; i<form.elements[radio].length; i++) {
 9833:                 if (form.elements[radio][i].checked) {
 9834:                     if (form.elements[radio][i].value == 1) {
 9835:                         for (var j=0; j<x.length; j++) {
 9836:                             if (x[j].id == 'undefined') {
 9837:                                 x[j].style.display = 'table-row';
 9838:                             } else if (insttypeRegExp.test(x[j].id)) {
 9839:                                 insttypes ++;
 9840:                             } else {
 9841:                                 x[j].style.display = 'table-row';
 9842:                             }
 9843:                         }
 9844:                     } else {
 9845:                         for (var j=0; j<x.length; j++) {
 9846:                             x[j].style.display = 'none';
 9847:                         }
 9848:                     }
 9849:                     break;
 9850:                 }
 9851:             }
 9852:             if (insttypes > 0) {
 9853:                 toggleDataRow(form,checkbox,target,altprefix);
 9854:                 toggleDataRow(form,checkbox,target,prefix,1);
 9855:             }
 9856:         }
 9857:     }
 9858:     return;
 9859: }
 9860: 
 9861: function toggleDataRow(form,checkbox,target,prefix,docount) {
 9862:     if (form.elements[checkbox].length != undefined) {
 9863:         var count = 0;
 9864:         if (docount) {
 9865:             for (var i=0; i<form.elements[checkbox].length; i++) {
 9866:                 if (form.elements[checkbox][i].checked) {
 9867:                     count ++;
 9868:                 }
 9869:             }
 9870:         }
 9871:         for (var i=0; i<form.elements[checkbox].length; i++) {
 9872:             var type = form.elements[checkbox][i].value;
 9873:             if (document.getElementById(prefix+type)) {
 9874:                 if (form.elements[checkbox][i].checked) {
 9875:                     document.getElementById(prefix+type).style.display = 'table-row';
 9876:                     if (count % 2 == 1) {
 9877:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 9878:                     } else {
 9879:                         document.getElementById(prefix+type).className = target;
 9880:                     }
 9881:                     count ++;
 9882:                 } else {
 9883:                     document.getElementById(prefix+type).style.display = 'none';
 9884:                 }
 9885:             }
 9886:         }
 9887:     }
 9888:     return;
 9889: }
 9890: 
 9891: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 9892:     var caller = radio+'_'+status;
 9893:     if (form.elements[caller].length != undefined) {
 9894:         for (var i=0; i<form.elements[caller].length; i++) {
 9895:             if (form.elements[caller][i].checked) {
 9896:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 9897:                     var curr = form.elements[caller][i].value;
 9898:                     if (prefix) {
 9899:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 9900:                     }
 9901:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 9902:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 9903:                     if (curr == 'custom') {
 9904:                         if (prefix) {
 9905:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 9906:                         }
 9907:                     } else if (curr == 'inst') {
 9908:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 9909:                     } else if (curr == 'noninst') {
 9910:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 9911:                     }
 9912:                     break;
 9913:                 }
 9914:             }
 9915:         }
 9916:     }
 9917: }
 9918: 
 9919: // ]]>
 9920: </script>
 9921: 
 9922: ENDSCRIPT
 9923: }
 9924: 
 9925: sub noninst_users {
 9926:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 9927:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_;
 9928:     my $class = 'LC_left_item';
 9929:     if ($css_class) {
 9930:         $css_class = ' class="'.$css_class.'"';
 9931:     }
 9932:     if ($rowid) {
 9933:         $rowid = ' id="'.$rowid.'"';
 9934:     }
 9935:     if ($rowstyle) {
 9936:         $rowstyle = ' style="'.$rowstyle.'"';
 9937:     }
 9938:     my ($output,$description);
 9939:     if ($type eq 'default') {
 9940:         $description = &mt('Requests for: [_1]',$typetitle);
 9941:     } else {
 9942:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 9943:     }
 9944:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 9945:               "<td>$description</td>\n".
 9946:               '<td class="'.$class.'" colspan="2">'.
 9947:               '<table><tr>';
 9948:     my %headers = &Apache::lonlocal::texthash(
 9949:               approve  => 'Processing',
 9950:               email    => 'E-mail',
 9951:               username => 'Username',
 9952:     );
 9953:     foreach my $item ('approve','email','username') {
 9954:         $output .= '<th>'.$headers{$item}.'</th>';
 9955:     }
 9956:     $output .= '</tr><tr>';
 9957:     foreach my $item ('approve','email','username') {
 9958:         $output .= '<td style="vertical-align: top">';
 9959:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 9960:         if ($item eq 'approve') {
 9961:             %choices = &Apache::lonlocal::texthash (
 9962:                                                      automatic => 'Automatically approved',
 9963:                                                      approval  => 'Queued for approval',
 9964:                                                    );
 9965:             @options = ('automatic','approval');
 9966:             $hashref = $processing;
 9967:             $defoption = 'automatic';
 9968:             $name = 'cancreate_emailprocess_'.$type;
 9969:         } elsif ($item eq 'email') {
 9970:             %choices = &Apache::lonlocal::texthash (
 9971:                                                      any     => 'Any e-mail',
 9972:                                                      inst    => 'Institutional only',
 9973:                                                      noninst => 'Non-institutional only',
 9974:                                                      custom  => 'Custom restrictions',
 9975:                                                    );
 9976:             @options = ('any','inst','noninst');
 9977:             my $showcustom;
 9978:             if (ref($emailrules) eq 'HASH') {
 9979:                 if (keys(%{$emailrules}) > 0) {
 9980:                     push(@options,'custom');
 9981:                     $showcustom = 'cancreate_emailrule';
 9982:                     if (ref($settings) eq 'HASH') {
 9983:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 9984:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 9985:                                 if (exists($emailrules->{$rule})) {
 9986:                                     $hascustom ++;
 9987:                                 }
 9988:                             }
 9989:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 9990:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 9991:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 9992:                                     if (exists($emailrules->{$rule})) {
 9993:                                         $hascustom ++;
 9994:                                     }
 9995:                                 }
 9996:                             }
 9997:                         }
 9998:                     }
 9999:                 }
10000:             }
10001:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
10002:                                                      "'cancreate_emaildomain','$type'".');"';
10003:             $hashref = $emailoptions;
10004:             $defoption = 'any';
10005:             $name = 'cancreate_emailoptions_'.$type;
10006:         } elsif ($item eq 'username') {
10007:             %choices = &Apache::lonlocal::texthash (
10008:                                                      all    => 'Same as e-mail',
10009:                                                      first  => 'Omit @domain',
10010:                                                      free   => 'Free to choose',
10011:                                                    );
10012:             @options = ('all','first','free');
10013:             $hashref = $emailverified;
10014:             $defoption = 'all';
10015:             $name = 'cancreate_usernameoptions_'.$type;
10016:         }
10017:         foreach my $option (@options) {
10018:             my $checked;
10019:             if (ref($hashref) eq 'HASH') {
10020:                 if ($type eq '') {
10021:                     if (!exists($hashref->{'default'})) {
10022:                         if ($option eq $defoption) {
10023:                             $checked = ' checked="checked"';
10024:                         }
10025:                     } else {
10026:                         if ($hashref->{'default'} eq $option) {
10027:                             $checked = ' checked="checked"';
10028:                         }
10029:                     }
10030:                 } else {
10031:                     if (!exists($hashref->{$type})) {
10032:                         if ($option eq $defoption) {
10033:                             $checked = ' checked="checked"';
10034:                         }
10035:                     } else {
10036:                         if ($hashref->{$type} eq $option) {
10037:                             $checked = ' checked="checked"';
10038:                         }
10039:                     }
10040:                 }
10041:             } elsif (($item eq 'email') && ($hascustom)) {
10042:                 if ($option eq 'custom') {
10043:                     $checked = ' checked="checked"';
10044:                 }
10045:             } elsif ($option eq $defoption) {
10046:                 $checked = ' checked="checked"';
10047:             }
10048:             $output .= '<span class="LC_nobreak"><label>'.
10049:                        '<input type="radio" name="'.$name.'"'.
10050:                        $checked.' value="'.$option.'"'.$onclick.' />'.
10051:                        $choices{$option}.'</label></span><br />';
10052:             if ($item eq 'email') {
10053:                 if ($option eq 'custom') {
10054:                     my $id = 'cancreate_emailrule_'.$type;
10055:                     my $display = 'none';
10056:                     if ($checked) {
10057:                         $display = 'inline';
10058:                     }
10059:                     my $numinrow = 2;
10060:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
10061:                                '<legend>'.&mt('Disallow').'</legend><table>'.
10062:                                &user_formats_row('email',$settings,$emailrules,
10063:                                                  $emailruleorder,$numinrow,'',$type);
10064:                               '</table></fieldset>';
10065:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
10066:                     my %text = &Apache::lonlocal::texthash (
10067:                                                              inst    => 'must end:',
10068:                                                              noninst => 'cannot end:',
10069:                                                            );
10070:                     my $value;
10071:                     if (ref($emaildomain) eq 'HASH') {
10072:                         if (ref($emaildomain->{$type}) eq 'HASH') {
10073:                             $value = $emaildomain->{$type}->{$option};
10074:                         }
10075:                     }
10076:                     if ($value eq '') {
10077:                         $value = '@'.$intdom;
10078:                     }
10079:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
10080:                     my $display = 'none';
10081:                     if ($checked) {
10082:                         $display = 'inline';
10083:                     }
10084:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
10085:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
10086:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
10087:                                '</div>';
10088:                 }
10089:             }
10090:         }
10091:         $output .= '</td>'."\n";
10092:     }
10093:     $output .= "</tr></table></td></tr>\n";
10094:     return $output;
10095: }
10096: 
10097: sub captcha_choice {
10098:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
10099:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
10100:         $vertext,$currver);
10101:     my %lt = &captcha_phrases();
10102:     $keyentry = 'hidden';
10103:     my $colspan=2;
10104:     if ($context eq 'cancreate') {
10105:         $rowname = &mt('CAPTCHA validation');
10106:     } elsif ($context eq 'login') {
10107:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
10108:     } elsif ($context eq 'passwords') {
10109:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
10110:         $colspan=1;
10111:     }
10112:     if (ref($settings) eq 'HASH') {
10113:         if ($settings->{'captcha'}) {
10114:             $checked{$settings->{'captcha'}} = ' checked="checked"';
10115:         } else {
10116:             $checked{'original'} = ' checked="checked"';
10117:         }
10118:         if ($settings->{'captcha'} eq 'recaptcha') {
10119:             $pubtext = $lt{'pub'};
10120:             $privtext = $lt{'priv'};
10121:             $keyentry = 'text';
10122:             $vertext = $lt{'ver'};
10123:             $currver = $settings->{'recaptchaversion'};
10124:             if ($currver ne '2') {
10125:                 $currver = 1;
10126:             }
10127:         }
10128:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
10129:             $currpub = $settings->{'recaptchakeys'}{'public'};
10130:             $currpriv = $settings->{'recaptchakeys'}{'private'};
10131:         }
10132:     } else {
10133:         $checked{'original'} = ' checked="checked"';
10134:     }
10135:     my $css_class;
10136:     if ($itemcount%2) {
10137:         $css_class = 'LC_odd_row';
10138:     }
10139:     if ($customcss) {
10140:         $css_class .= " $customcss";
10141:     }
10142:     $css_class =~ s/^\s+//;
10143:     if ($css_class) {
10144:         $css_class = ' class="'.$css_class.'"';
10145:     }
10146:     if ($rowstyle) {
10147:         $css_class .= ' style="'.$rowstyle.'"';
10148:     }
10149:     my $output = '<tr'.$css_class.'>'.
10150:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
10151:                  '<table><tr><td>'."\n";
10152:     foreach my $option ('original','recaptcha','notused') {
10153:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
10154:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
10155:                    $lt{$option}.'</label></span>';
10156:         unless ($option eq 'notused') {
10157:             $output .= ('&nbsp;'x2)."\n";
10158:         }
10159:     }
10160: #
10161: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
10162: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
10163: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
10164: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
10165: #
10166:     $output .= '</td></tr>'."\n".
10167:                '<tr><td class="LC_zero_height">'."\n".
10168:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
10169:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
10170:                $currpub.'" size="40" /></span><br />'."\n".
10171:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
10172:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
10173:                $currpriv.'" size="40" /></span><br />'.
10174:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
10175:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
10176:                $currver.'" size="3" /></span><br />'.
10177:                '</td></tr></table>'."\n".
10178:                '</td></tr>';
10179:     return $output;
10180: }
10181: 
10182: sub user_formats_row {
10183:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
10184:     my $output;
10185:     my %text = (
10186:                    'username' => 'new usernames',
10187:                    'id'       => 'IDs',
10188:                );
10189:     unless (($type eq 'email') || ($type eq 'unamemap')) {
10190:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
10191:         $output = '<tr '.$css_class.'>'.
10192:                   '<td><span class="LC_nobreak">'.
10193:                   &mt("Format rules to check for $text{$type}: ").
10194:                   '</td><td class="LC_left_item" colspan="2"><table>';
10195:     }
10196:     my $rem;
10197:     if (ref($ruleorder) eq 'ARRAY') {
10198:         for (my $i=0; $i<@{$ruleorder}; $i++) {
10199:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
10200:                 my $rem = $i%($numinrow);
10201:                 if ($rem == 0) {
10202:                     if ($i > 0) {
10203:                         $output .= '</tr>';
10204:                     }
10205:                     $output .= '<tr>';
10206:                 }
10207:                 my $check = ' ';
10208:                 if (ref($settings) eq 'HASH') {
10209:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
10210:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
10211:                             $check = ' checked="checked" ';
10212:                         }
10213:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
10214:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
10215:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
10216:                                 $check = ' checked="checked" ';
10217:                             }
10218:                         }
10219:                     }
10220:                 }
10221:                 my $name = $type.'_rule';
10222:                 if ($type eq 'email') {
10223:                     $name .= '_'.$status;
10224:                 }
10225:                 $output .= '<td class="LC_left_item">'.
10226:                            '<span class="LC_nobreak"><label>'.
10227:                            '<input type="checkbox" name="'.$name.'" '.
10228:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
10229:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
10230:             }
10231:         }
10232:         $rem = @{$ruleorder}%($numinrow);
10233:     }
10234:     my $colsleft;
10235:     if ($rem) {
10236:         $colsleft = $numinrow - $rem;
10237:     }
10238:     if ($colsleft > 1 ) {
10239:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10240:                    '&nbsp;</td>';
10241:     } elsif ($colsleft == 1) {
10242:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10243:     }
10244:     $output .= '</tr>';
10245:     unless (($type eq 'email') || ($type eq 'unamemap')) {
10246:         $output .= '</table></td></tr>';
10247:     }
10248:     return $output;
10249: }
10250: 
10251: sub usercreation_types {
10252:     my %lt = &Apache::lonlocal::texthash (
10253:                     author     => 'When adding a co-author',
10254:                     course     => 'When adding a user to a course',
10255:                     requestcrs => 'When requesting a course',
10256:                     any        => 'Any',
10257:                     official   => 'Institutional only ',
10258:                     unofficial => 'Non-institutional only',
10259:                     none       => 'None',
10260:     );
10261:     return %lt;
10262: }
10263: 
10264: sub selfcreation_types {
10265:     my %lt = &Apache::lonlocal::texthash (
10266:                     selfcreate => 'User creates own account',
10267:                     any        => 'Any',
10268:                     official   => 'Institutional only ',
10269:                     unofficial => 'Non-institutional only',
10270:                     email      => 'E-mail address',
10271:                     login      => 'Institutional Login',
10272:                     sso        => 'SSO',
10273:              );
10274: }
10275: 
10276: sub authtype_names {
10277:     my %lt = &Apache::lonlocal::texthash(
10278:                       int    => 'Internal',
10279:                       krb4   => 'Kerberos 4',
10280:                       krb5   => 'Kerberos 5',
10281:                       loc    => 'Local',
10282:                       lti    => 'LTI',
10283:                   );
10284:     return %lt;
10285: }
10286: 
10287: sub context_names {
10288:     my %context_title = &Apache::lonlocal::texthash(
10289:        author => 'Creating users when an Author',
10290:        course => 'Creating users when in a course',
10291:        domain => 'Creating users when a Domain Coordinator',
10292:     );
10293:     return %context_title;
10294: }
10295: 
10296: sub print_usermodification {
10297:     my ($position,$dom,$settings,$rowtotal) = @_;
10298:     my $numinrow = 4;
10299:     my ($context,$datatable,$rowcount);
10300:     if ($position eq 'top') {
10301:         $rowcount = 0;
10302:         $context = 'author'; 
10303:         foreach my $role ('ca','aa') {
10304:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10305:                                                    $numinrow,$rowcount);
10306:             $$rowtotal ++;
10307:             $rowcount ++;
10308:         }
10309:     } elsif ($position eq 'bottom') {
10310:         $context = 'course';
10311:         $rowcount = 0;
10312:         foreach my $role ('st','ep','ta','in','cr') {
10313:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10314:                                                    $numinrow,$rowcount);
10315:             $$rowtotal ++;
10316:             $rowcount ++;
10317:         }
10318:     }
10319:     return $datatable;
10320: }
10321: 
10322: sub print_defaults {
10323:     my ($position,$dom,$settings,$rowtotal) = @_;
10324:     my $rownum = 0;
10325:     my ($datatable,$css_class,$titles);
10326:     unless ($position eq 'bottom') {
10327:         $titles = &defaults_titles($dom);
10328:     }
10329:     if ($position eq 'top') {
10330:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
10331:                      'datelocale_def','portal_def');
10332:         my %defaults;
10333:         if (ref($settings) eq 'HASH') {
10334:             %defaults = %{$settings};
10335:         } else {
10336:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10337:             foreach my $item (@items) {
10338:                 $defaults{$item} = $domdefaults{$item};
10339:             }
10340:         }
10341:         foreach my $item (@items) {
10342:             if ($rownum%2) {
10343:                 $css_class = '';
10344:             } else {
10345:                 $css_class = ' class="LC_odd_row" ';
10346:             }
10347:             $datatable .= '<tr'.$css_class.'>'.
10348:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
10349:                           '</span></td><td class="LC_right_item" colspan="3">';
10350:             if ($item eq 'auth_def') {
10351:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
10352:                 my %shortauth = (
10353:                                  internal => 'int',
10354:                                  krb4 => 'krb4',
10355:                                  krb5 => 'krb5',
10356:                                  localauth  => 'loc',
10357:                                  lti => 'lti',
10358:                                 );
10359:                 my %authnames = &authtype_names();
10360:                 foreach my $auth (@authtypes) {
10361:                     my $checked = ' ';
10362:                     if ($defaults{$item} eq $auth) {
10363:                         $checked = ' checked="checked" ';
10364:                     }
10365:                     $datatable .= '<label><input type="radio" name="'.$item.
10366:                                   '" value="'.$auth.'"'.$checked.'/>'.
10367:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
10368:                 }
10369:             } elsif ($item eq 'timezone_def') {
10370:                 my $includeempty = 1;
10371:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
10372:             } elsif ($item eq 'datelocale_def') {
10373:                 my $includeempty = 1;
10374:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
10375:             } elsif ($item eq 'lang_def') {
10376:                 my $includeempty = 1;
10377:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
10378:             } elsif ($item eq 'portal_def') {
10379:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
10380:                               $defaults{$item}.'" size="25" onkeyup="portalExtras(this);" />';
10381:                 my $portalsty = 'none';
10382:                 if ($defaults{$item}) {
10383:                     $portalsty = 'block';
10384:                 }
10385:                 foreach my $field ('email','web') {
10386:                     my $checkedoff = ' checked="checked"';
10387:                     my $checkedon;
10388:                     if ($defaults{$item.'_'.$field}) {
10389:                         $checkedon = $checkedoff;
10390:                         $checkedoff = '';
10391:                     }
10392:                     $datatable .= '<div id="'.$item.'_'.$field.'_div" style="display:'.$portalsty.'">'.
10393:                               '<span class="LC_nobreak">'.$titles->{$field}.'&nbsp;'.
10394:                               '<label><input type="radio" name="'.$item.'_'.$field.'" value="1"'.$checkedon.'/>'.&mt('Yes').'</label>'.
10395:                               ('&nbsp;'x2).
10396:                               '<label><input type="radio" name="'.$item.'_'.$field.'" value="0"'.$checkedoff.'/>'.&mt('No').'</label>'.
10397:                               '</div>';
10398:                 }
10399:             } else {
10400:                 $datatable .= '<input type="text" name="'.$item.'" value="'.$defaults{$item}.'" />';
10401:             }
10402:             $datatable .= '</td></tr>';
10403:             $rownum ++;
10404:         }
10405:     } elsif ($position eq 'middle') {
10406:         my %defaults;
10407:         if (ref($settings) eq 'HASH') {
10408:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10409:                 my $maxnum = @{$settings->{'inststatusorder'}};
10410:                 for (my $i=0; $i<$maxnum; $i++) {
10411:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
10412:                     my $item = $settings->{'inststatusorder'}->[$i];
10413:                     my $title = $settings->{'inststatustypes'}->{$item};
10414:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
10415:                     $datatable .= '<tr'.$css_class.'>'.
10416:                                   '<td><span class="LC_nobreak">'.
10417:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
10418:                     for (my $k=0; $k<=$maxnum; $k++) {
10419:                         my $vpos = $k+1;
10420:                         my $selstr;
10421:                         if ($k == $i) {
10422:                             $selstr = ' selected="selected" ';
10423:                         }
10424:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10425:                     }
10426:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
10427:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
10428:                                   &mt('delete').'</span></td>'.
10429:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
10430:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
10431:                                   '</span></td></tr>';
10432:                 }
10433:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
10434:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
10435:                 $datatable .= '<tr '.$css_class.'>'.
10436:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
10437:                 for (my $k=0; $k<=$maxnum; $k++) {
10438:                     my $vpos = $k+1;
10439:                     my $selstr;
10440:                     if ($k == $maxnum) {
10441:                         $selstr = ' selected="selected" ';
10442:                     }
10443:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10444:                 }
10445:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
10446:                               '<input type="text" size="10" name="addinststatus" value="" />'.
10447:                               '&nbsp;'.&mt('(new)').
10448:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
10449:                               &mt('Name displayed').':'.
10450:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
10451:                               '</tr>'."\n";
10452:                 $rownum ++;
10453:             }
10454:         }
10455:     } else {
10456:         my ($unamemaprules,$ruleorder) =
10457:             &Apache::lonnet::inst_userrules($dom,'unamemap');
10458:         $css_class = $rownum%2?' class="LC_odd_row"':'';
10459:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10460:             my $numinrow = 2;
10461:             $datatable .= '<tr'.$css_class.'><td>'.&mt('Available conversions').'</td><td><table>'.
10462:                           &user_formats_row('unamemap',$settings,$unamemaprules,
10463:                                             $ruleorder,$numinrow).
10464:                           '</table></td></tr>';
10465:         }
10466:         if ($datatable eq '') {
10467:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
10468:                           &mt('No rules set for domain in customized localenroll.pm').
10469:                           '</td></tr>';
10470:         }
10471:     }
10472:     $$rowtotal += $rownum;
10473:     return $datatable;
10474: }
10475: 
10476: sub get_languages_hash {
10477:     my %langchoices;
10478:     foreach my $id (&Apache::loncommon::languageids()) {
10479:         my $code = &Apache::loncommon::supportedlanguagecode($id);
10480:         if ($code ne '') {
10481:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
10482:         }
10483:     }
10484:     return %langchoices;
10485: }
10486: 
10487: sub defaults_titles {
10488:     my ($dom) = @_;
10489:     my %titles = &Apache::lonlocal::texthash (
10490:                    'auth_def'      => 'Default authentication type',
10491:                    'auth_arg_def'  => 'Default authentication argument',
10492:                    'lang_def'      => 'Default language',
10493:                    'timezone_def'  => 'Default timezone',
10494:                    'datelocale_def' => 'Default locale for dates',
10495:                    'portal_def'     => 'Portal/Default URL',
10496:                    'email'          => 'Email links use portal URL',
10497:                    'web'            => 'Public web links use portal URL',
10498:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
10499:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
10500:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
10501:                  );
10502:     if ($dom) {
10503:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
10504:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
10505:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
10506:         $protocol = 'http' if ($protocol ne 'https');
10507:         if ($uint_dom) {
10508:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
10509:                                          $uint_dom);
10510:         }
10511:     }
10512:     return (\%titles);
10513: }
10514: 
10515: sub print_scantron {
10516:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
10517:     if ($position eq 'top') {
10518:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
10519:     } else {
10520:         return &print_scantronconfig($dom,$settings,\$rowtotal);
10521:     }
10522: }
10523: 
10524: sub scantron_javascript {
10525:     return <<"ENDSCRIPT";
10526: 
10527: <script type="text/javascript">
10528: // <![CDATA[
10529: 
10530: function toggleScantron(form) {
10531:     var csvfieldset = new Array();
10532:     if (document.getElementById('scantroncsv_cols')) {
10533:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
10534:     }
10535:     if (document.getElementById('scantroncsv_options')) {
10536:         csvfieldset.push(document.getElementById('scantroncsv_options'));
10537:     }
10538:     if (csvfieldset.length) {
10539:         if (document.getElementById('scantronconfcsv')) {
10540:             var scantroncsv = document.getElementById('scantronconfcsv');
10541:             if (scantroncsv.checked) {
10542:                 for (var i=0; i<csvfieldset.length; i++) {
10543:                     csvfieldset[i].style.display = 'block';
10544:                 }
10545:             } else {
10546:                 for (var i=0; i<csvfieldset.length; i++) {
10547:                     csvfieldset[i].style.display = 'none';
10548:                 }
10549:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
10550:                 if (csvselects.length) {
10551:                     for (var j=0; j<csvselects.length; j++) {
10552:                         csvselects[j].selectedIndex = 0;
10553:                     }
10554:                 }
10555:             }
10556:         }
10557:     }
10558:     return;
10559: }
10560: // ]]>
10561: </script>
10562: 
10563: ENDSCRIPT
10564: 
10565: }
10566: 
10567: sub print_scantronformat {
10568:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
10569:     my $itemcount = 1;
10570:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
10571:         %confhash);
10572:     my $switchserver = &check_switchserver($dom,$confname);
10573:     my %lt = &Apache::lonlocal::texthash (
10574:                 default => 'Default bubblesheet format file error',
10575:                 custom  => 'Custom bubblesheet format file error',
10576:              );
10577:     my %scantronfiles = (
10578:         default => 'default.tab',
10579:         custom => 'custom.tab',
10580:     );
10581:     foreach my $key (keys(%scantronfiles)) {
10582:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
10583:                               .$scantronfiles{$key};
10584:     }
10585:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
10586:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
10587:         if (!$switchserver) {
10588:             my $servadm = $r->dir_config('lonAdmEMail');
10589:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
10590:             if ($configuserok eq 'ok') {
10591:                 if ($author_ok eq 'ok') {
10592:                     my %legacyfile = (
10593:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
10594:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
10595:                     );
10596:                     my %md5chk;
10597:                     foreach my $type (keys(%legacyfile)) {
10598:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
10599:                         chomp($md5chk{$type});
10600:                     }
10601:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
10602:                         foreach my $type (keys(%legacyfile)) {
10603:                             ($scantronurls{$type},my $error) =
10604:                                 &legacy_scantronformat($r,$dom,$confname,
10605:                                                  $type,$legacyfile{$type},
10606:                                                  $scantronurls{$type},
10607:                                                  $scantronfiles{$type});
10608:                             if ($error ne '') {
10609:                                 $error{$type} = $error;
10610:                             }
10611:                         }
10612:                         if (keys(%error) == 0) {
10613:                             $is_custom = 1;
10614:                             $confhash{'scantron'}{'scantronformat'} =
10615:                                 $scantronurls{'custom'};
10616:                             my $putresult =
10617:                                 &Apache::lonnet::put_dom('configuration',
10618:                                                          \%confhash,$dom);
10619:                             if ($putresult ne 'ok') {
10620:                                 $error{'custom'} =
10621:                                     '<span class="LC_error">'.
10622:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10623:                             }
10624:                         }
10625:                     } else {
10626:                         ($scantronurls{'default'},my $error) =
10627:                             &legacy_scantronformat($r,$dom,$confname,
10628:                                           'default',$legacyfile{'default'},
10629:                                           $scantronurls{'default'},
10630:                                           $scantronfiles{'default'});
10631:                         if ($error eq '') {
10632:                             $confhash{'scantron'}{'scantronformat'} = ''; 
10633:                             my $putresult =
10634:                                 &Apache::lonnet::put_dom('configuration',
10635:                                                          \%confhash,$dom);
10636:                             if ($putresult ne 'ok') {
10637:                                 $error{'default'} =
10638:                                     '<span class="LC_error">'.
10639:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10640:                             }
10641:                         } else {
10642:                             $error{'default'} = $error;
10643:                         }
10644:                     }
10645:                 }
10646:             }
10647:         } else {
10648:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
10649:         }
10650:     }
10651:     if (ref($settings) eq 'HASH') {
10652:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
10653:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
10654:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
10655:                 $scantronurl = '';
10656:             } else {
10657:                 $scantronurl = $settings->{'scantronformat'};
10658:             }
10659:             $is_custom = 1;
10660:         } else {
10661:             $scantronurl = $scantronurls{'default'};
10662:         }
10663:     } else {
10664:         if ($is_custom) {
10665:             $scantronurl = $scantronurls{'custom'};
10666:         } else {
10667:             $scantronurl = $scantronurls{'default'};
10668:         }
10669:     }
10670:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10671:     $datatable .= '<tr'.$css_class.'>';
10672:     if (!$is_custom) {
10673:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
10674:                       '<span class="LC_nobreak">';
10675:         if ($scantronurl) {
10676:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
10677:                                                          undef,undef,undef,undef,'background-color:#ffffff');
10678:         } else {
10679:             $datatable = &mt('File unavailable for display');
10680:         }
10681:         $datatable .= '</span></td>';
10682:         if (keys(%error) == 0) { 
10683:             $datatable .= '<td style="vertical-align: bottom">';
10684:             if (!$switchserver) {
10685:                 $datatable .= &mt('Upload:').'<br />';
10686:             }
10687:         } else {
10688:             my $errorstr;
10689:             foreach my $key (sort(keys(%error))) {
10690:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10691:             }
10692:             $datatable .= '<td>'.$errorstr;
10693:         }
10694:     } else {
10695:         if (keys(%error) > 0) {
10696:             my $errorstr;
10697:             foreach my $key (sort(keys(%error))) {
10698:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10699:             } 
10700:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
10701:         } elsif ($scantronurl) {
10702:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
10703:                                                        undef,undef,undef,undef,'background-color:#ffffff');
10704:             $datatable .= '<td><span class="LC_nobreak">'.
10705:                           $link.
10706:                           '<label><input type="checkbox" name="scantronformat_del"'.
10707:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
10708:                           '<td><span class="LC_nobreak">&nbsp;'.
10709:                           &mt('Replace:').'</span><br />';
10710:         }
10711:     }
10712:     if (keys(%error) == 0) {
10713:         if ($switchserver) {
10714:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
10715:         } else {
10716:             $datatable .='<span class="LC_nobreak">&nbsp;'.
10717:                          '<input type="file" name="scantronformat" /></span>';
10718:         }
10719:     }
10720:     $datatable .= '</td></tr>';
10721:     $$rowtotal ++;
10722:     return $datatable;
10723: }
10724: 
10725: sub legacy_scantronformat {
10726:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
10727:     my ($url,$error);
10728:     my @statinfo = &Apache::lonnet::stat_file($newurl);
10729:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
10730:         my $modified = [];
10731:         (my $result,$url) =
10732:             &Apache::lonconfigsettings::publishlogo($r,'copy',$legacyfile,$dom,$confname,
10733:                                                     'scantron','','',$newfile,$modified);
10734:         if ($result eq 'ok') {
10735:             &update_modify_urls($r,$modified);
10736:         } else {
10737:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
10738:         }
10739:     }
10740:     return ($url,$error);
10741: }
10742: 
10743: sub print_scantronconfig {
10744:     my ($dom,$settings,$rowtotal) = @_;
10745:     my $itemcount = 2;
10746:     my $is_checked = ' checked="checked"';
10747:     my %optionson = (
10748:                      hdr => ' checked="checked"',
10749:                      pad => ' checked="checked"',
10750:                      rem => ' checked="checked"',
10751:                     );
10752:     my %optionsoff = (
10753:                       hdr => '',
10754:                       pad => '',
10755:                       rem => '',
10756:                      );
10757:     my $currcsvsty = 'none';
10758:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
10759:     my @fields = &scantroncsv_fields();
10760:     my %titles = &scantronconfig_titles();
10761:     if (ref($settings) eq 'HASH') {
10762:         if (ref($settings->{config}) eq 'HASH') {
10763:             if ($settings->{config}->{dat}) {
10764:                 $checked{'dat'} = $is_checked;
10765:             }
10766:             if (ref($settings->{config}->{csv}) eq 'HASH') {
10767:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
10768:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
10769:                     if (keys(%csvfields) > 0) {
10770:                         $checked{'csv'} = $is_checked;
10771:                         $currcsvsty = 'block';
10772:                     }
10773:                 }
10774:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
10775:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
10776:                     foreach my $option (keys(%optionson)) {
10777:                         unless ($csvoptions{$option}) {
10778:                             $optionsoff{$option} = $optionson{$option};
10779:                             $optionson{$option} = '';
10780:                         }
10781:                     }
10782:                 }
10783:             }
10784:         } else {
10785:             $checked{'dat'} = $is_checked;
10786:         }
10787:     } else {
10788:         $checked{'dat'} = $is_checked;
10789:     }
10790:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
10791:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
10792:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
10793:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
10794:     foreach my $item ('dat','csv') {
10795:         my $id;
10796:         if ($item eq 'csv') {
10797:             $id = 'id="scantronconfcsv" ';
10798:         }
10799:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
10800:                       $titles{$item}.'</label>'.('&nbsp;'x3);
10801:         if ($item eq 'csv') {
10802:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
10803:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
10804:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
10805:             foreach my $col (@fields) {
10806:                 my $selnone;
10807:                 if ($csvfields{$col} eq '') {
10808:                     $selnone = ' selected="selected"';
10809:                 }
10810:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
10811:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
10812:                               '<option value=""'.$selnone.'></option>';
10813:                 for (my $i=0; $i<20; $i++) {
10814:                     my $shown = $i+1;
10815:                     my $sel;
10816:                     unless ($selnone) {
10817:                         if (exists($csvfields{$col})) {
10818:                             if ($csvfields{$col} == $i) {
10819:                                 $sel = ' selected="selected"';
10820:                             }
10821:                         }
10822:                     }
10823:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
10824:                 }
10825:                 $datatable .= '</select></td></tr>';
10826:            }
10827:            $datatable .= '</table></fieldset>'.
10828:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
10829:                          '<legend>'.&mt('CSV Options').'</legend>';
10830:            foreach my $option ('hdr','pad','rem') {
10831:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
10832:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
10833:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
10834:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
10835:            }
10836:            $datatable .= '</fieldset>';
10837:            $itemcount ++;
10838:         }
10839:     }
10840:     $datatable .= '</td></tr>';
10841:     $$rowtotal ++;
10842:     return $datatable;
10843: }
10844: 
10845: sub scantronconfig_titles {
10846:     return &Apache::lonlocal::texthash(
10847:                                           dat => 'Standard format (.dat)',
10848:                                           csv => 'Comma separated values (.csv)',
10849:                                           hdr => 'Remove first line in file (contains column titles)',
10850:                                           pad => 'Prepend 0s to PaperID',
10851:                                           rem => 'Remove leading spaces (except Question Response columns)',
10852:                                           CODE => 'CODE',
10853:                                           ID   => 'Student ID',
10854:                                           PaperID => 'Paper ID',
10855:                                           FirstName => 'First Name',
10856:                                           LastName => 'Last Name',
10857:                                           FirstQuestion => 'First Question Response',
10858:                                           Section => 'Section',
10859:     );
10860: }
10861: 
10862: sub scantroncsv_fields {
10863:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
10864: }
10865: 
10866: sub print_coursecategories {
10867:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
10868:     my $datatable;
10869:     if ($position eq 'top') {
10870:         my (%checked);
10871:         my @catitems = ('unauth','auth');
10872:         my @cattypes = ('std','domonly','codesrch','none');
10873:         $checked{'unauth'} = 'std';
10874:         $checked{'auth'} = 'std';
10875:         if (ref($settings) eq 'HASH') {
10876:             foreach my $type (@cattypes) {
10877:                 if ($type eq $settings->{'unauth'}) {
10878:                     $checked{'unauth'} = $type;
10879:                 }
10880:                 if ($type eq $settings->{'auth'}) {
10881:                     $checked{'auth'} = $type;
10882:                 }
10883:             }
10884:         }
10885:         my %lt = &Apache::lonlocal::texthash (
10886:                                                unauth   => 'Catalog type for unauthenticated users',
10887:                                                auth     => 'Catalog type for authenticated users',
10888:                                                none     => 'No catalog',
10889:                                                std      => 'Standard catalog',
10890:                                                domonly  => 'Domain-only catalog',
10891:                                                codesrch => "Code search form",
10892:                                              );
10893:        my $itemcount = 0;
10894:        foreach my $item (@catitems) {
10895:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
10896:            $datatable .= '<tr '.$css_class.'>'.
10897:                          '<td>'.$lt{$item}.'</td>'.
10898:                          '<td class="LC_right_item"><span class="LC_nobreak">';
10899:            foreach my $type (@cattypes) {
10900:                my $ischecked;
10901:                if ($checked{$item} eq $type) {
10902:                    $ischecked=' checked="checked"';
10903:                }
10904:                $datatable .= '<label>'.
10905:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
10906:                              ' />'.$lt{$type}.'</label>&nbsp;';
10907:            }
10908:            $datatable .= '</span></td></tr>';
10909:            $itemcount ++;
10910:         }
10911:         $$rowtotal += $itemcount;
10912:     } elsif ($position eq 'middle') {
10913:         my $toggle_cats_crs = ' ';
10914:         my $toggle_cats_dom = ' checked="checked" ';
10915:         my $can_cat_crs = ' ';
10916:         my $can_cat_dom = ' checked="checked" ';
10917:         my $toggle_catscomm_comm = ' ';
10918:         my $toggle_catscomm_dom = ' checked="checked" ';
10919:         my $can_catcomm_comm = ' ';
10920:         my $can_catcomm_dom = ' checked="checked" ';
10921:         my $toggle_catsplace_place = ' ';
10922:         my $toggle_catsplace_dom = ' checked="checked" ';
10923:         my $can_catplace_place = ' ';
10924:         my $can_catplace_dom = ' checked="checked" ';
10925: 
10926:         if (ref($settings) eq 'HASH') {
10927:             if ($settings->{'togglecats'} eq 'crs') {
10928:                 $toggle_cats_crs = $toggle_cats_dom;
10929:                 $toggle_cats_dom = ' ';
10930:             }
10931:             if ($settings->{'categorize'} eq 'crs') {
10932:                 $can_cat_crs = $can_cat_dom;
10933:                 $can_cat_dom = ' ';
10934:             }
10935:             if ($settings->{'togglecatscomm'} eq 'comm') {
10936:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
10937:                 $toggle_catscomm_dom = ' ';
10938:             }
10939:             if ($settings->{'categorizecomm'} eq 'comm') {
10940:                 $can_catcomm_comm = $can_catcomm_dom;
10941:                 $can_catcomm_dom = ' ';
10942:             }
10943:             if ($settings->{'togglecatsplace'} eq 'place') {
10944:                 $toggle_catsplace_place = $toggle_catsplace_dom;
10945:                 $toggle_catsplace_dom = ' ';
10946:             }
10947:             if ($settings->{'categorizeplace'} eq 'place') {
10948:                 $can_catplace_place = $can_catplace_dom;
10949:                 $can_catplace_dom = ' ';
10950:             }
10951:         }
10952:         my %title = &Apache::lonlocal::texthash (
10953:                      togglecats      => 'Show/Hide a course in catalog',
10954:                      togglecatscomm  => 'Show/Hide a community in catalog',
10955:                      togglecatsplace => 'Show/Hide a placement test in catalog',
10956:                      categorize      => 'Assign a category to a course',
10957:                      categorizecomm  => 'Assign a category to a community',
10958:                      categorizeplace => 'Assign a category to a placement test',
10959:                     );
10960:         my %level = &Apache::lonlocal::texthash (
10961:                      dom   => 'Set in Domain',
10962:                      crs   => 'Set in Course',
10963:                      comm  => 'Set in Community',
10964:                      place => 'Set in Placement Test',
10965:                     );
10966:         $datatable = '<tr class="LC_odd_row">'.
10967:                   '<td>'.$title{'togglecats'}.'</td>'.
10968:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10969:                   '<input type="radio" name="togglecats"'.
10970:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10971:                   '<label><input type="radio" name="togglecats"'.
10972:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
10973:                   '</tr><tr>'.
10974:                   '<td>'.$title{'categorize'}.'</td>'.
10975:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10976:                   '<label><input type="radio" name="categorize"'.
10977:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10978:                   '<label><input type="radio" name="categorize"'.
10979:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
10980:                   '</tr><tr class="LC_odd_row">'.
10981:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
10982:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10983:                   '<input type="radio" name="togglecatscomm"'.
10984:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10985:                   '<label><input type="radio" name="togglecatscomm"'.
10986:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
10987:                   '</tr><tr>'.
10988:                   '<td>'.$title{'categorizecomm'}.'</td>'.
10989:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10990:                   '<label><input type="radio" name="categorizecomm"'.
10991:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10992:                   '<label><input type="radio" name="categorizecomm"'.
10993:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
10994:                   '</tr><tr class="LC_odd_row">'.
10995:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
10996:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10997:                   '<input type="radio" name="togglecatsplace"'.
10998:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10999:                   '<label><input type="radio" name="togglecatscomm"'.
11000:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
11001:                   '</tr><tr>'.
11002:                   '<td>'.$title{'categorizeplace'}.'</td>'.
11003:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11004:                   '<label><input type="radio" name="categorizeplace"'.
11005:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11006:                   '<label><input type="radio" name="categorizeplace"'.
11007:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
11008:                   '</tr>';
11009:         $$rowtotal += 6;
11010:     } else {
11011:         my $css_class;
11012:         my $itemcount = 1;
11013:         my $cathash; 
11014:         if (ref($settings) eq 'HASH') {
11015:             $cathash = $settings->{'cats'};
11016:         }
11017:         if (ref($cathash) eq 'HASH') {
11018:             my (@cats,@trails,%allitems,%idx,@jsarray);
11019:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
11020:                                                    \%allitems,\%idx,\@jsarray);
11021:             my $maxdepth = scalar(@cats);
11022:             my $colattrib = '';
11023:             if ($maxdepth > 2) {
11024:                 $colattrib = ' colspan="2" ';
11025:             }
11026:             my @path;
11027:             if (@cats > 0) {
11028:                 if (ref($cats[0]) eq 'ARRAY') {
11029:                     my $numtop = @{$cats[0]};
11030:                     my $maxnum = $numtop;
11031:                     my %default_names = (
11032:                           instcode    => &mt('Official courses'),
11033:                           communities => &mt('Communities'),
11034:                           placement   => &mt('Placement Tests'),
11035:                     );
11036: 
11037:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
11038:                         ($cathash->{'instcode::0'} eq '') ||
11039:                         (!grep(/^communities$/,@{$cats[0]})) || 
11040:                         ($cathash->{'communities::0'} eq '') ||
11041:                         (!grep(/^placement$/,@{$cats[0]})) ||
11042:                         ($cathash->{'placement::0'} eq '')) {
11043:                         $maxnum ++;
11044:                     }
11045:                     my $lastidx;
11046:                     for (my $i=0; $i<$numtop; $i++) {
11047:                         my $parent = $cats[0][$i];
11048:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11049:                         my $item = &escape($parent).'::0';
11050:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
11051:                         $lastidx = $idx{$item};
11052:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11053:                                       .'<select name="'.$item.'"'.$chgstr.'>';
11054:                         for (my $k=0; $k<=$maxnum; $k++) {
11055:                             my $vpos = $k+1;
11056:                             my $selstr;
11057:                             if ($k == $i) {
11058:                                 $selstr = ' selected="selected" ';
11059:                             }
11060:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11061:                         }
11062:                         $datatable .= '</select></span></td><td>';
11063:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
11064:                             $datatable .=  '<span class="LC_nobreak">'
11065:                                            .$default_names{$parent}.'</span>';
11066:                             if ($parent eq 'instcode') {
11067:                                 $datatable .= '<br /><span class="LC_nobreak">('
11068:                                               .&mt('with institutional codes')
11069:                                               .')</span></td><td'.$colattrib.'>';
11070:                             } else {
11071:                                 $datatable .= '<table><tr><td>';
11072:                             }
11073:                             $datatable .= '<span class="LC_nobreak">'
11074:                                           .'<label><input type="radio" name="'
11075:                                           .$parent.'" value="1" checked="checked" />'
11076:                                           .&mt('Display').'</label>';
11077:                             if ($parent eq 'instcode') {
11078:                                 $datatable .= '&nbsp;';
11079:                             } else {
11080:                                 $datatable .= '</span></td></tr><tr><td>'
11081:                                               .'<span class="LC_nobreak">';
11082:                             }
11083:                             $datatable .= '<label><input type="radio" name="'
11084:                                           .$parent.'" value="0" />'
11085:                                           .&mt('Do not display').'</label></span>';
11086:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
11087:                                 $datatable .= '</td></tr></table>';
11088:                             }
11089:                             $datatable .= '</td>';
11090:                         } else {
11091:                             $datatable .= $parent
11092:                                           .'&nbsp;<span class="LC_nobreak"><label>'
11093:                                           .'<input type="checkbox" name="deletecategory" '
11094:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
11095:                         }
11096:                         my $depth = 1;
11097:                         push(@path,$parent);
11098:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
11099:                         pop(@path);
11100:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
11101:                         $itemcount ++;
11102:                     }
11103:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11104:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
11105:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
11106:                     for (my $k=0; $k<=$maxnum; $k++) {
11107:                         my $vpos = $k+1;
11108:                         my $selstr;
11109:                         if ($k == $numtop) {
11110:                             $selstr = ' selected="selected" ';
11111:                         }
11112:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11113:                     }
11114:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
11115:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
11116:                                   .'</tr>'."\n";
11117:                     $itemcount ++;
11118:                     foreach my $default ('instcode','communities','placement') {
11119:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
11120:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
11121:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
11122:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
11123:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
11124:                             for (my $k=0; $k<=$maxnum; $k++) {
11125:                                 my $vpos = $k+1;
11126:                                 my $selstr;
11127:                                 if ($k == $maxnum) {
11128:                                     $selstr = ' selected="selected" ';
11129:                                 }
11130:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11131:                             }
11132:                             $datatable .= '</select></span></td>'.
11133:                                           '<td><span class="LC_nobreak">'.
11134:                                           $default_names{$default}.'</span>';
11135:                             if ($default eq 'instcode') {
11136:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
11137:                                               .&mt('with institutional codes').')</span>';
11138:                             }
11139:                             $datatable .= '</td>'
11140:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
11141:                                           .&mt('Display').'</label>&nbsp;'
11142:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
11143:                                           .&mt('Do not display').'</label></span></td></tr>';
11144:                         }
11145:                     }
11146:                 }
11147:             } else {
11148:                 $datatable .= &initialize_categories($itemcount);
11149:             }
11150:         } else {
11151:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
11152:                           .&initialize_categories($itemcount);
11153:         }
11154:         $$rowtotal += $itemcount;
11155:     }
11156:     return $datatable;
11157: }
11158: 
11159: sub print_serverstatuses {
11160:     my ($dom,$settings,$rowtotal) = @_;
11161:     my $datatable;
11162:     my @pages = &serverstatus_pages();
11163:     my (%namedaccess,%machineaccess);
11164:     foreach my $type (@pages) {
11165:         $namedaccess{$type} = '';
11166:         $machineaccess{$type}= '';
11167:     }
11168:     if (ref($settings) eq 'HASH') {
11169:         foreach my $type (@pages) {
11170:             if (exists($settings->{$type})) {
11171:                 if (ref($settings->{$type}) eq 'HASH') {
11172:                     foreach my $key (keys(%{$settings->{$type}})) {
11173:                         if ($key eq 'namedusers') {
11174:                             $namedaccess{$type} = $settings->{$type}->{$key};
11175:                         } elsif ($key eq 'machines') {
11176:                             $machineaccess{$type} = $settings->{$type}->{$key};
11177:                         }
11178:                     }
11179:                 }
11180:             }
11181:         }
11182:     }
11183:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11184:     my $rownum = 0;
11185:     my $css_class;
11186:     foreach my $type (@pages) {
11187:         $rownum ++;
11188:         $css_class = $rownum%2?' class="LC_odd_row"':'';
11189:         $datatable .= '<tr'.$css_class.'>'.
11190:                       '<td><span class="LC_nobreak">'.
11191:                       $titles->{$type}.'</span></td>'.
11192:                       '<td class="LC_left_item">'.
11193:                       '<input type="text" name="'.$type.'_namedusers" '.
11194:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
11195:                       '<td class="LC_right_item">'.
11196:                       '<span class="LC_nobreak">'.
11197:                       '<input type="text" name="'.$type.'_machines" '.
11198:                       'value="'.$machineaccess{$type}.'" size="10" />'.
11199:                       '</span></td></tr>'."\n";
11200:     }
11201:     $$rowtotal += $rownum;
11202:     return $datatable;
11203: }
11204: 
11205: sub serverstatus_pages {
11206:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
11207:             'checksums','clusterstatus','certstatus','metadata_keywords',
11208:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
11209:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
11210: }
11211: 
11212: sub defaults_javascript {
11213:     my ($settings) = @_;
11214:     return unless (ref($settings) eq 'HASH');
11215:     my $portal_js = <<"ENDPORTAL";
11216: 
11217: function portalExtras(caller) {
11218:     var x = caller.value;
11219:     var y = new Array('email','web');
11220:     for (var i=0; i<y.length; i++) {
11221:         if (document.getElementById('portal_def_'+y[i]+'_div')) {
11222:             var z = document.getElementById('portal_def_'+y[i]+'_div');
11223:             if (x.length > 0) {
11224:                 z.style.display = 'block';
11225:             } else {
11226:                 z.style.display = 'none';
11227:             }
11228:         }
11229:     }
11230: }
11231: ENDPORTAL
11232:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
11233:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
11234:         if ($maxnum eq '') {
11235:             $maxnum = 0;
11236:         }
11237:         $maxnum ++;
11238:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
11239:         return <<"ENDSCRIPT";
11240: <script type="text/javascript">
11241: // <![CDATA[
11242: function reorderTypes(form,caller) {
11243:     var changedVal;
11244: $jstext 
11245:     var newpos = 'addinststatus_pos';
11246:     var current = new Array;
11247:     var maxh = $maxnum;
11248:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11249:     var oldVal;
11250:     if (caller == newpos) {
11251:         changedVal = newitemVal;
11252:     } else {
11253:         var curritem = 'inststatus_pos_'+caller;
11254:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
11255:         current[newitemVal] = newpos;
11256:     }
11257:     for (var i=0; i<inststatuses.length; i++) {
11258:         if (inststatuses[i] != caller) {
11259:             var elementName = 'inststatus_pos_'+inststatuses[i];
11260:             if (form.elements[elementName]) {
11261:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11262:                 current[currVal] = elementName;
11263:             }
11264:         }
11265:     }
11266:     for (var j=0; j<maxh; j++) {
11267:         if (current[j] == undefined) {
11268:             oldVal = j;
11269:         }
11270:     }
11271:     if (oldVal < changedVal) {
11272:         for (var k=oldVal+1; k<=changedVal ; k++) {
11273:            var elementName = current[k];
11274:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11275:         }
11276:     } else {
11277:         for (var k=changedVal; k<oldVal; k++) {
11278:             var elementName = current[k];
11279:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11280:         }
11281:     }
11282:     return;
11283: }
11284: 
11285: $portal_js
11286: 
11287: // ]]>
11288: </script>
11289: 
11290: ENDSCRIPT
11291:     } else {
11292: return <<"ENDSCRIPT";
11293: <script type="text/javascript">
11294: // <![CDATA[
11295: $portal_js
11296: // ]]>
11297: </script>
11298: 
11299: ENDSCRIPT
11300:     }
11301:     return;
11302: }
11303: 
11304: sub passwords_javascript {
11305:     my ($prefix) = @_;
11306:     my %intalert;
11307:     if ($prefix eq 'passwords') {
11308:         %intalert = &Apache::lonlocal::texthash (
11309:             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.',
11310:             authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
11311:             passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
11312:             passmax => 'Warning: maximum password length must be a positive integer (or blank).',
11313:             passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
11314:             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
11315:         );
11316:     } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
11317:         %intalert = &Apache::lonlocal::texthash (
11318:             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
11319:             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
11320:         );
11321:     }
11322:     &js_escape(\%intalert);
11323:     my $defmin = $Apache::lonnet::passwdmin;
11324:     my $intauthjs;
11325:     if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
11326: 
11327: function warnIntAuth(field) {
11328:     if (field.name == 'intauth_check') {
11329:         if (field.value == '2') {
11330:             alert('$intalert{authcheck}');
11331:         }
11332:     }
11333:     if (field.name == 'intauth_cost') {
11334:         field.value.replace(/\s/g,'');
11335:         if (field.value != '') {
11336:             var regexdigit=/^\\d+\$/;
11337:             if (!regexdigit.test(field.value)) {
11338:                 alert('$intalert{authcost}');
11339:             }
11340:         }
11341:     }
11342:     return;
11343: }
11344: 
11345: ENDSCRIPT
11346: 
11347:      }
11348: 
11349:      $intauthjs .= <<"ENDSCRIPT";
11350: 
11351: function warnInt$prefix(field) {
11352:     field.value.replace(/^\s+/,'');
11353:     field.value.replace(/\s+\$/,'');
11354:     var regexdigit=/^\\d+\$/;
11355:     if (field.name == '${prefix}_min') {
11356:         if (field.value == '') {
11357:             alert('$intalert{passmin}');
11358:             field.value = '$defmin';
11359:         } else {
11360:             if (!regexdigit.test(field.value)) {
11361:                 alert('$intalert{passmin}');
11362:                 field.value = '$defmin';
11363:             }
11364:             var minval = parseInt(field.value,10);
11365:             if (minval < $defmin) {
11366:                 alert('$intalert{passmin}');
11367:                 field.value = '$defmin';
11368:             }
11369:         }
11370:     } else {
11371:         if (field.value == '0') {
11372:             field.value = '';
11373:         }
11374:         if (field.value != '') {
11375:             if (field.name == '${prefix}_expire') {
11376:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
11377:                 if (!regexpposnum.test(field.value)) {
11378:                     alert('$intalert{passexp}');
11379:                     field.value = '';
11380:                 } else {
11381:                     var expval = parseFloat(field.value);
11382:                     if (expval == 0) {
11383:                         alert('$intalert{passexp}');
11384:                         field.value = '';
11385:                     }
11386:                 }
11387:             } else {
11388:                 if (!regexdigit.test(field.value)) {
11389:                     if (field.name == '${prefix}_max') {
11390:                         alert('$intalert{passmax}');
11391:                     } else {
11392:                         if (field.name == '${prefix}_numsaved') {
11393:                             alert('$intalert{passnum}');
11394:                         }
11395:                     }
11396:                     field.value = '';
11397:                 }
11398:             }
11399:         }
11400:     }
11401:     return;
11402: }
11403: 
11404: ENDSCRIPT
11405:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
11406: }
11407: 
11408: sub coursecategories_javascript {
11409:     my ($settings) = @_;
11410:     my ($output,$jstext,$cathash);
11411:     if (ref($settings) eq 'HASH') {
11412:         $cathash = $settings->{'cats'};
11413:     }
11414:     if (ref($cathash) eq 'HASH') {
11415:         my (@cats,@jsarray,%idx);
11416:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
11417:         if (@jsarray > 0) {
11418:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
11419:             for (my $i=0; $i<@jsarray; $i++) {
11420:                 if (ref($jsarray[$i]) eq 'ARRAY') {
11421:                     my $catstr = join('","',@{$jsarray[$i]});
11422:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
11423:                 }
11424:             }
11425:         }
11426:     } else {
11427:         $jstext  = '    var categories = Array(1);'."\n".
11428:                    '    categories[0] = Array("instcode_pos");'."\n"; 
11429:     }
11430:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
11431:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
11432:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
11433:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
11434:     &js_escape(\$instcode_reserved);
11435:     &js_escape(\$communities_reserved);
11436:     &js_escape(\$placement_reserved);
11437:     &js_escape(\$choose_again);
11438:     $output = <<"ENDSCRIPT";
11439: <script type="text/javascript">
11440: // <![CDATA[
11441: function reorderCats(form,parent,item,idx) {
11442:     var changedVal;
11443: $jstext
11444:     var newpos = 'addcategory_pos';
11445:     if (parent == '') {
11446:         var has_instcode = 0;
11447:         var maxtop = categories[idx].length;
11448:         for (var j=0; j<maxtop; j++) {
11449:             if (categories[idx][j] == 'instcode::0') {
11450:                 has_instcode == 1;
11451:             }
11452:         }
11453:         if (has_instcode == 0) {
11454:             categories[idx][maxtop] = 'instcode_pos';
11455:         }
11456:     } else {
11457:         newpos += '_'+parent;
11458:     }
11459:     var maxh = 1 + categories[idx].length;
11460:     var current = new Array;
11461:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11462:     if (item == newpos) {
11463:         changedVal = newitemVal;
11464:     } else {
11465:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
11466:         current[newitemVal] = newpos;
11467:     }
11468:     for (var i=0; i<categories[idx].length; i++) {
11469:         var elementName = categories[idx][i];
11470:         if (elementName != item) {
11471:             if (form.elements[elementName]) {
11472:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11473:                 current[currVal] = elementName;
11474:             }
11475:         }
11476:     }
11477:     var oldVal;
11478:     for (var j=0; j<maxh; j++) {
11479:         if (current[j] == undefined) {
11480:             oldVal = j;
11481:         }
11482:     }
11483:     if (oldVal < changedVal) {
11484:         for (var k=oldVal+1; k<=changedVal ; k++) {
11485:            var elementName = current[k];
11486:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11487:         }
11488:     } else {
11489:         for (var k=changedVal; k<oldVal; k++) {
11490:             var elementName = current[k];
11491:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11492:         }
11493:     }
11494:     return;
11495: }
11496: 
11497: function categoryCheck(form) {
11498:     if (form.elements['addcategory_name'].value == 'instcode') {
11499:         alert('$instcode_reserved\\n$choose_again');
11500:         return false;
11501:     }
11502:     if (form.elements['addcategory_name'].value == 'communities') {
11503:         alert('$communities_reserved\\n$choose_again');
11504:         return false;
11505:     }
11506:     if (form.elements['addcategory_name'].value == 'placement') {
11507:         alert('$placement_reserved\\n$choose_again');
11508:         return false;
11509:     }
11510:     return true;
11511: }
11512: 
11513: // ]]>
11514: </script>
11515: 
11516: ENDSCRIPT
11517:     return $output;
11518: }
11519: 
11520: sub initialize_categories {
11521:     my ($itemcount) = @_;
11522:     my ($datatable,$css_class,$chgstr);
11523:     my %default_names = &Apache::lonlocal::texthash (
11524:                       instcode    => 'Official courses (with institutional codes)',
11525:                       communities => 'Communities',
11526:                       placement   => 'Placement Tests',
11527:                         );
11528:     my %selnum = (
11529:                    instcode    => '0',
11530:                    communities => '1',
11531:                    placement   => '2',
11532:                  );
11533:     my %selected;
11534:     foreach my $default ('instcode','communities','placement') {
11535:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11536:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
11537:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
11538:         $selected{$selnum{$default}} = ' selected="selected"';
11539:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11540:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
11541:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
11542:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
11543:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
11544:                      .'<option value="3">4</option></select>&nbsp;'
11545:                      .$default_names{$default}
11546:                      .'</span></td><td><span class="LC_nobreak">'
11547:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
11548:                      .&mt('Display').'</label>&nbsp;<label>'
11549:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
11550:                  .'</label></span></td></tr>';
11551:         $itemcount ++;
11552:     }
11553:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11554:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
11555:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11556:                   .'<select name="addcategory_pos"'.$chgstr.'>'
11557:                   .'<option value="0">1</option>'
11558:                   .'<option value="1">2</option>'
11559:                   .'<option value="2">3</option>'
11560:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
11561:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
11562:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
11563:                   .'</td></tr>';
11564:     return $datatable;
11565: }
11566: 
11567: sub build_category_rows {
11568:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
11569:     my ($text,$name,$item,$chgstr);
11570:     if (ref($cats) eq 'ARRAY') {
11571:         my $maxdepth = scalar(@{$cats});
11572:         if (ref($cats->[$depth]) eq 'HASH') {
11573:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
11574:                 my $numchildren = @{$cats->[$depth]{$parent}};
11575:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
11576:                 $text .= '<td><table class="LC_data_table">';
11577:                 my ($idxnum,$parent_name,$parent_item);
11578:                 my $higher = $depth - 1;
11579:                 if ($higher == 0) {
11580:                     $parent_name = &escape($parent).'::'.$higher;
11581:                 } else {
11582:                     if (ref($path) eq 'ARRAY') {
11583:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11584:                     }
11585:                 }
11586:                 $parent_item = 'addcategory_pos_'.$parent_name;
11587:                 for (my $j=0; $j<=$numchildren; $j++) {
11588:                     if ($j < $numchildren) {
11589:                         $name = $cats->[$depth]{$parent}[$j];
11590:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
11591:                         $idxnum = $idx->{$item};
11592:                     } else {
11593:                         $name = $parent_name;
11594:                         $item = $parent_item;
11595:                     }
11596:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
11597:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
11598:                     for (my $i=0; $i<=$numchildren; $i++) {
11599:                         my $vpos = $i+1;
11600:                         my $selstr;
11601:                         if ($j == $i) {
11602:                             $selstr = ' selected="selected" ';
11603:                         }
11604:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
11605:                     }
11606:                     $text .= '</select>&nbsp;';
11607:                     if ($j < $numchildren) {
11608:                         my $deeper = $depth+1;
11609:                         $text .= $name.'&nbsp;'
11610:                                  .'<label><input type="checkbox" name="deletecategory" value="'
11611:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
11612:                         if(ref($path) eq 'ARRAY') {
11613:                             push(@{$path},$name);
11614:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
11615:                             pop(@{$path});
11616:                         }
11617:                     } else {
11618:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
11619:                         if ($j == $numchildren) {
11620:                             $text .= $name;
11621:                         } else {
11622:                             $text .= $item;
11623:                         }
11624:                         $text .= '" value="" />';
11625:                     }
11626:                     $text .= '</td></tr>';
11627:                 }
11628:                 $text .= '</table></td>';
11629:             } else {
11630:                 my $higher = $depth-1;
11631:                 if ($higher == 0) {
11632:                     $name = &escape($parent).'::'.$higher;
11633:                 } else {
11634:                     if (ref($path) eq 'ARRAY') {
11635:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11636:                     }
11637:                 }
11638:                 my $colspan;
11639:                 if ($parent ne 'instcode') {
11640:                     $colspan = $maxdepth - $depth - 1;
11641:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
11642:                 }
11643:             }
11644:         }
11645:     }
11646:     return $text;
11647: }
11648: 
11649: sub modifiable_userdata_row {
11650:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
11651:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
11652:     my ($role,$rolename,$statustype);
11653:     $role = $item;
11654:     if ($context eq 'cancreate') {
11655:         if ($item =~ /^(emailusername)_(.+)$/) {
11656:             $role = $1;
11657:             $statustype = $2;
11658:             if (ref($usertypes) eq 'HASH') {
11659:                 if ($usertypes->{$statustype}) {
11660:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
11661:                 } else {
11662:                     $rolename = &mt('Data provided by user');
11663:                 }
11664:             }
11665:         }
11666:     } elsif ($context eq 'selfcreate') {
11667:         if (ref($usertypes) eq 'HASH') {
11668:             $rolename = $usertypes->{$role};
11669:         } else {
11670:             $rolename = $role;
11671:         }
11672:     } elsif ($context eq 'lti') {
11673:         $rolename = &mt('Institutional data used (if available)');
11674:     } elsif ($context eq 'privacy') {
11675:         $rolename = $itemdesc;
11676:     } else {
11677:         if ($role eq 'cr') {
11678:             $rolename = &mt('Custom role');
11679:         } else {
11680:             $rolename = &Apache::lonnet::plaintext($role);
11681:         }
11682:     }
11683:     my (@fields,%fieldtitles);
11684:     if (ref($fieldsref) eq 'ARRAY') {
11685:         @fields = @{$fieldsref};
11686:     } else {
11687:         @fields = ('lastname','firstname','middlename','generation',
11688:                    'permanentemail','id');
11689:     }
11690:     if ((ref($titlesref) eq 'HASH')) {
11691:         %fieldtitles = %{$titlesref};
11692:     } else {
11693:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11694:     }
11695:     my $output;
11696:     my $css_class;
11697:     if ($rowcount%2) {
11698:         $css_class = 'LC_odd_row';
11699:     }
11700:     if ($customcss) {
11701:         $css_class .= " $customcss";
11702:     }
11703:     $css_class =~ s/^\s+//;
11704:     if ($css_class) {
11705:         $css_class = ' class="'.$css_class.'"';
11706:     }
11707:     if ($rowstyle) {
11708:         $css_class .= ' style="'.$rowstyle.'"';
11709:     }
11710:     if ($rowid) {
11711:         $rowid = ' id="'.$rowid.'"';
11712:     }
11713:     $output = '<tr '.$css_class.$rowid.'>'.
11714:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
11715:               '<td class="LC_left_item" colspan="2"><table>';
11716:     my $rem;
11717:     my %checks;
11718:     my %current;
11719:     if (ref($settings) eq 'HASH') {
11720:         my $hashref;
11721:         if ($context eq 'lti') {
11722:             if (ref($settings) eq 'HASH') {
11723:                 $hashref = $settings->{'instdata'};
11724:             }
11725:         } elsif ($context eq 'privacy') {
11726:             my ($key,$inner) = split(/_/,$role);
11727:             if (ref($settings) eq 'HASH') {
11728:                 if (ref($settings->{$key}) eq 'HASH') {
11729:                     $hashref = $settings->{$key}->{$inner};
11730:                 }
11731:             }
11732:         } elsif (ref($settings->{$context}) eq 'HASH') {
11733:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
11734:                 $hashref = $settings->{'lti_instdata'};
11735:             }
11736:             if ($role eq 'emailusername') {
11737:                 if ($statustype) {
11738:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
11739:                         $hashref = $settings->{$context}->{$role}->{$statustype};
11740:                     }
11741:                 }
11742:             }
11743:         }
11744:         if (ref($hashref) eq 'HASH') {
11745:             foreach my $field (@fields) {
11746:                 if ($hashref->{$field}) {
11747:                     if ($role eq 'emailusername') {
11748:                         $checks{$field} = $hashref->{$field};
11749:                     } else {
11750:                         $checks{$field} = ' checked="checked" ';
11751:                     }
11752:                 }
11753:             }
11754:         }
11755:     }
11756:     my $total = scalar(@fields);
11757:     for (my $i=0; $i<$total; $i++) {
11758:         $rem = $i%($numinrow);
11759:         if ($rem == 0) {
11760:             if ($i > 0) {
11761:                 $output .= '</tr>';
11762:             }
11763:             $output .= '<tr>';
11764:         }
11765:         my $check = ' ';
11766:         unless ($role eq 'emailusername') {
11767:             if (exists($checks{$fields[$i]})) {
11768:                 $check = $checks{$fields[$i]};
11769:             } elsif ($context eq 'privacy') {
11770:                 if ($role =~ /^priv_(domain|course)$/) {
11771:                     if (ref($settings) ne 'HASH') {
11772:                         $check = ' checked="checked" ';
11773:                     }
11774:                 } elsif ($role =~ /^priv_(author|community)$/) {
11775:                     if (ref($settings) ne 'HASH') {
11776:                         unless ($fields[$i] eq 'id') {
11777:                             $check = ' checked="checked" ';
11778:                         }
11779:                     }
11780:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
11781:                     if (ref($settings) ne 'HASH') {
11782:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
11783:                             $check = ' checked="checked" ';
11784:                         }
11785:                     }
11786:                 }
11787:             } elsif ($context ne 'lti') {
11788:                 if ($role eq 'st') {
11789:                     if (ref($settings) ne 'HASH') {
11790:                         $check = ' checked="checked" '; 
11791:                     }
11792:                 }
11793:             }
11794:         }
11795:         $output .= '<td class="LC_left_item">'.
11796:                    '<span class="LC_nobreak">';
11797:         my $prefix = 'canmodify';
11798:         if ($role eq 'emailusername') {
11799:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
11800:                 $checks{$fields[$i]} = 'omit';
11801:             }
11802:             foreach my $option ('required','optional','omit') {
11803:                 my $checked='';
11804:                 if ($checks{$fields[$i]} eq $option) {
11805:                     $checked='checked="checked" ';
11806:                 }
11807:                 $output .= '<label>'.
11808:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
11809:                            &mt($option).'</label>'.('&nbsp;' x2);
11810:             }
11811:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
11812:         } else {
11813:             if ($context eq 'lti') {
11814:                 $prefix = 'lti';
11815:             } elsif ($context eq 'privacy') {
11816:                 $prefix = 'privacy';
11817:             }
11818:             $output .= '<label>'.
11819:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
11820:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
11821:                        '</label>';
11822:         }
11823:         $output .= '</span></td>';
11824:     }
11825:     $rem = $total%$numinrow;
11826:     my $colsleft;
11827:     if ($rem) {
11828:         $colsleft = $numinrow - $rem;
11829:     }
11830:     if ($colsleft > 1) {
11831:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
11832:                    '&nbsp;</td>';
11833:     } elsif ($colsleft == 1) {
11834:         $output .= '<td class="LC_left_item">&nbsp;</td>';
11835:     }
11836:     $output .= '</tr></table></td></tr>';
11837:     return $output;
11838: }
11839: 
11840: sub insttypes_row {
11841:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
11842:         $customcss,$rowstyle) = @_;
11843:     my %lt = &Apache::lonlocal::texthash (
11844:                       cansearch => 'Users allowed to search',
11845:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
11846:                       lockablenames => 'User preference to lock name',
11847:                       selfassign    => 'Self-reportable affiliations',
11848:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
11849:              );
11850:     my $showdom;
11851:     if ($context eq 'cansearch') {
11852:         $showdom = ' ('.$dom.')';
11853:     }
11854:     my $class = 'LC_left_item';
11855:     if ($context eq 'statustocreate') {
11856:         $class = 'LC_right_item';
11857:     }
11858:     my $css_class;
11859:     if ($$rowtotal%2) {
11860:         $css_class = 'LC_odd_row';
11861:     }
11862:     if ($customcss) {
11863:         $css_class .= ' '.$customcss;
11864:     }
11865:     $css_class =~ s/^\s+//;
11866:     if ($css_class) {
11867:         $css_class = ' class="'.$css_class.'"';
11868:     }
11869:     if ($rowstyle) {
11870:         $css_class .= ' style="'.$rowstyle.'"';
11871:     }
11872:     if ($onclick) {
11873:         $onclick = 'onclick="'.$onclick.'" ';
11874:     }
11875:     my $output = '<tr'.$css_class.'>'.
11876:                  '<td>'.$lt{$context}.$showdom.
11877:                  '</td><td class="'.$class.'" colspan="2"><table>';
11878:     my $rem;
11879:     if (ref($types) eq 'ARRAY') {
11880:         for (my $i=0; $i<@{$types}; $i++) {
11881:             if (defined($usertypes->{$types->[$i]})) {
11882:                 my $rem = $i%($numinrow);
11883:                 if ($rem == 0) {
11884:                     if ($i > 0) {
11885:                         $output .= '</tr>';
11886:                     }
11887:                     $output .= '<tr>';
11888:                 }
11889:                 my $check = ' ';
11890:                 if (ref($settings) eq 'HASH') {
11891:                     if (ref($settings->{$context}) eq 'ARRAY') {
11892:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
11893:                             $check = ' checked="checked" ';
11894:                         }
11895:                     } elsif (ref($settings->{$context}) eq 'HASH') {
11896:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
11897:                             $check = ' checked="checked" ';
11898:                         }
11899:                     } elsif ($context eq 'statustocreate') {
11900:                         $check = ' checked="checked" ';
11901:                     }
11902:                 }
11903:                 $output .= '<td class="LC_left_item">'.
11904:                            '<span class="LC_nobreak"><label>'.
11905:                            '<input type="checkbox" name="'.$context.'" '.
11906:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
11907:                            $usertypes->{$types->[$i]}.'</label></span></td>';
11908:             }
11909:         }
11910:         $rem = @{$types}%($numinrow);
11911:     }
11912:     my $colsleft = $numinrow - $rem;
11913:     if ($context eq 'overrides') {
11914:         if ($colsleft > 1) {
11915:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11916:         } else {
11917:             $output .= '<td class="LC_left_item">';
11918:         }
11919:         $output .= '&nbsp;';
11920:     } else {
11921:         if ($rem == 0) {
11922:             $output .= '<tr>';
11923:         }
11924:         if ($colsleft > 1) {
11925:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11926:         } else {
11927:             $output .= '<td class="LC_left_item">';
11928:         }
11929:         my $defcheck = ' ';
11930:         if (ref($settings) eq 'HASH') {  
11931:             if (ref($settings->{$context}) eq 'ARRAY') {
11932:                 if (grep(/^default$/,@{$settings->{$context}})) {
11933:                     $defcheck = ' checked="checked" ';
11934:                 }
11935:             } elsif ($context eq 'statustocreate') {
11936:                 $defcheck = ' checked="checked" ';
11937:             }
11938:         }
11939:         $output .= '<span class="LC_nobreak"><label>'.
11940:                    '<input type="checkbox" name="'.$context.'" '.
11941:                    'value="default"'.$defcheck.$onclick.' />'.
11942:                    $othertitle.'</label></span>';
11943:     }
11944:     $output .= '</td></tr></table></td></tr>';
11945:     return $output;
11946: }
11947: 
11948: sub sorted_searchtitles {
11949:     my %searchtitles = &Apache::lonlocal::texthash(
11950:                          'uname' => 'username',
11951:                          'lastname' => 'last name',
11952:                          'lastfirst' => 'last name, first name',
11953:                      );
11954:     my @titleorder = ('uname','lastname','lastfirst');
11955:     return (\%searchtitles,\@titleorder);
11956: }
11957: 
11958: sub sorted_searchtypes {
11959:     my %srchtypes_desc = (
11960:                            exact    => 'is exact match',
11961:                            contains => 'contains ..',
11962:                            begins   => 'begins with ..',
11963:                          );
11964:     my @srchtypeorder = ('exact','begins','contains');
11965:     return (\%srchtypes_desc,\@srchtypeorder);
11966: }
11967: 
11968: sub usertype_update_row {
11969:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
11970:     my $datatable;
11971:     my $numinrow = 4;
11972:     foreach my $type (@{$types}) {
11973:         if (defined($usertypes->{$type})) {
11974:             $$rownums ++;
11975:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
11976:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
11977:                           '</td><td class="LC_left_item"><table>';
11978:             for (my $i=0; $i<@{$fields}; $i++) {
11979:                 my $rem = $i%($numinrow);
11980:                 if ($rem == 0) {
11981:                     if ($i > 0) {
11982:                         $datatable .= '</tr>';
11983:                     }
11984:                     $datatable .= '<tr>';
11985:                 }
11986:                 my $check = ' ';
11987:                 if (ref($settings) eq 'HASH') {
11988:                     if (ref($settings->{'fields'}) eq 'HASH') {
11989:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
11990:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
11991:                                 $check = ' checked="checked" ';
11992:                             }
11993:                         }
11994:                     }
11995:                 }
11996: 
11997:                 if ($i == @{$fields}-1) {
11998:                     my $colsleft = $numinrow - $rem;
11999:                     if ($colsleft > 1) {
12000:                         $datatable .= '<td colspan="'.$colsleft.'">';
12001:                     } else {
12002:                         $datatable .= '<td>';
12003:                     }
12004:                 } else {
12005:                     $datatable .= '<td>';
12006:                 }
12007:                 $datatable .= '<span class="LC_nobreak"><label>'.
12008:                               '<input type="checkbox" name="updateable_'.$type.
12009:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
12010:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
12011:             }
12012:             $datatable .= '</tr></table></td></tr>';
12013:         }
12014:     }
12015:     return $datatable;
12016: }
12017: 
12018: sub modify_login {
12019:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12020:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
12021:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
12022:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlwindow,%samlnotsso);
12023:     %title = ( coursecatalog => 'Display course catalog',
12024:                adminmail => 'Display administrator E-mail address',
12025:                helpdesk  => 'Display "Contact Helpdesk" link',
12026:                newuser => 'Link for visitors to create a user account',
12027:                loginheader => 'Log-in box header',
12028:                saml => 'Dual SSO and non-SSO login');
12029:     @offon = ('off','on');
12030:     if (ref($domconfig{login}) eq 'HASH') {
12031:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
12032:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
12033:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
12034:             }
12035:         }
12036:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
12037:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
12038:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
12039:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
12040:                     $saml{$lonhost} = 1;
12041:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
12042:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
12043:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
12044:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
12045:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
12046:                     $samlwindow{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'window'};
12047:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
12048:                 }
12049:             }
12050:         }
12051:     }
12052:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
12053:                                            \%domconfig,\%loginhash);
12054:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12055:     foreach my $item (@toggles) {
12056:         $loginhash{login}{$item} = $env{'form.'.$item};
12057:     }
12058:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
12059:     if (ref($colchanges{'login'}) eq 'HASH') {  
12060:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
12061:                                          \%loginhash);
12062:     }
12063: 
12064:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12065:     my %domservers = &Apache::lonnet::get_servers($dom);
12066:     my @loginvia_attribs = ('serverpath','custompath','exempt');
12067:     if (keys(%servers) > 1) {
12068:         foreach my $lonhost (keys(%servers)) {
12069:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
12070:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
12071:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
12072:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
12073:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
12074:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12075:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12076:                         $changes{'loginvia'}{$lonhost} = 1;
12077:                     } else {
12078:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
12079:                         $changes{'loginvia'}{$lonhost} = 1;
12080:                     }
12081:                 } else {
12082:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12083:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12084:                         $changes{'loginvia'}{$lonhost} = 1;
12085:                     }
12086:                 }
12087:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
12088:                     foreach my $item (@loginvia_attribs) {
12089:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
12090:                     }
12091:                 } else {
12092:                     foreach my $item (@loginvia_attribs) {
12093:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12094:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12095:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
12096:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12097:                                 $new = '/';
12098:                             }
12099:                         }
12100:                         if (($item eq 'custompath') && 
12101:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12102:                             $new = '';
12103:                         }
12104:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
12105:                             $changes{'loginvia'}{$lonhost} = 1;
12106:                         }
12107:                         if ($item eq 'exempt') {
12108:                             $new = &check_exempt_addresses($new);
12109:                         }
12110:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12111:                     }
12112:                 }
12113:             } else {
12114:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12115:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12116:                     $changes{'loginvia'}{$lonhost} = 1;
12117:                     foreach my $item (@loginvia_attribs) {
12118:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12119:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12120:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12121:                                 $new = '/';
12122:                             }
12123:                         }
12124:                         if (($item eq 'custompath') && 
12125:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12126:                             $new = '';
12127:                         }
12128:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12129:                     }
12130:                 }
12131:             }
12132:         }
12133:     }
12134: 
12135:     my $servadm = $r->dir_config('lonAdmEMail');
12136:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
12137:     if (ref($domconfig{'login'}) eq 'HASH') {
12138:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
12139:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
12140:                 if ($lang eq 'nolang') {
12141:                     push(@currlangs,$lang);
12142:                 } elsif (defined($langchoices{$lang})) {
12143:                     push(@currlangs,$lang);
12144:                 } else {
12145:                     next;
12146:                 }
12147:             }
12148:         }
12149:     }
12150:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
12151:     if (@currlangs > 0) {
12152:         foreach my $lang (@currlangs) {
12153:             if (grep(/^\Q$lang\E$/,@delurls)) {
12154:                 $changes{'helpurl'}{$lang} = 1;
12155:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
12156:                 $changes{'helpurl'}{$lang} = 1;
12157:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
12158:                 push(@newlangs,$lang);
12159:             } else {
12160:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12161:             }
12162:         }
12163:     }
12164:     unless (grep(/^nolang$/,@currlangs)) {
12165:         if ($env{'form.loginhelpurl_nolang.filename'}) {
12166:             $changes{'helpurl'}{'nolang'} = 1;
12167:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
12168:             push(@newlangs,'nolang');
12169:         }
12170:     }
12171:     if ($env{'form.loginhelpurl_add_lang'}) {
12172:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
12173:             ($env{'form.loginhelpurl_add_file.filename'})) {
12174:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
12175:             $addedfile = $env{'form.loginhelpurl_add_lang'};
12176:         }
12177:     }
12178:     if ((@newlangs > 0) || ($addedfile)) {
12179:         my $error;
12180:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12181:         if ($configuserok eq 'ok') {
12182:             if ($switchserver) {
12183:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
12184:             } elsif ($author_ok eq 'ok') {
12185:                 my @allnew = @newlangs;
12186:                 if ($addedfile ne '') {
12187:                     push(@allnew,$addedfile);
12188:                 }
12189:                 my $modified = [];
12190:                 foreach my $lang (@allnew) {
12191:                     my $formelem = 'loginhelpurl_'.$lang;
12192:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
12193:                         $formelem = 'loginhelpurl_add_file';
12194:                     }
12195:                     (my $result,$newurl{$lang}) =
12196:                         &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
12197:                                                                 "help/$lang",'','',$newfile{$lang},
12198:                                                                 $modified);
12199:                     if ($result eq 'ok') {
12200:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
12201:                         $changes{'helpurl'}{$lang} = 1;
12202:                     } else {
12203:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
12204:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12205:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
12206:                             (!grep(/^\Q$lang\E$/,@delurls))) {
12207:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12208:                         }
12209:                     }
12210:                 }
12211:                 &update_modify_urls($r,$modified);
12212:             } else {
12213:                 $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);
12214:             }
12215:         } else {
12216:             $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);
12217:         }
12218:         if ($error) {
12219:             &Apache::lonnet::logthis($error);
12220:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12221:         }
12222:     }
12223: 
12224:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
12225:     if (ref($domconfig{'login'}) eq 'HASH') {
12226:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
12227:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
12228:                 if ($domservers{$lonhost}) {
12229:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12230:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
12231:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
12232:                     }
12233:                 }
12234:             }
12235:         }
12236:     }
12237:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
12238:     foreach my $lonhost (sort(keys(%domservers))) {
12239:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12240:             $changes{'headtag'}{$lonhost} = 1;
12241:         } else {
12242:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
12243:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
12244:             }
12245:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
12246:                 push(@newhosts,$lonhost);
12247:             } elsif ($currheadtagurls{$lonhost}) {
12248:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
12249:                 if ($currexempt{$lonhost}) {
12250:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
12251:                         $changes{'headtag'}{$lonhost} = 1;
12252:                     }
12253:                 } elsif ($possexempt{$lonhost}) {
12254:                     $changes{'headtag'}{$lonhost} = 1;
12255:                 }
12256:                 if ($possexempt{$lonhost}) {
12257:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12258:                 }
12259:             }
12260:         }
12261:     }
12262:     if (@newhosts) {
12263:         my $error;
12264:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12265:         if ($configuserok eq 'ok') {
12266:             if ($switchserver) {
12267:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
12268:             } elsif ($author_ok eq 'ok') {
12269:                 my $modified = [];
12270:                 foreach my $lonhost (@newhosts) {
12271:                     my $formelem = 'loginheadtag_'.$lonhost;
12272:                     (my $result,$newheadtagurls{$lonhost}) =
12273:                         &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
12274:                                                                 "login/headtag/$lonhost",'','',
12275:                                                                 $env{'form.loginheadtag_'.$lonhost.'.filename'},
12276:                                                                 $modified);
12277:                     if ($result eq 'ok') {
12278:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
12279:                         $changes{'headtag'}{$lonhost} = 1;
12280:                         if ($possexempt{$lonhost}) {
12281:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12282:                         }
12283:                     } else {
12284:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
12285:                                            $newheadtagurls{$lonhost},$result);
12286:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12287:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
12288:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
12289:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
12290:                         }
12291:                     }
12292:                 }
12293:                 &update_modify_urls($r,$modified);
12294:             } else {
12295:                 $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);
12296:             }
12297:         } else {
12298:             $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);
12299:         }
12300:         if ($error) {
12301:             &Apache::lonnet::logthis($error);
12302:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12303:         }
12304:     }
12305:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
12306:     my @newsamlimgs;
12307:     foreach my $lonhost (keys(%domservers)) {
12308:         if ($env{'form.saml_'.$lonhost}) {
12309:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
12310:                 push(@newsamlimgs,$lonhost);
12311:             }
12312:             foreach my $item ('text','alt','url','title','window','notsso') {
12313:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
12314:             }
12315:             if ($saml{$lonhost}) {
12316:                 if ($env{'form.saml_window_'.$lonhost} ne '1') {
12317:                     $env{'form.saml_window_'.$lonhost} = '';
12318:                 }
12319:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
12320: #FIXME Need to obsolete published image
12321:                     delete($currsaml{$lonhost}{'img'});
12322:                     $changes{'saml'}{$lonhost} = 1;
12323:                 }
12324:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
12325:                     $changes{'saml'}{$lonhost} = 1;
12326:                 }
12327:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
12328:                     $changes{'saml'}{$lonhost} = 1;
12329:                 }
12330:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
12331:                     $changes{'saml'}{$lonhost} = 1;
12332:                 }
12333:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
12334:                     $changes{'saml'}{$lonhost} = 1;
12335:                 }
12336:                 if ($env{'form.saml_window_'.$lonhost} ne $samlwindow{$lonhost}) {
12337:                     $changes{'saml'}{$lonhost} = 1;
12338:                 }
12339:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
12340:                     $changes{'saml'}{$lonhost} = 1;
12341:                 }
12342:             } else {
12343:                 $changes{'saml'}{$lonhost} = 1;
12344:             }
12345:             foreach my $item ('text','alt','url','title','window','notsso') {
12346:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
12347:             }
12348:         } else {
12349:             if ($saml{$lonhost}) {
12350:                 $changes{'saml'}{$lonhost} = 1;
12351:                 delete($currsaml{$lonhost});
12352:             }
12353:         }
12354:     }
12355:     foreach my $posshost (keys(%currsaml)) {
12356:         unless (exists($domservers{$posshost})) {
12357:             delete($currsaml{$posshost});
12358:         }
12359:     }
12360:     %{$loginhash{'login'}{'saml'}} = %currsaml;
12361:     if (@newsamlimgs) {
12362:         my $error;
12363:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12364:         if ($configuserok eq 'ok') {
12365:             if ($switchserver) {
12366:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
12367:             } elsif ($author_ok eq 'ok') {
12368:                 my $modified = [];
12369:                 foreach my $lonhost (@newsamlimgs) {
12370:                     my $formelem = 'saml_img_'.$lonhost;
12371:                     my ($result,$imgurl) =
12372:                         &Apache::lonconfigsettings::publishlogo($r,'upload',$formelem,$dom,$confname,
12373:                                                                 "login/saml/$lonhost",'','',
12374:                                                                 $env{'form.saml_img_'.$lonhost.'.filename'},
12375:                                                                 $modified);
12376:                     if ($result eq 'ok') {
12377:                         $currsaml{$lonhost}{'img'} = $imgurl;
12378:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
12379:                         $changes{'saml'}{$lonhost} = 1;
12380:                     } else {
12381:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
12382:                                            $lonhost,$result);
12383:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12384:                     }
12385:                 }
12386:                 &update_modify_urls($r,$modified);
12387:             } else {
12388:                 $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);
12389:             }
12390:         } else {
12391:             $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);
12392:         }
12393:         if ($error) {
12394:             &Apache::lonnet::logthis($error);
12395:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12396:         }
12397:     }
12398:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
12399: 
12400:     my $defaulthelpfile = '/adm/loginproblems.html';
12401:     my $defaulttext = &mt('Default in use');
12402: 
12403:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
12404:                                              $dom);
12405:     if ($putresult eq 'ok') {
12406:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12407:         my %defaultchecked = (
12408:                     'coursecatalog' => 'on',
12409:                     'helpdesk'      => 'on',
12410:                     'adminmail'     => 'off',
12411:                     'newuser'       => 'off',
12412:         );
12413:         if (ref($domconfig{'login'}) eq 'HASH') {
12414:             foreach my $item (@toggles) {
12415:                 if ($defaultchecked{$item} eq 'on') { 
12416:                     if (($domconfig{'login'}{$item} eq '0') &&
12417:                         ($env{'form.'.$item} eq '1')) {
12418:                         $changes{$item} = 1;
12419:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12420:                               $domconfig{'login'}{$item} eq '1') &&
12421:                              ($env{'form.'.$item} eq '0')) {
12422:                         $changes{$item} = 1;
12423:                     }
12424:                 } elsif ($defaultchecked{$item} eq 'off') {
12425:                     if (($domconfig{'login'}{$item} eq '1') &&
12426:                         ($env{'form.'.$item} eq '0')) {
12427:                         $changes{$item} = 1;
12428:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12429:                               $domconfig{'login'}{$item} eq '0') &&
12430:                              ($env{'form.'.$item} eq '1')) {
12431:                         $changes{$item} = 1;
12432:                     }
12433:                 }
12434:             }
12435:         }
12436:         if (keys(%changes) > 0 || $colchgtext) {
12437:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12438:             if (exists($changes{'saml'})) {
12439:                 my $hostid_in_use;
12440:                 my @hosts = &Apache::lonnet::current_machine_ids();
12441:                 if (@hosts > 1) {
12442:                     foreach my $hostid (@hosts) {
12443:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
12444:                             $hostid_in_use = $hostid;
12445:                             last;
12446:                         }
12447:                     }
12448:                 } else {
12449:                     $hostid_in_use = $r->dir_config('lonHostID');
12450:                 }
12451:                 if (($hostid_in_use) &&
12452:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
12453:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
12454:                 }
12455:                 if (ref($lastactref) eq 'HASH') {
12456:                     if (ref($changes{'saml'}) eq 'HASH') {
12457:                         my %updates;
12458:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
12459:                         $lastactref->{'samllanding'} = \%updates;
12460:                     }
12461:                 }
12462:             }
12463:             if (ref($lastactref) eq 'HASH') {
12464:                 $lastactref->{'domainconfig'} = 1;
12465:             }
12466:             $resulttext = &mt('Changes made:').'<ul>';
12467:             foreach my $item (sort(keys(%changes))) {
12468:                 if ($item eq 'loginvia') {
12469:                     if (ref($changes{$item}) eq 'HASH') {
12470:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
12471:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12472:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
12473:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
12474:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
12475:                                     $protocol = 'http' if ($protocol ne 'https');
12476:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
12477: 
12478:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
12479:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
12480:                                     } else {
12481:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
12482:                                     }
12483:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
12484:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
12485:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
12486:                                     }
12487:                                     $resulttext .= '</li>';
12488:                                 } else {
12489:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
12490:                                 }
12491:                             } else {
12492:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
12493:                             }
12494:                         }
12495:                         $resulttext .= '</ul></li>';
12496:                     }
12497:                 } elsif ($item eq 'helpurl') {
12498:                     if (ref($changes{$item}) eq 'HASH') {
12499:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
12500:                             if (grep(/^\Q$lang\E$/,@delurls)) {
12501:                                 my ($chg,$link);
12502:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
12503:                                 if ($lang eq 'nolang') {
12504:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
12505:                                 } else {
12506:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
12507:                                 }
12508:                                 $resulttext .= '<li>'.$chg.'</li>';
12509:                             } else {
12510:                                 my $chg;
12511:                                 if ($lang eq 'nolang') {
12512:                                     $chg = &mt('custom log-in help file for no preferred language');
12513:                                 } else {
12514:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
12515:                                 }
12516:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
12517:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
12518:                                                       '?inhibitmenu=yes',$chg,600,500).
12519:                                                '</li>';
12520:                             }
12521:                         }
12522:                     }
12523:                 } elsif ($item eq 'headtag') {
12524:                     if (ref($changes{$item}) eq 'HASH') {
12525:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12526:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12527:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
12528:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12529:                                 $resulttext .= '<li><a href="'.
12530:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
12531:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
12532:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
12533:                                 if ($possexempt{$lonhost}) {
12534:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
12535:                                 } else {
12536:                                     $resulttext .= &mt('included for any client IP');
12537:                                 }
12538:                                 $resulttext .= '</li>';
12539:                             }
12540:                         }
12541:                     }
12542:                 } elsif ($item eq 'saml') {
12543:                     if (ref($changes{$item}) eq 'HASH') {
12544:                         my %notlt = (
12545:                                        text   => 'Text for log-in by SSO',
12546:                                        img    => 'SSO button image',
12547:                                        alt    => 'Alt text for button image',
12548:                                        url    => 'SSO URL',
12549:                                        title  => 'Tooltip for SSO link',
12550:                                        window => 'Pop-up window if iframe',
12551:                                        notsso => 'Text for non-SSO log-in',
12552:                                     );
12553:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12554:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
12555:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
12556:                                                '<ul>';
12557:                                 foreach my $key ('text','img','alt','url','title','window','notsso') {
12558:                                     if ($currsaml{$lonhost}{$key} eq '') {
12559:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
12560:                                     } else {
12561:                                         my $value = "'$currsaml{$lonhost}{$key}'";
12562:                                         if ($key eq 'img') {
12563:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
12564:                                         } elsif ($key eq 'window') {
12565:                                             $value = 'On';
12566:                                         }
12567:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
12568:                                                                   $value).'</li>';
12569:                                     }
12570:                                 }
12571:                                 $resulttext .= '</ul></li>';
12572:                             } else {
12573:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
12574:                             }
12575:                         }
12576:                     }
12577:                 } elsif ($item eq 'captcha') {
12578:                     if (ref($loginhash{'login'}) eq 'HASH') {
12579:                         my $chgtxt;
12580:                         if ($loginhash{'login'}{$item} eq 'notused') {
12581:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
12582:                         } else {
12583:                             my %captchas = &captcha_phrases();
12584:                             if ($captchas{$loginhash{'login'}{$item}}) {
12585:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
12586:                             } else {
12587:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
12588:                             }
12589:                         }
12590:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12591:                     }
12592:                 } elsif ($item eq 'recaptchakeys') {
12593:                     if (ref($loginhash{'login'}) eq 'HASH') {
12594:                         my ($privkey,$pubkey);
12595:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
12596:                             $pubkey = $loginhash{'login'}{$item}{'public'};
12597:                             $privkey = $loginhash{'login'}{$item}{'private'};
12598:                         }
12599:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
12600:                         if (!$pubkey) {
12601:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
12602:                         } else {
12603:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
12604:                         }
12605:                         if (!$privkey) {
12606:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
12607:                         } else {
12608:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
12609:                         }
12610:                         $chgtxt .= '</ul>';
12611:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12612:                     }
12613:                 } elsif ($item eq 'recaptchaversion') {
12614:                     if (ref($loginhash{'login'}) eq 'HASH') {
12615:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
12616:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
12617:                                            '</li>';
12618:                         }
12619:                     }
12620:                 } else {
12621:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
12622:                 }
12623:             }
12624:             $resulttext .= $colchgtext.'</ul>';
12625:         } else {
12626:             $resulttext = &mt('No changes made to log-in page settings');
12627:         }
12628:     } else {
12629:         $resulttext = '<span class="LC_error">'.
12630: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12631:     }
12632:     if ($errors) {
12633:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12634:                        $errors.'</ul>';
12635:     }
12636:     return $resulttext;
12637: }
12638: 
12639: sub check_exempt_addresses {
12640:     my ($iplist) = @_;
12641:     $iplist =~ s/^\s+//;
12642:     $iplist =~ s/\s+$//;
12643:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
12644:     my (@okips,$new);
12645:     foreach my $ip (@poss_ips) {
12646:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
12647:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
12648:                 push(@okips,$ip);
12649:             }
12650:         }
12651:     }
12652:     if (@okips > 0) {
12653:         $new = join(',',@okips);
12654:     } else {
12655:         $new = '';
12656:     }
12657:     return $new;
12658: }
12659: 
12660: sub color_font_choices {
12661:     my %choices =
12662:         &Apache::lonlocal::texthash (
12663:             img => "Header",
12664:             bgs => "Background colors",
12665:             links => "Link colors",
12666:             images => "Images",
12667:             font => "Font color",
12668:             fontmenu => "Font menu",
12669:             pgbg => "Page",
12670:             tabbg => "Header",
12671:             sidebg => "Border",
12672:             link => "Link",
12673:             alink => "Active link",
12674:             vlink => "Visited link",
12675:         );
12676:     return %choices;
12677: }
12678: 
12679: sub modify_ipaccess {
12680:     my ($dom,$lastactref,%domconfig) = @_;
12681:     my (@allpos,%changes,%confhash,$errors,$resulttext);
12682:     my (@items,%deletions,%itemids,@warnings);
12683:     my ($typeorder,$types) = &commblocktype_text();
12684:     if ($env{'form.ipaccess_add'}) {
12685:         my $name = $env{'form.ipaccess_name_add'};
12686:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
12687:         if ($newid) {
12688:             $itemids{'add'} = $newid;
12689:             push(@items,'add');
12690:             $changes{$newid} = 1;
12691:         } else {
12692:             $error = &mt('Failed to acquire unique ID for new IP access control item');
12693:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12694:         }
12695:     }
12696:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
12697:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
12698:         if (@todelete) {
12699:             map { $deletions{$_} = 1; } @todelete;
12700:         }
12701:         my $maxnum = $env{'form.ipaccess_maxnum'};
12702:         for (my $i=0; $i<$maxnum; $i++) {
12703:             my $itemid = $env{'form.ipaccess_id_'.$i};
12704:             $itemid =~ s/\D+//g;
12705:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12706:                 if ($deletions{$itemid}) {
12707:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
12708:                 } else {
12709:                     push(@items,$i);
12710:                     $itemids{$i} = $itemid;
12711:                 }
12712:             }
12713:         }
12714:     }
12715:     foreach my $idx (@items) {
12716:         my $itemid = $itemids{$idx};
12717:         next unless ($itemid);
12718:         my %current;
12719:         unless ($idx eq 'add') {
12720:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12721:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
12722:             }
12723:         }
12724:         my $position = $env{'form.ipaccess_pos_'.$itemid};
12725:         $position =~ s/\D+//g;
12726:         if ($position ne '') {
12727:             $allpos[$position] = $itemid;
12728:         }
12729:         my $name = $env{'form.ipaccess_name_'.$idx};
12730:         $name =~ s/^\s+|\s+$//g;
12731:         $confhash{$itemid}{'name'} = $name;
12732:         my $possrange = $env{'form.ipaccess_range_'.$idx};
12733:         $possrange =~ s/^\s+|\s+$//g;
12734:         unless ($possrange eq '') {
12735:             $possrange =~ s/[\r\n]+/\s/g;
12736:             $possrange =~ s/\s*-\s*/-/g;
12737:             $possrange =~ s/\s+/,/g;
12738:             $possrange =~ s/,+/,/g;
12739:             if ($possrange ne '') {
12740:                 my (@ok,$count);
12741:                 $count = 0;
12742:                 foreach my $poss (split(/\,/,$possrange)) {
12743:                     $count ++;
12744:                     $poss = &validate_ip_pattern($poss);
12745:                     if ($poss ne '') {
12746:                         push(@ok,$poss);
12747:                     }
12748:                 }
12749:                 my $diff = $count - scalar(@ok);
12750:                 if ($diff) {
12751:                     $errors .= '<li><span class="LC_error">'.
12752:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
12753:                                    $diff,$name).
12754:                                '</span></li>';
12755:                 }
12756:                 if (@ok) {
12757:                     my @cidr_list;
12758:                     foreach my $item (@ok) {
12759:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
12760:                     }
12761:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
12762:                 }
12763:             }
12764:         }
12765:         foreach my $field ('name','ip') {
12766:             unless (($idx eq 'add') || ($changes{$itemid})) {
12767:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
12768:                     $changes{$itemid} = 1;
12769:                     last;
12770:                 }
12771:             }
12772:         }
12773:         $confhash{$itemid}{'commblocks'} = {};
12774: 
12775:         my %commblocks;
12776:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);
12777:         foreach my $type (@{$typeorder}) {
12778:             if ($commblocks{$type}) {
12779:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
12780:             }
12781:             unless (($idx eq 'add') || ($changes{$itemid})) {
12782:                 if (ref($current{'commblocks'}) eq 'HASH') {
12783:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
12784:                         $changes{$itemid} = 1;
12785:                     }
12786:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
12787:                     $changes{$itemid} = 1;
12788:                 }
12789:             }
12790:         }
12791:         $confhash{$itemid}{'courses'} = {};
12792:         my %crsdeletions;
12793:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
12794:         if (@delcrs) {
12795:             map { $crsdeletions{$_} = 1; } @delcrs;
12796:         }
12797:         if (ref($current{'courses'}) eq 'HASH') {
12798:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
12799:                 if ($crsdeletions{$cid}) {
12800:                     $changes{$itemid} = 1;
12801:                 } else {
12802:                     $confhash{$itemid}{'courses'}{$cid} = 1;
12803:                 }
12804:             }
12805:         }
12806:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
12807:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
12808:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) &&
12809:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
12810:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
12811:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
12812:                 $errors .= '<li><span class="LC_error">'.
12813:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
12814:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
12815:                            '</span></li>';
12816:             } else {
12817:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
12818:                 $changes{$itemid} = 1;
12819:             }
12820:         }
12821:     }
12822:     if (@allpos > 0) {
12823:         my $idx = 0;
12824:         foreach my $itemid (@allpos) {
12825:             if ($itemid ne '') {
12826:                 $confhash{$itemid}{'order'} = $idx;
12827:                 unless ($changes{$itemid}) {
12828:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
12829:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12830:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
12831:                                 $changes{$itemid} = 1;
12832:                             }
12833:                         }
12834:                     }
12835:                 }
12836:                 $idx ++;
12837:             }
12838:         }
12839:     }
12840:     if (keys(%changes)) {
12841:         my %defaultshash = (
12842:                               ipaccess => \%confhash,
12843:                            );
12844:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
12845:                                                  $dom);
12846:         if ($putresult eq 'ok') {
12847:             my $cachetime = 1800;
12848:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
12849:             if (ref($lastactref) eq 'HASH') {
12850:                 $lastactref->{'ipaccess'} = 1;
12851:             }
12852:             $resulttext = &mt('Changes made:').'<ul>';
12853:             my %bynum;
12854:             foreach my $itemid (sort(keys(%changes))) {
12855:                 if (ref($confhash{$itemid}) eq 'HASH') {
12856:                     my $position = $confhash{$itemid}{'order'};
12857:                     if ($position =~ /^\d+$/) {
12858:                         $bynum{$position} = $itemid;
12859:                     }
12860:                 }
12861:             }
12862:             if (keys(%deletions)) {
12863:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
12864:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
12865:                 }
12866:             }
12867:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
12868:                 my $itemid = $bynum{$pos};
12869:                 if (ref($confhash{$itemid}) eq 'HASH') {
12870:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
12871:                     my $position = $pos + 1;
12872:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
12873:                     if ($confhash{$itemid}{'ip'} eq '') {
12874:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
12875:                     } else {
12876:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
12877:                     }
12878:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
12879:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
12880:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
12881:                                        '</li>';
12882:                     } else {
12883:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
12884:                     }
12885:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
12886:                         my @courses;
12887:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
12888:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
12889:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
12890:                         }
12891:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
12892:                                              join('</li><li>',@courses).'</li></ul>';
12893:                     } else {
12894:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
12895:                     }
12896:                     $resulttext .= '</ul></li>';
12897:                 }
12898:             }
12899:             $resulttext .= '</ul>';
12900:         } else {
12901:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
12902:         }
12903:     } else {
12904:         $resulttext = &mt('No changes made');
12905:     }
12906:     if ($errors) {
12907:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
12908:                        $errors.'</ul></p>';
12909:     }
12910:     return $resulttext;
12911: }
12912: 
12913: sub get_ipaccess_id {
12914:     my ($domain,$location) = @_;
12915:     # get lock on ipaccess db
12916:     my $lockhash = {
12917:                       lock => $env{'user.name'}.
12918:                               ':'.$env{'user.domain'},
12919:                    };
12920:     my $tries = 0;
12921:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
12922:     my ($id,$error);
12923: 
12924:     while (($gotlock ne 'ok') && ($tries<10)) {
12925:         $tries ++;
12926:         sleep (0.1);
12927:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
12928:     }
12929:     if ($gotlock eq 'ok') {
12930:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
12931:         if ($currids{'lock'}) {
12932:             delete($currids{'lock'});
12933:             if (keys(%currids)) {
12934:                 my @curr = sort { $a <=> $b } keys(%currids);
12935:                 if ($curr[-1] =~ /^\d+$/) {
12936:                     $id = 1 + $curr[-1];
12937:                 }
12938:             } else {
12939:                 $id = 1;
12940:             }
12941:             if ($id) {
12942:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
12943:                     $error = 'nostore';
12944:                 }
12945:             } else {
12946:                 $error = 'nonumber';
12947:             }
12948:         }
12949:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
12950:     } else {
12951:         $error = 'nolock';
12952:     }
12953:     return ($id,$error);
12954: }
12955: 
12956: sub modify_rolecolors {
12957:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
12958:     my ($resulttext,%rolehash);
12959:     $rolehash{'rolecolors'} = {};
12960:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
12961:         if ($domconfig{'rolecolors'} eq '') {
12962:             $domconfig{'rolecolors'} = {};
12963:         }
12964:     }
12965:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
12966:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
12967:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
12968:                                              $dom);
12969:     if ($putresult eq 'ok') {
12970:         if (keys(%changes) > 0) {
12971:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12972:             if (ref($lastactref) eq 'HASH') {
12973:                 $lastactref->{'domainconfig'} = 1;
12974:             }
12975:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
12976:                                              $rolehash{'rolecolors'});
12977:         } else {
12978:             $resulttext = &mt('No changes made to default color schemes');
12979:         }
12980:     } else {
12981:         $resulttext = '<span class="LC_error">'.
12982: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12983:     }
12984:     if ($errors) {
12985:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
12986:                        $errors.'</ul>';
12987:     }
12988:     return $resulttext;
12989: }
12990: 
12991: sub modify_colors {
12992:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
12993:     my (%changes,%choices);
12994:     my @bgs;
12995:     my @links = ('link','alink','vlink');
12996:     my @logintext;
12997:     my @images;
12998:     my $servadm = $r->dir_config('lonAdmEMail');
12999:     my $errors;
13000:     my %defaults;
13001:     foreach my $role (@{$roles}) {
13002:         if ($role eq 'login') {
13003:             %choices = &login_choices();
13004:             @logintext = ('textcol','bgcol');
13005:         } else {
13006:             %choices = &color_font_choices();
13007:         }
13008:         if ($role eq 'login') {
13009:             @images = ('img','logo','domlogo','login');
13010:             @bgs = ('pgbg','mainbg','sidebg');
13011:         } else {
13012:             @images = ('img');
13013:             @bgs = ('pgbg','tabbg','sidebg');
13014:         }
13015:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
13016:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
13017:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
13018:         }
13019:         if ($role eq 'login') {
13020:             foreach my $item (@logintext) {
13021:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13022:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13023:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13024:                 }
13025:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
13026:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13027:                 }
13028:             }
13029:         } else {
13030:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
13031:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
13032:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
13033:             }
13034:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
13035:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
13036:             }
13037:         }
13038:         foreach my $item (@bgs) {
13039:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13040:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13041:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13042:             }
13043:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
13044:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13045:             }
13046:         }
13047:         foreach my $item (@links) {
13048:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13049:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13050:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13051:             }
13052:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
13053:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13054:             }
13055:         }
13056:         my ($configuserok,$author_ok,$switchserver) = 
13057:             &config_check($dom,$confname,$servadm);
13058:         my ($width,$height) = &thumb_dimensions();
13059:         if (ref($domconfig->{$role}) ne 'HASH') {
13060:             $domconfig->{$role} = {};
13061:         }
13062:         foreach my $img (@images) {
13063:             if ($role eq 'login') {
13064:                 if (($img eq 'img') || ($img eq 'logo')) {  
13065:                     if (defined($env{'form.login_showlogo_'.$img})) {
13066:                         $confhash->{$role}{'showlogo'}{$img} = 1;
13067:                     } else { 
13068:                         $confhash->{$role}{'showlogo'}{$img} = 0;
13069:                     }
13070:                 }
13071:                 if ($env{'form.login_alt_'.$img} ne '') {
13072:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
13073:                 }
13074:             }
13075: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
13076: 		 && !defined($domconfig->{$role}{$img})
13077: 		 && !$env{'form.'.$role.'_del_'.$img}
13078: 		 && $env{'form.'.$role.'_import_'.$img}) {
13079: 		# import the old configured image from the .tab setting
13080: 		# if they haven't provided a new one 
13081: 		$domconfig->{$role}{$img} = 
13082: 		    $env{'form.'.$role.'_import_'.$img};
13083: 	    }
13084:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
13085:                 my $error;
13086:                 if ($configuserok eq 'ok') {
13087:                     if ($switchserver) {
13088:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
13089:                     } else {
13090:                         if ($author_ok eq 'ok') {
13091:                             my $modified = [];
13092:                             my ($result,$logourl) = 
13093:                                 &Apache::lonconfigsettings::publishlogo($r,'upload',$role.'_'.$img,
13094:                                                                         $dom,$confname,$img,$width,$height,
13095:                                                                         '',$modified);
13096:                             if ($result eq 'ok') {
13097:                                 $confhash->{$role}{$img} = $logourl;
13098:                                 $changes{$role}{'images'}{$img} = 1;
13099:                                 &update_modify_urls($r,$modified);
13100:                             } else {
13101:                                 $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);
13102:                             }
13103:                         } else {
13104:                             $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);
13105:                         }
13106:                     }
13107:                 } else {
13108:                     $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);
13109:                 }
13110:                 if ($error) {
13111:                     &Apache::lonnet::logthis($error);
13112:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13113:                 }
13114:             } elsif ($domconfig->{$role}{$img} ne '') {
13115:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
13116:                     my $error;
13117:                     if ($configuserok eq 'ok') {
13118: # is confname an author?
13119:                         if ($switchserver eq '') {
13120:                             if ($author_ok eq 'ok') {
13121:                                 my $modified = [];
13122:                                 my ($result,$logourl) = 
13123:                                     &Apache::lonconfigsettings::publishlogo($r,'copy',$domconfig->{$role}{$img},
13124:                                                                             $dom,$confname,$img,$width,$height,
13125:                                                                             '',$modified);
13126:                                 if ($result eq 'ok') {
13127:                                     $confhash->{$role}{$img} = $logourl;
13128: 				    $changes{$role}{'images'}{$img} = 1;
13129:                                     &update_modify_urls($r,$modified);
13130:                                 }
13131:                             }
13132:                         }
13133:                     }
13134:                 }
13135:             }
13136:         }
13137:         if (ref($domconfig) eq 'HASH') {
13138:             if (ref($domconfig->{$role}) eq 'HASH') {
13139:                 foreach my $img (@images) {
13140:                     if ($domconfig->{$role}{$img} ne '') {
13141:                         if ($env{'form.'.$role.'_del_'.$img}) {
13142:                             $confhash->{$role}{$img} = '';
13143:                             $changes{$role}{'images'}{$img} = 1;
13144:                         } else {
13145:                             if ($confhash->{$role}{$img} eq '') {
13146:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
13147:                             }
13148:                         }
13149:                     } else {
13150:                         if ($env{'form.'.$role.'_del_'.$img}) {
13151:                             $confhash->{$role}{$img} = '';
13152:                             $changes{$role}{'images'}{$img} = 1;
13153:                         } 
13154:                     }
13155:                     if ($role eq 'login') {
13156:                         if (($img eq 'logo') || ($img eq 'img')) {
13157:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
13158:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
13159:                                     $domconfig->{$role}{'showlogo'}{$img}) {
13160:                                     $changes{$role}{'showlogo'}{$img} = 1; 
13161:                                 }
13162:                             } else {
13163:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13164:                                     $changes{$role}{'showlogo'}{$img} = 1;
13165:                                 }
13166:                             }
13167:                         }
13168:                         if ($img ne 'login') {
13169:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
13170:                                 if ($confhash->{$role}{'alttext'}{$img} ne
13171:                                     $domconfig->{$role}{'alttext'}{$img}) {
13172:                                     $changes{$role}{'alttext'}{$img} = 1;
13173:                                 }
13174:                             } else {
13175:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13176:                                     $changes{$role}{'alttext'}{$img} = 1;
13177:                                 }
13178:                             }
13179:                         }
13180:                     }
13181:                 }
13182:                 if ($domconfig->{$role}{'font'} ne '') {
13183:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
13184:                         $changes{$role}{'font'} = 1;
13185:                     }
13186:                 } else {
13187:                     if ($confhash->{$role}{'font'}) {
13188:                         $changes{$role}{'font'} = 1;
13189:                     }
13190:                 }
13191:                 if ($role ne 'login') {
13192:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
13193:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
13194:                             $changes{$role}{'fontmenu'} = 1;
13195:                         }
13196:                     } else {
13197:                         if ($confhash->{$role}{'fontmenu'}) {
13198:                             $changes{$role}{'fontmenu'} = 1;
13199:                         }
13200:                     }
13201:                 }
13202:                 foreach my $item (@bgs) {
13203:                     if ($domconfig->{$role}{$item} ne '') {
13204:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13205:                             $changes{$role}{'bgs'}{$item} = 1;
13206:                         } 
13207:                     } else {
13208:                         if ($confhash->{$role}{$item}) {
13209:                             $changes{$role}{'bgs'}{$item} = 1;
13210:                         }
13211:                     }
13212:                 }
13213:                 foreach my $item (@links) {
13214:                     if ($domconfig->{$role}{$item} ne '') {
13215:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13216:                             $changes{$role}{'links'}{$item} = 1;
13217:                         }
13218:                     } else {
13219:                         if ($confhash->{$role}{$item}) {
13220:                             $changes{$role}{'links'}{$item} = 1;
13221:                         }
13222:                     }
13223:                 }
13224:                 foreach my $item (@logintext) {
13225:                     if ($domconfig->{$role}{$item} ne '') {
13226:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13227:                             $changes{$role}{'logintext'}{$item} = 1;
13228:                         }
13229:                     } else {
13230:                         if ($confhash->{$role}{$item}) {
13231:                             $changes{$role}{'logintext'}{$item} = 1;
13232:                         }
13233:                     }
13234:                 }
13235:             } else {
13236:                 &default_change_checker($role,\@images,\@links,\@bgs,
13237:                                         \@logintext,$confhash,\%changes); 
13238:             }
13239:         } else {
13240:             &default_change_checker($role,\@images,\@links,\@bgs,
13241:                                     \@logintext,$confhash,\%changes); 
13242:         }
13243:     }
13244:     return ($errors,%changes);
13245: }
13246: 
13247: sub config_check {
13248:     my ($dom,$confname,$servadm) = @_;
13249:     my ($configuserok,$author_ok,$switchserver,%currroles);
13250:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
13251:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
13252:                                                    $confname,$servadm);
13253:     if ($configuserok eq 'ok') {
13254:         $switchserver = &check_switchserver($dom,$confname);
13255:         if ($switchserver eq '') {
13256:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
13257:         }
13258:     }
13259:     return ($configuserok,$author_ok,$switchserver);
13260: }
13261: 
13262: sub default_change_checker {
13263:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
13264:     foreach my $item (@{$links}) {
13265:         if ($confhash->{$role}{$item}) {
13266:             $changes->{$role}{'links'}{$item} = 1;
13267:         }
13268:     }
13269:     foreach my $item (@{$bgs}) {
13270:         if ($confhash->{$role}{$item}) {
13271:             $changes->{$role}{'bgs'}{$item} = 1;
13272:         }
13273:     }
13274:     foreach my $item (@{$logintext}) {
13275:         if ($confhash->{$role}{$item}) {
13276:             $changes->{$role}{'logintext'}{$item} = 1;
13277:         }
13278:     }
13279:     foreach my $img (@{$images}) {
13280:         if ($env{'form.'.$role.'_del_'.$img}) {
13281:             $confhash->{$role}{$img} = '';
13282:             $changes->{$role}{'images'}{$img} = 1;
13283:         }
13284:         if ($role eq 'login') {
13285:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13286:                 $changes->{$role}{'showlogo'}{$img} = 1;
13287:             }
13288:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
13289:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13290:                     $changes->{$role}{'alttext'}{$img} = 1;
13291:                 }
13292:             }
13293:         }
13294:     }
13295:     if ($confhash->{$role}{'font'}) {
13296:         $changes->{$role}{'font'} = 1;
13297:     }
13298: }
13299: 
13300: sub display_colorchgs {
13301:     my ($dom,$changes,$roles,$confhash) = @_;
13302:     my (%choices,$resulttext);
13303:     if (!grep(/^login$/,@{$roles})) {
13304:         $resulttext = &mt('Changes made:').'<br />';
13305:     }
13306:     foreach my $role (@{$roles}) {
13307:         if ($role eq 'login') {
13308:             %choices = &login_choices();
13309:         } else {
13310:             %choices = &color_font_choices();
13311:         }
13312:         if (ref($changes->{$role}) eq 'HASH') {
13313:             if ($role ne 'login') {
13314:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
13315:             }
13316:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
13317:                 if ($role ne 'login') {
13318:                     $resulttext .= '<ul>';
13319:                 }
13320:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
13321:                     if ($role ne 'login') {
13322:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
13323:                     }
13324:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
13325:                         if (($role eq 'login') && ($key eq 'showlogo')) {
13326:                             if ($confhash->{$role}{$key}{$item}) {
13327:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
13328:                             } else {
13329:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
13330:                             }
13331:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
13332:                             if ($confhash->{$role}{$key}{$item} ne '') {
13333:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
13334:                                                $confhash->{$role}{$key}{$item}).'</li>';
13335:                             } else {
13336:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
13337:                             }
13338:                         } elsif ($confhash->{$role}{$item} eq '') {
13339:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
13340:                         } else {
13341:                             my $newitem = $confhash->{$role}{$item};
13342:                             if ($key eq 'images') {
13343:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
13344:                             }
13345:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
13346:                         }
13347:                     }
13348:                     if ($role ne 'login') {
13349:                         $resulttext .= '</ul></li>';
13350:                     }
13351:                 } else {
13352:                     if ($confhash->{$role}{$key} eq '') {
13353:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
13354:                     } else {
13355:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
13356:                     }
13357:                 }
13358:                 if ($role ne 'login') {
13359:                     $resulttext .= '</ul>';
13360:                 }
13361:             }
13362:         }
13363:     }
13364:     return $resulttext;
13365: }
13366: 
13367: sub thumb_dimensions {
13368:     return ('200','50');
13369: }
13370: 
13371: sub check_dimensions {
13372:     my ($inputfile) = @_;
13373:     my ($fullwidth,$fullheight);
13374:     if ($inputfile =~ m|^[/\w.\-]+$|) {
13375:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
13376:             my $imageinfo = <PIPE>;
13377:             if (!close(PIPE)) {
13378:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
13379:             }
13380:             chomp($imageinfo);
13381:             my ($fullsize) = 
13382:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
13383:             if ($fullsize) {
13384:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
13385:             }
13386:         }
13387:     }
13388:     return ($fullwidth,$fullheight);
13389: }
13390: 
13391: sub check_configuser {
13392:     my ($uhome,$dom,$confname,$servadm) = @_;
13393:     my ($configuserok,%currroles);
13394:     if ($uhome eq 'no_host') {
13395:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
13396:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
13397:         $configuserok = 
13398:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
13399:                              $configpass,'','','','','',undef,$servadm);
13400:     } else {
13401:         $configuserok = 'ok';
13402:         %currroles = 
13403:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
13404:     }
13405:     return ($configuserok,%currroles);
13406: }
13407: 
13408: sub check_authorstatus {
13409:     my ($dom,$confname,%currroles) = @_;
13410:     my $author_ok;
13411:     if (!$currroles{':'.$dom.':au'}) {
13412:         my $start = time;
13413:         my $end = 0;
13414:         $author_ok = 
13415:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
13416:                                         'au',$end,$start,'','','domconfig');
13417:     } else {
13418:         $author_ok = 'ok';
13419:     }
13420:     return $author_ok;
13421: }
13422: 
13423: sub update_modify_urls {
13424:     my ($r,$modified) = @_;
13425:     if ((ref($modified) eq 'ARRAY') && (@{$modified})) {
13426:         push(@{$modified_urls},$modified);
13427:         unless ($registered_cleanup) {
13428:             my $handlers = $r->get_handlers('PerlCleanupHandler');
13429:             $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13430:             $registered_cleanup=1;
13431:         }
13432:     }
13433: }
13434: 
13435: sub notifysubscribed {
13436:     foreach my $targetsource (@{$modified_urls}){
13437:         next unless (ref($targetsource) eq 'ARRAY');
13438:         my ($target,$source)=@{$targetsource};
13439:         if ($source ne '') {
13440:             if (open(my $logfh,">>",$source.'.log')) {
13441:                 print $logfh "\nCleanup phase: Notifications\n";
13442:                 my @subscribed=&subscribed_hosts($target);
13443:                 foreach my $subhost (@subscribed) {
13444:                     print $logfh "\nNotifying host ".$subhost.':';
13445:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
13446:                     print $logfh $reply;
13447:                 }
13448:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
13449:                 foreach my $subhost (@subscribedmeta) {
13450:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
13451:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
13452:                                                         $subhost);
13453:                     print $logfh $reply;
13454:                 }
13455:                 print $logfh "\n============ Done ============\n";
13456:                 close($logfh);
13457:             }
13458:         }
13459:     }
13460:     return OK;
13461: }
13462: 
13463: sub subscribed_hosts {
13464:     my ($target) = @_;
13465:     my @subscribed;
13466:     if (open(my $fh,"<","$target.subscription")) {
13467:         while (my $subline=<$fh>) {
13468:             if ($subline =~ /^($match_lonid):/) {
13469:                 my $host = $1;
13470:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
13471:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
13472:                         push(@subscribed,$host);
13473:                     }
13474:                 }
13475:             }
13476:         }
13477:     }
13478:     return @subscribed;
13479: }
13480: 
13481: sub check_switchserver {
13482:     my ($dom,$confname) = @_;
13483:     my ($allowed,$switchserver,$home);
13484:     if ($confname eq '') {
13485:         $home = &Apache::lonnet::domain($dom,'primary');
13486:     } else {
13487:         $home = &Apache::lonnet::homeserver($confname,$dom);
13488:         if ($home eq 'no_host') {
13489:             $home = &Apache::lonnet::domain($dom,'primary');
13490:         }
13491:     }
13492:     my @ids=&Apache::lonnet::current_machine_ids();
13493:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
13494:     if (!$allowed) {
13495: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
13496:     }
13497:     return $switchserver;
13498: }
13499: 
13500: sub modify_quotas {
13501:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13502:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
13503:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
13504:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
13505:         $validationfieldsref);
13506:     if ($action eq 'quotas') {
13507:         $context = 'tools'; 
13508:     } else {
13509:         $context = $action;
13510:     }
13511:     if ($context eq 'requestcourses') {
13512:         @usertools = ('official','unofficial','community','textbook','placement','lti');
13513:         @options =('norequest','approval','validate','autolimit');
13514:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
13515:         %titles = &courserequest_titles();
13516:         $toolregexp = join('|',@usertools);
13517:         %conditions = &courserequest_conditions();
13518:         $confname = $dom.'-domainconfig';
13519:         my $servadm = $r->dir_config('lonAdmEMail');
13520:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13521:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
13522:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
13523:     } elsif ($context eq 'requestauthor') {
13524:         @usertools = ('author');
13525:         %titles = &authorrequest_titles();
13526:     } else {
13527:         @usertools = ('aboutme','blog','webdav','portfolio','timezone');
13528:         %titles = &tool_titles();
13529:     }
13530:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13531:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13532:     foreach my $key (keys(%env)) {
13533:         if ($context eq 'requestcourses') {
13534:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
13535:                 my $item = $1;
13536:                 my $type = $2;
13537:                 if ($type =~ /^limit_(.+)/) {
13538:                     $limithash{$item}{$1} = $env{$key};
13539:                 } else {
13540:                     $confhash{$item}{$type} = $env{$key};
13541:                 }
13542:             }
13543:         } elsif ($context eq 'requestauthor') {
13544:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
13545:                 $confhash{$1} = $env{$key};
13546:             }
13547:         } else {
13548:             if ($key =~ /^form\.quota_(.+)$/) {
13549:                 $confhash{'defaultquota'}{$1} = $env{$key};
13550:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
13551:                 $confhash{'authorquota'}{$1} = $env{$key};
13552:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
13553:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
13554:             }
13555:         }
13556:     }
13557:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
13558:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
13559:         @approvalnotify = sort(@approvalnotify);
13560:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
13561:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
13562:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
13563:         foreach my $type (@hasuniquecode) {
13564:             if (grep(/^\Q$type\E$/,@crstypes)) {
13565:                 $confhash{'uniquecode'}{$type} = 1;
13566:             }
13567:         }
13568:         my (%newbook,%allpos);
13569:         if ($context eq 'requestcourses') {
13570:             foreach my $type ('textbooks','templates') {
13571:                 @{$allpos{$type}} = (); 
13572:                 my $invalid;
13573:                 if ($type eq 'textbooks') {
13574:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
13575:                 } else {
13576:                     $invalid = &mt('Invalid LON-CAPA course for template');
13577:                 }
13578:                 if ($env{'form.'.$type.'_addbook'}) {
13579:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
13580:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
13581:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
13582:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
13583:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
13584:                         } else {
13585:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
13586:                             my $position = $env{'form.'.$type.'_addbook_pos'};
13587:                             $position =~ s/\D+//g;
13588:                             if ($position ne '') {
13589:                                 $allpos{$type}[$position] = $newbook{$type};
13590:                             }
13591:                         }
13592:                     } else {
13593:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
13594:                     }
13595:                 }
13596:             } 
13597:         }
13598:         if (ref($domconfig{$action}) eq 'HASH') {
13599:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
13600:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
13601:                     $changes{'notify'}{'approval'} = 1;
13602:                 }
13603:             } else {
13604:                 if ($confhash{'notify'}{'approval'}) {
13605:                     $changes{'notify'}{'approval'} = 1;
13606:                 }
13607:             }
13608:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
13609:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
13610:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
13611:                         unless ($confhash{'uniquecode'}{$crstype}) {
13612:                             $changes{'uniquecode'} = 1;
13613:                         }
13614:                     }
13615:                     unless ($changes{'uniquecode'}) {
13616:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
13617:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
13618:                                 $changes{'uniquecode'} = 1;
13619:                             }
13620:                         }
13621:                     }
13622:                } else {
13623:                    $changes{'uniquecode'} = 1;
13624:                }
13625:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
13626:                 $changes{'uniquecode'} = 1;
13627:             }
13628:             if ($context eq 'requestcourses') {
13629:                 foreach my $type ('textbooks','templates') {
13630:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
13631:                         my %deletions;
13632:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
13633:                         if (@todelete) {
13634:                             map { $deletions{$_} = 1; } @todelete;
13635:                         }
13636:                         my %imgdeletions;
13637:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
13638:                         if (@todeleteimages) {
13639:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
13640:                         }
13641:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
13642:                         for (my $i=0; $i<=$maxnum; $i++) {
13643:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
13644:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
13645:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
13646:                                 if ($deletions{$key}) {
13647:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
13648:                                         #FIXME need to obsolete item in RES space
13649:                                     }
13650:                                     next;
13651:                                 } else {
13652:                                     my $newpos = $env{'form.'.$itemid};
13653:                                     $newpos =~ s/\D+//g;
13654:                                     foreach my $item ('subject','title','publisher','author') {
13655:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
13656:                                                  ($type eq 'templates'));
13657:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
13658:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
13659:                                             $changes{$type}{$key} = 1;
13660:                                         }
13661:                                     }
13662:                                     $allpos{$type}[$newpos] = $key;
13663:                                 }
13664:                                 if ($imgdeletions{$key}) {
13665:                                     $changes{$type}{$key} = 1;
13666:                                     #FIXME need to obsolete item in RES space
13667:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
13668:                                     my ($cdom,$cnum) = split(/_/,$key);
13669:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
13670:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
13671:                                     } else {
13672:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
13673:                                                                                       $cdom,$cnum,$type,$configuserok,
13674:                                                                                       $switchserver,$author_ok);
13675:                                         if ($imgurl) {
13676:                                             $confhash{$type}{$key}{'image'} = $imgurl;
13677:                                             $changes{$type}{$key} = 1; 
13678:                                         }
13679:                                         if ($error) {
13680:                                             &Apache::lonnet::logthis($error);
13681:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13682:                                         }
13683:                                     }
13684:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
13685:                                     $confhash{$type}{$key}{'image'} = 
13686:                                         $domconfig{$action}{$type}{$key}{'image'};
13687:                                 }
13688:                             }
13689:                         }
13690:                     }
13691:                 }
13692:             }
13693:         } else {
13694:             if ($confhash{'notify'}{'approval'}) {
13695:                 $changes{'notify'}{'approval'} = 1;
13696:             }
13697:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
13698:                 $changes{'uniquecode'} = 1;
13699:             }
13700:         }
13701:         if ($context eq 'requestcourses') {
13702:             foreach my $type ('textbooks','templates') {
13703:                 if ($newbook{$type}) {
13704:                     $changes{$type}{$newbook{$type}} = 1;
13705:                     foreach my $item ('subject','title','publisher','author') {
13706:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
13707:                                  ($type eq 'template'));
13708:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
13709:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
13710:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
13711:                         }
13712:                     }
13713:                     if ($type eq 'textbooks') {
13714:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
13715:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
13716:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
13717:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
13718:                             } else {
13719:                                 my ($imageurl,$error) =
13720:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
13721:                                                             $configuserok,$switchserver,$author_ok);
13722:                                 if ($imageurl) {
13723:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
13724:                                 }
13725:                                 if ($error) {
13726:                                     &Apache::lonnet::logthis($error);
13727:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13728:                                 }
13729:                             }
13730:                         }
13731:                     }
13732:                 }
13733:                 if (@{$allpos{$type}} > 0) {
13734:                     my $idx = 0;
13735:                     foreach my $item (@{$allpos{$type}}) {
13736:                         if ($item ne '') {
13737:                             $confhash{$type}{$item}{'order'} = $idx;
13738:                             if (ref($domconfig{$action}) eq 'HASH') {
13739:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
13740:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
13741:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
13742:                                             $changes{$type}{$item} = 1;
13743:                                         }
13744:                                     }
13745:                                 }
13746:                             }
13747:                             $idx ++;
13748:                         }
13749:                     }
13750:                 }
13751:             }
13752:             if (ref($validationitemsref) eq 'ARRAY') {
13753:                 foreach my $item (@{$validationitemsref}) {
13754:                     if ($item eq 'fields') {
13755:                         my @changed;
13756:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
13757:                         if (@{$confhash{'validation'}{$item}} > 0) {
13758:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
13759:                         }
13760:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13761:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13762:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
13763:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
13764:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
13765:                                 } else {
13766:                                     @changed = @{$confhash{'validation'}{$item}};
13767:                                 }
13768:                             } else {
13769:                                 @changed = @{$confhash{'validation'}{$item}};
13770:                             }
13771:                         } else {
13772:                             @changed = @{$confhash{'validation'}{$item}};
13773:                         }
13774:                         if (@changed) {
13775:                             if ($confhash{'validation'}{$item}) {
13776:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
13777:                             } else {
13778:                                 $changes{'validation'}{$item} = &mt('None');
13779:                             }
13780:                         }
13781:                     } else {
13782:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
13783:                         if ($item eq 'markup') {
13784:                             if ($env{'form.requestcourses_validation_'.$item}) {
13785:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
13786:                             }
13787:                         }
13788:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13789:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13790:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
13791:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13792:                                 }
13793:                             } else {
13794:                                 if ($confhash{'validation'}{$item} ne '') {
13795:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13796:                                 }
13797:                             }
13798:                         } else {
13799:                             if ($confhash{'validation'}{$item} ne '') {
13800:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13801:                             }
13802:                         }
13803:                     }
13804:                 }
13805:             }
13806:             if ($env{'form.validationdc'}) {
13807:                 my $newval = $env{'form.validationdc'};
13808:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
13809:                 if (exists($domcoords{$newval})) {
13810:                     $confhash{'validation'}{'dc'} = $newval;
13811:                 }
13812:             }
13813:             if (ref($confhash{'validation'}) eq 'HASH') {
13814:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13815:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13816:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
13817:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
13818:                                 if ($confhash{'validation'}{'dc'} eq '') {
13819:                                     $changes{'validation'}{'dc'} = &mt('None');
13820:                                 } else {
13821:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13822:                                 }
13823:                             }
13824:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
13825:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13826:                         }
13827:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
13828:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13829:                     }
13830:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
13831:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13832:                 }
13833:             } else {
13834:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13835:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13836:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
13837:                             $changes{'validation'}{'dc'} = &mt('None');
13838:                         }
13839:                     }
13840:                 }
13841:             }
13842:         }
13843:     } else {
13844:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
13845:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
13846:     }
13847:     foreach my $item (@usertools) {
13848:         foreach my $type (@{$types},'default','_LC_adv') {
13849:             my $unset; 
13850:             if ($context eq 'requestcourses') {
13851:                 $unset = '0';
13852:                 if ($type eq '_LC_adv') {
13853:                     $unset = '';
13854:                 }
13855:                 if ($confhash{$item}{$type} eq 'autolimit') {
13856:                     $confhash{$item}{$type} .= '=';
13857:                     unless ($limithash{$item}{$type} =~ /\D/) {
13858:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
13859:                     }
13860:                 }
13861:             } elsif ($context eq 'requestauthor') {
13862:                 $unset = '0';
13863:                 if ($type eq '_LC_adv') {
13864:                     $unset = '';
13865:                 }
13866:             } else {
13867:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
13868:                     $confhash{$item}{$type} = 1;
13869:                 } else {
13870:                     $confhash{$item}{$type} = 0;
13871:                 }
13872:             }
13873:             if (ref($domconfig{$action}) eq 'HASH') {
13874:                 if ($action eq 'requestauthor') {
13875:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
13876:                         $changes{$type} = 1;
13877:                     }
13878:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
13879:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
13880:                         $changes{$item}{$type} = 1;
13881:                     }
13882:                 } else {
13883:                     if ($context eq 'requestcourses') {
13884:                         if ($confhash{$item}{$type} ne $unset) {
13885:                             $changes{$item}{$type} = 1;
13886:                         }
13887:                     } else {
13888:                         if (!$confhash{$item}{$type}) {
13889:                             $changes{$item}{$type} = 1;
13890:                         }
13891:                     }
13892:                 }
13893:             } else {
13894:                 if ($context eq 'requestcourses') {
13895:                     if ($confhash{$item}{$type} ne $unset) {
13896:                         $changes{$item}{$type} = 1;
13897:                     }
13898:                 } elsif ($context eq 'requestauthor') {
13899:                     if ($confhash{$type} ne $unset) {
13900:                         $changes{$type} = 1;
13901:                     }
13902:                 } else {
13903:                     if (!$confhash{$item}{$type}) {
13904:                         $changes{$item}{$type} = 1;
13905:                     }
13906:                 }
13907:             }
13908:         }
13909:     }
13910:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
13911:         if (ref($domconfig{'quotas'}) eq 'HASH') {
13912:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
13913:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
13914:                     if (exists($confhash{'defaultquota'}{$key})) {
13915:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
13916:                             $changes{'defaultquota'}{$key} = 1;
13917:                         }
13918:                     } else {
13919:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
13920:                     }
13921:                 }
13922:             } else {
13923:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
13924:                     if (exists($confhash{'defaultquota'}{$key})) {
13925:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
13926:                             $changes{'defaultquota'}{$key} = 1;
13927:                         }
13928:                     } else {
13929:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
13930:                     }
13931:                 }
13932:             }
13933:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
13934:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
13935:                     if (exists($confhash{'authorquota'}{$key})) {
13936:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
13937:                             $changes{'authorquota'}{$key} = 1;
13938:                         }
13939:                     } else {
13940:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
13941:                     }
13942:                 }
13943:             }
13944:         }
13945:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
13946:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
13947:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
13948:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
13949:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
13950:                             $changes{'defaultquota'}{$key} = 1;
13951:                         }
13952:                     } else {
13953:                         if (!exists($domconfig{'quotas'}{$key})) {
13954:                             $changes{'defaultquota'}{$key} = 1;
13955:                         }
13956:                     }
13957:                 } else {
13958:                     $changes{'defaultquota'}{$key} = 1;
13959:                 }
13960:             }
13961:         }
13962:         if (ref($confhash{'authorquota'}) eq 'HASH') {
13963:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
13964:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
13965:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
13966:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
13967:                             $changes{'authorquota'}{$key} = 1;
13968:                         }
13969:                     } else {
13970:                         $changes{'authorquota'}{$key} = 1;
13971:                     }
13972:                 } else {
13973:                     $changes{'authorquota'}{$key} = 1;
13974:                 }
13975:             }
13976:         }
13977:     }
13978: 
13979:     if ($context eq 'requestauthor') {
13980:         $domdefaults{'requestauthor'} = \%confhash;
13981:     } else {
13982:         foreach my $key (keys(%confhash)) {
13983:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
13984:                 $domdefaults{$key} = $confhash{$key};
13985:             }
13986:         }
13987:     }
13988: 
13989:     my %quotahash = (
13990:                       $action => { %confhash }
13991:                     );
13992:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
13993:                                              $dom);
13994:     if ($putresult eq 'ok') {
13995:         if (keys(%changes) > 0) {
13996:             my $cachetime = 24*60*60;
13997:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13998:             if (ref($lastactref) eq 'HASH') {
13999:                 $lastactref->{'domdefaults'} = 1;
14000:             }
14001:             $resulttext = &mt('Changes made:').'<ul>';
14002:             unless (($context eq 'requestcourses') ||
14003:                     ($context eq 'requestauthor')) {
14004:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
14005:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
14006:                     foreach my $type (@{$types},'default') {
14007:                         if (defined($changes{'defaultquota'}{$type})) {
14008:                             my $typetitle = $usertypes->{$type};
14009:                             if ($type eq 'default') {
14010:                                 $typetitle = $othertitle;
14011:                             }
14012:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
14013:                         }
14014:                     }
14015:                     $resulttext .= '</ul></li>';
14016:                 }
14017:                 if (ref($changes{'authorquota'}) eq 'HASH') {
14018:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
14019:                     foreach my $type (@{$types},'default') {
14020:                         if (defined($changes{'authorquota'}{$type})) {
14021:                             my $typetitle = $usertypes->{$type};
14022:                             if ($type eq 'default') {
14023:                                 $typetitle = $othertitle;
14024:                             }
14025:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
14026:                         }
14027:                     }
14028:                     $resulttext .= '</ul></li>';
14029:                 }
14030:             }
14031:             my %newenv;
14032:             foreach my $item (@usertools) {
14033:                 my (%haschgs,%inconf);
14034:                 if ($context eq 'requestauthor') {
14035:                     %haschgs = %changes;
14036:                     %inconf = %confhash;
14037:                 } else {
14038:                     if (ref($changes{$item}) eq 'HASH') {
14039:                         %haschgs = %{$changes{$item}};
14040:                     }
14041:                     if (ref($confhash{$item}) eq 'HASH') {
14042:                         %inconf = %{$confhash{$item}};
14043:                     }
14044:                 }
14045:                 if (keys(%haschgs) > 0) {
14046:                     my $newacc = 
14047:                         &Apache::lonnet::usertools_access($env{'user.name'},
14048:                                                           $env{'user.domain'},
14049:                                                           $item,'reload',$context);
14050:                     if (($context eq 'requestcourses') ||
14051:                         ($context eq 'requestauthor')) {
14052:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
14053:                             $newenv{'environment.canrequest.'.$item} = $newacc;
14054:                         }
14055:                     } else {
14056:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
14057:                             $newenv{'environment.availabletools.'.$item} = $newacc;
14058:                         }
14059:                     }
14060:                     unless ($context eq 'requestauthor') {
14061:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
14062:                     }
14063:                     foreach my $type (@{$types},'default','_LC_adv') {
14064:                         if ($haschgs{$type}) {
14065:                             my $typetitle = $usertypes->{$type};
14066:                             if ($type eq 'default') {
14067:                                 $typetitle = $othertitle;
14068:                             } elsif ($type eq '_LC_adv') {
14069:                                 $typetitle = 'LON-CAPA Advanced Users'; 
14070:                             }
14071:                             if ($inconf{$type}) {
14072:                                 if ($context eq 'requestcourses') {
14073:                                     my $cond;
14074:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
14075:                                         if ($1 eq '') {
14076:                                             $cond = &mt('(Automatic processing of any request).');
14077:                                         } else {
14078:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
14079:                                         }
14080:                                     } else { 
14081:                                         $cond = $conditions{$inconf{$type}};
14082:                                     }
14083:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
14084:                                 } elsif ($context eq 'requestauthor') {
14085:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
14086:                                                              $titles{$inconf{$type}},$typetitle);
14087: 
14088:                                 } else {
14089:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
14090:                                 }
14091:                             } else {
14092:                                 if ($type eq '_LC_adv') {
14093:                                     if ($inconf{$type} eq '0') {
14094:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14095:                                     } else { 
14096:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
14097:                                     }
14098:                                 } else {
14099:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14100:                                 }
14101:                             }
14102:                         }
14103:                     }
14104:                     unless ($context eq 'requestauthor') {
14105:                         $resulttext .= '</ul></li>';
14106:                     }
14107:                 }
14108:             }
14109:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
14110:                 if (ref($changes{'notify'}) eq 'HASH') {
14111:                     if ($changes{'notify'}{'approval'}) {
14112:                         if (ref($confhash{'notify'}) eq 'HASH') {
14113:                             if ($confhash{'notify'}{'approval'}) {
14114:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
14115:                             } else {
14116:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
14117:                             }
14118:                         }
14119:                     }
14120:                 }
14121:             }
14122:             if ($action eq 'requestcourses') {
14123:                 my @offon = ('off','on');
14124:                 if ($changes{'uniquecode'}) {
14125:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
14126:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
14127:                         $resulttext .= '<li>'.
14128:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
14129:                                        '</li>';
14130:                     } else {
14131:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
14132:                                        '</li>';
14133:                     }
14134:                 }
14135:                 foreach my $type ('textbooks','templates') {
14136:                     if (ref($changes{$type}) eq 'HASH') {
14137:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
14138:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
14139:                             my %coursehash = &Apache::lonnet::coursedescription($key);
14140:                             my $coursetitle = $coursehash{'description'};
14141:                             my $position = $confhash{$type}{$key}{'order'} + 1;
14142:                             $resulttext .= '<li>';
14143:                             foreach my $item ('subject','title','publisher','author') {
14144:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
14145:                                          ($type eq 'templates'));
14146:                                 my $name = $item.':';
14147:                                 $name =~ s/^(\w)/\U$1/;
14148:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
14149:                             }
14150:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
14151:                             if ($type eq 'textbooks') {
14152:                                 if ($confhash{$type}{$key}{'image'}) {
14153:                                     $resulttext .= ' '.&mt('Image: [_1]',
14154:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
14155:                                                    ' alt="Textbook cover" />').'<br />';
14156:                                 }
14157:                             }
14158:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
14159:                         }
14160:                         $resulttext .= '</ul></li>';
14161:                     }
14162:                 }
14163:                 if (ref($changes{'validation'}) eq 'HASH') {
14164:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
14165:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
14166:                         foreach my $item (@{$validationitemsref}) {
14167:                             if (exists($changes{'validation'}{$item})) {
14168:                                 if ($item eq 'markup') {
14169:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14170:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
14171:                                 } else {
14172:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14173:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
14174:                                 }
14175:                             }
14176:                         }
14177:                         if (exists($changes{'validation'}{'dc'})) {
14178:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
14179:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
14180:                         }
14181:                     }
14182:                 }
14183:             }
14184:             $resulttext .= '</ul>';
14185:             if (keys(%newenv)) {
14186:                 &Apache::lonnet::appenv(\%newenv);
14187:             }
14188:         } else {
14189:             if ($context eq 'requestcourses') {
14190:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
14191:             } elsif ($context eq 'requestauthor') {
14192:                 $resulttext = &mt('No changes made to rights to request author space.');
14193:             } else {
14194:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
14195:             }
14196:         }
14197:     } else {
14198:         $resulttext = '<span class="LC_error">'.
14199: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14200:     }
14201:     if ($errors) {
14202:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
14203:                        '<ul>'.$errors.'</ul></p>';
14204:     }
14205:     return $resulttext;
14206: }
14207: 
14208: sub process_textbook_image {
14209:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
14210:     my $filename = $env{'form.'.$caller.'.filename'};
14211:     my ($error,$url);
14212:     my ($width,$height) = (50,50);
14213:     if ($configuserok eq 'ok') {
14214:         if ($switchserver) {
14215:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
14216:                          $switchserver);
14217:         } elsif ($author_ok eq 'ok') {
14218:             my $modified = [];
14219:             my ($result,$imageurl) =
14220:                 &Apache::lonconfigsettings::publishlogo($r,'upload',$caller,$dom,$confname,
14221:                                                         "$type/$cdom/$cnum/cover",$width,$height,
14222:                                                         '',$modified);
14223:             if ($result eq 'ok') {
14224:                 $url = $imageurl;
14225:                 &update_modify_urls($r,$modified);
14226:             } else {
14227:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14228:             }
14229:         } else {
14230:             $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);
14231:         }
14232:     } else {
14233:         $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);
14234:     }
14235:     return ($url,$error);
14236: }
14237: 
14238: sub modify_ltitools {
14239:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14240:     my (%currtoolsec,%secchanges,%newtoolsec,%newkeyset);
14241:     &fetch_secrets($dom,'toolsec',\%domconfig,\%currtoolsec,\%secchanges,\%newtoolsec,\%newkeyset);
14242: 
14243:     my $confname = $dom.'-domainconfig';
14244:     my $servadm = $r->dir_config('lonAdmEMail');
14245:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14246: 
14247:     my ($resulttext,$ltitoolsoutput,$is_home,$errors,%ltitoolschg,%newtoolsenc,%newltitools);
14248:     my $toolserror =
14249:         &Apache::courseprefs::process_ltitools($r,$dom,$confname,$domconfig{'ltitools'},\%ltitoolschg,'domain',
14250:                                                $lastactref,$configuserok,$switchserver,$author_ok);
14251: 
14252:     my $home = &Apache::lonnet::domain($dom,'primary');
14253:     unless (($home eq 'no_host') || ($home eq '')) {
14254:         my @ids=&Apache::lonnet::current_machine_ids();
14255:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; last; } }
14256:     }
14257: 
14258:     if (keys(%ltitoolschg)) {
14259:         foreach my $id (keys(%ltitoolschg)) {
14260:             if (ref($ltitoolschg{$id}) eq 'HASH') {
14261:                 foreach my $inner (keys(%{$ltitoolschg{$id}})) {
14262:                     if (($inner eq 'secret') || ($inner eq 'key')) {
14263:                         if ($is_home) {
14264:                             $newtoolsenc{$id}{$inner} = $ltitoolschg{$id}{$inner};
14265:                         }
14266:                     }
14267:                 }
14268:             }
14269:         }
14270:         $ltitoolsoutput = &Apache::courseprefs::store_ltitools($dom,'','domain',\%ltitoolschg,$domconfig{'ltitools'});
14271:         if (keys(%ltitoolschg)) {
14272:             %newltitools = %ltitoolschg;
14273:         }
14274:     }
14275:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
14276:         foreach my $id (%{$domconfig{'ltitools'}}) {
14277:             next if ($id !~ /^\d+$/);
14278:             unless (exists($ltitoolschg{$id})) {
14279:                 if (ref($domconfig{'ltitools'}{$id}) eq 'HASH') {
14280:                     foreach my $inner (keys(%{$domconfig{'ltitools'}{$id}})) {
14281:                         if (($inner eq 'secret') || ($inner eq 'key')) {
14282:                             if ($is_home) {
14283:                                 $newtoolsenc{$id}{$inner} = $domconfig{'ltitools'}{$id}{$inner};
14284:                             }
14285:                         } else {
14286:                             $newltitools{$id}{$inner} = $domconfig{'ltitools'}{$id}{$inner};
14287:                         }
14288:                     }
14289:                 } else {
14290:                     $newltitools{$id} = $domconfig{'ltitools'}{$id};
14291:                 }
14292:             }
14293:         }
14294:     }
14295:     if ($toolserror) {
14296:         $errors = '<li>'.$toolserror.'</li>';
14297:     }
14298:     if ((keys(%ltitoolschg) == 0) && (keys(%secchanges) == 0)) {
14299:         $resulttext = &mt('No changes made.');
14300:         if ($errors) {
14301:             $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
14302:                                  $errors.'</ul>';
14303:         }
14304:         return $resulttext;
14305:     }
14306:     my %ltitoolshash = (
14307:                           $action => { %newltitools }
14308:                        );
14309:     if (keys(%secchanges)) {
14310:         $ltitoolshash{'toolsec'} = \%newtoolsec;
14311:     }
14312:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,$dom);
14313:     if ($putresult eq 'ok') {
14314:         my %keystore;
14315:         if ($is_home) {
14316:             my %toolsenchash = (
14317:                                    $action => { %newtoolsenc }
14318:                                );
14319:             &Apache::lonnet::put_dom('encconfig',\%toolsenchash,$dom,undef,1);
14320:             my $cachetime = 24*60*60;
14321:             &Apache::lonnet::do_cache_new('ltitoolsenc',$dom,\%newtoolsenc,$cachetime);
14322:             &store_security($dom,'ltitools',\%secchanges,\%newkeyset,\%keystore,$lastactref);
14323:         }
14324:         $resulttext = &mt('Changes made:').'<ul>';
14325:         if (keys(%secchanges) > 0) {
14326:             $resulttext .= &lti_security_results($dom,'ltitools',\%secchanges,\%newtoolsec,\%newkeyset,\%keystore);
14327:         }
14328:         if (keys(%ltitoolschg) > 0) {
14329:             $resulttext .= $ltitoolsoutput;
14330:         }
14331:         my $cachetime = 24*60*60;
14332:         &Apache::lonnet::do_cache_new('ltitools',$dom,\%newltitools,$cachetime);
14333:         if (ref($lastactref) eq 'HASH') {
14334:             $lastactref->{'ltitools'} = 1;
14335:         }
14336:     } else {
14337:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14338:     }
14339:     if ($errors) {
14340:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
14341:                        $errors.'</ul></p>';
14342:     }
14343:     return $resulttext;
14344: }
14345: 
14346: sub fetch_secrets {
14347:     my ($dom,$context,$domconfig,$currsec,$secchanges,$newsec,$newkeyset) = @_;
14348:     my %keyset;
14349:     %{$currsec} = ();
14350:     $newsec->{'private'}{'keys'} = [];
14351:     $newsec->{'encrypt'} = {};
14352:     $newsec->{'rules'} = {};
14353:     if ($context eq 'ltisec') {
14354:         $newsec->{'linkprot'} = {};
14355:     }
14356:     if (ref($domconfig->{$context}) eq 'HASH') {
14357:         %{$currsec} = %{$domconfig->{$context}};
14358:         if ($context eq 'ltisec') {
14359:             if (ref($currsec->{'linkprot'}) eq 'HASH') {
14360:                 foreach my $id (keys(%{$currsec->{'linkprot'}})) {
14361:                     unless ($id =~ /^\d+$/) {
14362:                         delete($currsec->{'linkprot'}{$id});
14363:                     }
14364:                 }
14365:             }
14366:         }
14367:         if (ref($currsec->{'private'}) eq 'HASH') {
14368:             if (ref($currsec->{'private'}{'keys'}) eq 'ARRAY') {
14369:                 $newsec->{'private'}{'keys'} = $currsec->{'private'}{'keys'};
14370:                 map { $keyset{$_} = 1; } @{$currsec->{'private'}{'keys'}};
14371:             }
14372:         }
14373:     }
14374:     my @items= ('crs','dom');
14375:     if ($context eq 'ltisec') {
14376:         push(@items,'consumers');
14377:     }
14378:     foreach my $item (@items) {
14379:         my $formelement;
14380:         if (($context eq 'toolsec') || ($item eq 'consumers')) {
14381:             $formelement = 'form.'.$context.'_'.$item;
14382:         } else {
14383:             $formelement = 'form.'.$context.'_'.$item.'linkprot';
14384:         }
14385:         if ($env{$formelement}) {
14386:             $newsec->{'encrypt'}{$item} = 1;
14387:             if (ref($currsec->{'encrypt'}) eq 'HASH') {
14388:                 unless ($currsec->{'encrypt'}{$item}) {
14389:                     $secchanges->{'encrypt'} = 1;
14390:                 }
14391:             } else {
14392:                 $secchanges->{'encrypt'} = 1;
14393:             }
14394:         } elsif (ref($currsec->{'encrypt'}) eq 'HASH') {
14395:             if ($currsec->{'encrypt'}{$item}) {
14396:                 $secchanges->{'encrypt'} = 1;
14397:             }
14398:         }
14399:     }
14400:     my $secrets;
14401:     if ($context eq 'ltisec') {
14402:         $secrets = 'ltisecrets';
14403:     } else {
14404:         $secrets = 'toolsecrets';
14405:     }
14406:     unless (exists($currsec->{'rules'})) {
14407:         $currsec->{'rules'} = {};
14408:     }
14409:     &password_rule_changes($secrets,$newsec->{'rules'},$currsec->{'rules'},$secchanges);
14410: 
14411:     my @ids=&Apache::lonnet::current_machine_ids();
14412:     my %servers = &Apache::lonnet::get_servers($dom,'library');
14413: 
14414:     foreach my $hostid (keys(%servers)) {
14415:         if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
14416:             my $keyitem = 'form.'.$context.'_privkey_'.$hostid;
14417:             if (exists($env{$keyitem})) {
14418:                 $env{$keyitem} =~ s/(`)/'/g;
14419:                 if ($keyset{$hostid}) {
14420:                     if ($env{'form.'.$context.'_changeprivkey_'.$hostid}) {
14421:                         if ($env{$keyitem} ne '') {
14422:                             $secchanges->{'private'} = 1;
14423:                             $newkeyset->{$hostid} = $env{$keyitem};
14424:                         }
14425:                     }
14426:                 } elsif ($env{$keyitem} ne '') {
14427:                     unless (grep(/^\Q$hostid\E$/,@{$newsec->{'private'}{'keys'}})) {
14428:                         push(@{$newsec->{'private'}{'keys'}},$hostid);
14429:                     }
14430:                     $secchanges->{'private'} = 1;
14431:                     $newkeyset->{$hostid} = $env{$keyitem};
14432:                 }
14433:             }
14434:         }
14435:     }
14436: }
14437: 
14438: sub store_security {
14439:     my ($dom,$context,$secchanges,$newkeyset,$keystore) = @_;
14440:     return unless ((ref($secchanges) eq 'HASH') && (ref($newkeyset) eq 'HASH') &&
14441:                    (ref($keystore) eq 'HASH'));
14442:     if (keys(%{$secchanges})) {
14443:         if ($secchanges->{'private'}) {
14444:             my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
14445:             foreach my $hostid (keys(%{$newkeyset})) {
14446:                 my $storehash = {
14447:                                    key => $newkeyset->{$hostid},
14448:                                    who => $env{'user.name'}.':'.$env{'user.domain'},
14449:                                 };
14450:                 $keystore->{$hostid} = &Apache::lonnet::store_dom($storehash,$context,'private',
14451:                                                                   $dom,$hostid);
14452:             }
14453:         }
14454:     }
14455: }
14456: 
14457: sub lti_security_results {
14458:     my ($dom,$context,$secchanges,$newsec,$newkeyset,$keystore) = @_;
14459:     my $output;
14460:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
14461:     my $needs_update;
14462:     foreach my $item (keys(%{$secchanges})) {
14463:         if ($item eq 'encrypt') {
14464:             $needs_update = 1;
14465:             my %encrypted;
14466:             if ($context eq 'lti') {
14467:                 %encrypted = (
14468:                               crs  => {
14469:                                         on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
14470:                                         off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
14471:                                       },
14472:                               dom => {
14473:                                        on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
14474:                                        off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
14475:                                      },
14476:                               consumers => {
14477:                                              on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
14478:                                              off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
14479:                                            },
14480:                              );
14481:             } else {
14482:                 %encrypted = (
14483:                               crs  => {
14484:                                         on => &mt('Encryption of stored external tool secrets defined in courses enabled'),
14485:                                         off => &mt('Encryption of stored external tool secrets defined in courses disabled'),
14486:                                       },
14487:                               dom => {
14488:                                        on => &mt('Encryption of stored external tool secrets defined in domain enabled'),
14489:                                        off => &mt('Encryption of stored external tool secrets defined in domain disabled'),
14490:                                      },
14491:                              );
14492: 
14493:             }
14494:             my @types= ('crs','dom');
14495:             if ($context eq 'lti') {
14496:                 foreach my $type (@types) {
14497:                     undef($domdefaults{'linkprotenc_'.$type});
14498:                 }
14499:                 push(@types,'consumers');
14500:                 undef($domdefaults{'ltienc_consumers'});
14501:             } elsif ($context eq 'ltitools') {
14502:                 foreach my $type (@types) {
14503:                     undef($domdefaults{'toolenc_'.$type});
14504:                 }
14505:             }
14506:             foreach my $type (@types) {
14507:                 my $shown = $encrypted{$type}{'off'};
14508:                 if (ref($newsec->{$item}) eq 'HASH') {
14509:                     if ($newsec->{$item}{$type}) {
14510:                         if ($context eq 'lti') {
14511:                             if ($type eq 'consumers') {
14512:                                 $domdefaults{'ltienc_consumers'} = 1;
14513:                             } else {
14514:                                 $domdefaults{'linkprotenc_'.$type} = 1;
14515:                             }
14516:                         } elsif ($context eq 'ltitools') {
14517:                             $domdefaults{'toolenc_'.$type} = 1;
14518:                         }
14519:                         $shown = $encrypted{$type}{'on'};
14520:                     }
14521:                 }
14522:                 $output .= '<li>'.$shown.'</li>';
14523:             }
14524:         } elsif ($item eq 'rules') {
14525:             my %titles = &Apache::lonlocal::texthash(
14526:                                       min   => 'Minimum password length',
14527:                                       max   => 'Maximum password length',
14528:                                       chars => 'Required characters',
14529:                          );
14530:             foreach my $rule ('min','max') {
14531:                 if ($newsec->{rules}{$rule} eq '') {
14532:                     if ($rule eq 'min') {
14533:                         $output .= '<li>'.&mt('[_1] not set.',$titles{$rule});
14534:                                    ' '.&mt('Default of [_1] will be used',
14535:                                            $Apache::lonnet::passwdmin).'</li>';
14536:                     } else {
14537:                         $output .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
14538:                     }
14539:                 } else {
14540:                     $output .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newsec->{rules}{$rule}).'</li>';
14541:                 }
14542:             }
14543:             if (ref($newsec->{'rules'}{'chars'}) eq 'ARRAY') {
14544:                 if (@{$newsec->{'rules'}{'chars'}} > 0) {
14545:                     my %rulenames = &Apache::lonlocal::texthash(
14546:                                              uc => 'At least one upper case letter',
14547:                                              lc => 'At least one lower case letter',
14548:                                              num => 'At least one number',
14549:                                              spec => 'At least one non-alphanumeric',
14550:                                     );
14551:                     my $needed = '<ul><li>'.
14552:                                  join('</li><li>',map {$rulenames{$_} } @{$newsec->{'rules'}{'chars'}}).
14553:                                  '</li></ul>';
14554:                     $output .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
14555:                 } else {
14556:                     $output .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
14557:                 }
14558:             } else {
14559:                 $output .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
14560:             }
14561:         } elsif ($item eq 'private') {
14562:             $needs_update = 1;
14563:             if ($context eq 'lti') {
14564:                 undef($domdefaults{'ltiprivhosts'});
14565:             } elsif ($context eq 'ltitools') {
14566:                 undef($domdefaults{'toolprivhosts'});
14567:             }
14568:             if (keys(%{$newkeyset})) {
14569:                 my @privhosts;
14570:                 foreach my $hostid (sort(keys(%{$newkeyset}))) {
14571:                     if ($keystore->{$hostid} eq 'ok') {
14572:                         $output .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
14573:                         unless (grep(/^\Q$hostid\E$/,@privhosts)) {
14574:                             push(@privhosts,$hostid);
14575:                         }
14576:                     }
14577:                 }
14578:                 if (@privhosts) {
14579:                     if ($context eq 'lti') {
14580:                         $domdefaults{'ltiprivhosts'} = \@privhosts;
14581:                     } elsif ($context eq 'ltitools') {
14582:                         $domdefaults{'toolprivhosts'} = \@privhosts;
14583:                     }
14584:                 }
14585:             }
14586:         } elsif ($item eq 'linkprot') {
14587:             next;
14588:         }
14589:     }
14590:     if ($needs_update) {
14591:         my $cachetime = 24*60*60;
14592:         &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14593:     }
14594:     return $output;
14595: }
14596: 
14597: sub modify_proctoring {
14598:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14599:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14600:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
14601:     my $confname = $dom.'-domainconfig';
14602:     my $servadm = $r->dir_config('lonAdmEMail');
14603:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14604:     my %providernames = &proctoring_providernames();
14605:     my $maxnum = scalar(keys(%providernames));
14606: 
14607:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
14608:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
14609:     if (ref($requref) eq 'HASH') {
14610:         %requserfields = %{$requref};
14611:     }
14612:     if (ref($opturef) eq 'HASH') {
14613:         %optuserfields = %{$opturef};
14614:     }
14615:     if (ref($defref) eq 'HASH') {
14616:         %defaults = %{$defref};
14617:     }
14618:     if (ref($extref) eq 'HASH') {
14619:         %extended = %{$extref};
14620:     }
14621:     if (ref($crsref) eq 'HASH') {
14622:         %crsconf = %{$crsref};
14623:     }
14624:     if (ref($rolesref) eq 'ARRAY') {
14625:         @courseroles = @{$rolesref};
14626:     }
14627:     if (ref($ltiref) eq 'ARRAY') {
14628:         @ltiroles = @{$ltiref};
14629:     }
14630: 
14631:     if (ref($domconfig{$action}) eq 'HASH') {
14632:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
14633:         if (@todeleteimages) {
14634:             map { $imgdeletions{$_} = 1; } @todeleteimages;
14635:         }
14636:     }
14637:     my %customadds;
14638:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
14639:     if (@newcustom) {
14640:         map { $customadds{$_} = 1; } @newcustom;
14641:     }
14642:     foreach my $provider (sort(keys(%providernames))) {
14643:         $confhash{$provider} = {};
14644:         my $pos = $env{'form.proctoring_pos_'.$provider};
14645:         $pos =~ s/\D+//g;
14646:         $allpos[$pos] = $provider;
14647:         my (%current,%currentenc);
14648:         my $showroles = 0;
14649:         if (ref($domconfig{$action}) eq 'HASH') {
14650:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
14651:                 %current = %{$domconfig{$action}{$provider}};
14652:                 foreach my $item ('key','secret') { 
14653:                     $currentenc{$item} = $current{$item};
14654:                     delete($current{$item});
14655:                 }
14656:             }
14657:         }
14658:         if ($env{'form.proctoring_available_'.$provider}) {
14659:             $confhash{$provider}{'available'} = 1;
14660:             unless ($current{'available'}) {
14661:                 $changes{$provider} = 1;
14662:             }
14663:         } else {
14664:             %{$confhash{$provider}} = %current;
14665:             %{$encconfhash{$provider}} = %currentenc;
14666:             $confhash{$provider}{'available'} = 0;
14667:             if ($current{'available'}) {
14668:                 $changes{$provider} = 1;
14669:             }
14670:         }
14671:         if ($confhash{$provider}{'available'}) {
14672:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
14673:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
14674:                 if ($field eq 'lifetime') {
14675:                     if ($possval =~ /^\d+$/) {
14676:                         $confhash{$provider}{$field} = $possval;
14677:                     }
14678:                 } elsif ($field eq 'version') {
14679:                     if ($possval =~ /^\d+\.\d+$/) {
14680:                         $confhash{$provider}{$field} = $possval;
14681:                     }
14682:                 } elsif ($field eq 'sigmethod') {
14683:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
14684:                         $confhash{$provider}{$field} = $possval;
14685:                     }
14686:                 } elsif ($field eq 'url') {
14687:                     $confhash{$provider}{$field} = $possval;
14688:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
14689:                     $encconfhash{$provider}{$field} = $possval;
14690:                     unless ($currentenc{$field} eq $possval) {
14691:                         $changes{$provider} = 1;
14692:                     }
14693:                 }
14694:                 unless (($field eq 'key') || ($field eq 'secret')) {
14695:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
14696:                         $changes{$provider} = 1;
14697:                     }
14698:                 }
14699:             }
14700:             if ($imgdeletions{$provider}) {
14701:                 $changes{$provider} = 1;
14702:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
14703:                 my ($imageurl,$error) =
14704:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
14705:                                               $configuserok,$switchserver,$author_ok);
14706:                 if ($imageurl) {
14707:                     $confhash{$provider}{'image'} = $imageurl;
14708:                     $changes{$provider} = 1; 
14709:                 }
14710:                 if ($error) {
14711:                     &Apache::lonnet::logthis($error);
14712:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14713:                 }
14714:             } elsif (exists($current{'image'})) {
14715:                 $confhash{$provider}{'image'} = $current{'image'};
14716:             }
14717:             if (ref($requserfields{$provider}) eq 'ARRAY') {
14718:                 if (@{$requserfields{$provider}} > 0) {
14719:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
14720:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
14721:                             $confhash{$provider}{'incdom'} = 1;
14722:                         }
14723:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
14724:                             $changes{$provider} = 1;
14725:                         }
14726:                     }
14727:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
14728:                         $showroles = 1;
14729:                     }
14730:                 }
14731:             }
14732:             $confhash{$provider}{'fields'} = [];
14733:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
14734:                 if (@{$optuserfields{$provider}} > 0) {
14735:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
14736:                     foreach my $field (@{$optuserfields{$provider}}) {
14737:                         if (grep(/^\Q$field\E$/,@optfields)) {
14738:                             push(@{$confhash{$provider}{'fields'}},$field);
14739:                         }
14740:                     }
14741:                 }
14742:                 if (ref($current{'fields'}) eq 'ARRAY') {
14743:                     unless ($changes{$provider}) {
14744:                         my @new = sort(@{$confhash{$provider}{'fields'}});
14745:                         my @old = sort(@{$current{'fields'}}); 
14746:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14747:                         if (@diffs) {
14748:                             $changes{$provider} = 1;
14749:                         }
14750:                     }
14751:                 } elsif (@{$confhash{$provider}{'fields'}}) {
14752:                     $changes{$provider} = 1;
14753:                 }
14754:             }
14755:             if (ref($defaults{$provider}) eq 'ARRAY') {  
14756:                 if (@{$defaults{$provider}} > 0) {
14757:                     my %options;
14758:                     if (ref($extended{$provider}) eq 'HASH') {
14759:                         %options = %{$extended{$provider}};
14760:                     }
14761:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
14762:                     foreach my $field (@{$defaults{$provider}}) {
14763:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
14764:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
14765:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
14766:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
14767:                             }
14768:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
14769:                             foreach my $inner (keys(%{$options{$field}})) {
14770:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
14771:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
14772:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
14773:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
14774:                                     }
14775:                                 } else {
14776:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
14777:                                 }
14778:                             }
14779:                         } else {
14780:                             if (grep(/^\Q$field\E$/,@checked)) {
14781:                                 push(@{$confhash{$provider}{'defaults'}},$field);
14782:                             }
14783:                         }
14784:                     }
14785:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
14786:                         if (ref($current{'defaults'}) eq 'ARRAY') {
14787:                             unless ($changes{$provider}) {
14788:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
14789:                                 my @old = sort(@{$current{'defaults'}});
14790:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14791:                                 if (@diffs) {
14792:                                     $changes{$provider} = 1; 
14793:                                 }
14794:                             }
14795:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
14796:                             if (@{$current{'defaults'}}) {
14797:                                 $changes{$provider} = 1;
14798:                             }
14799:                         }
14800:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
14801:                         if (ref($current{'defaults'}) eq 'HASH') {
14802:                             unless ($changes{$provider}) {
14803:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
14804:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
14805:                                         $changes{$provider} = 1;
14806:                                         last;
14807:                                     }
14808:                                 }
14809:                             }
14810:                             unless ($changes{$provider}) {
14811:                                 foreach my $key (keys(%{$current{'defaults'}})) {
14812:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
14813:                                         $changes{$provider} = 1;
14814:                                         last;
14815:                                     }
14816:                                 }
14817:                             }
14818:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
14819:                             $changes{$provider} = 1;
14820:                         }
14821:                     }
14822:                 }
14823:             }
14824:             if (ref($crsconf{$provider}) eq 'ARRAY') {
14825:                 if (@{$crsconf{$provider}} > 0) {
14826:                     $confhash{$provider}{'crsconf'} = [];
14827:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
14828:                     foreach my $crsfield (@{$crsconf{$provider}}) {
14829:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
14830:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
14831:                         }
14832:                     }
14833:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
14834:                         unless ($changes{$provider}) {  
14835:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
14836:                             my @old = sort(@{$current{'crsconf'}});
14837:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14838:                             if (@diffs) {
14839:                                 $changes{$provider} = 1;
14840:                             }
14841:                         }
14842:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
14843:                         $changes{$provider} = 1;
14844:                     }
14845:                 }
14846:             }
14847:             if ($showroles) {
14848:                 $confhash{$provider}{'roles'} = {};
14849:                 foreach my $role (@courseroles) {
14850:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
14851:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
14852:                         $confhash{$provider}{'roles'}{$role} = $poss;
14853:                     }
14854:                 }
14855:                 unless ($changes{$provider}) {
14856:                     if (ref($current{'roles'}) eq 'HASH') {
14857:                         foreach my $role (keys(%{$current{'roles'}})) {
14858:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
14859:                                 $changes{$provider} = 1;
14860:                                 last
14861:                             }
14862:                         }
14863:                         unless ($changes{$provider}) {
14864:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
14865:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
14866:                                     $changes{$provider} = 1;
14867:                                     last;
14868:                                 }
14869:                             }
14870:                         }
14871:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
14872:                         $changes{$provider} = 1;
14873:                     }
14874:                 }
14875:             }
14876:             if (ref($current{'custom'}) eq 'HASH') {
14877:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
14878:                 foreach my $key (keys(%{$current{'custom'}})) {
14879:                     if (grep(/^\Q$key\E$/,@customdels)) {
14880:                         $changes{$provider} = 1;
14881:                     } else {
14882:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
14883:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
14884:                             $changes{$provider} = 1;
14885:                         }
14886:                     }
14887:                 }
14888:             }
14889:             if ($customadds{$provider}) {
14890:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
14891:                 $name =~ s/(`)/'/g;
14892:                 $name =~ s/^\s+//;
14893:                 $name =~ s/\s+$//;
14894:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
14895:                 $value =~ s/(`)/'/g;
14896:                 $value =~ s/^\s+//;
14897:                 $value =~ s/\s+$//;
14898:                 if ($name ne '') {
14899:                     $confhash{$provider}{'custom'}{$name} = $value;
14900:                     $changes{$provider} = 1;
14901:                 }
14902:             }
14903:         }
14904:     }
14905:     if (@allpos > 0) {
14906:         my $idx = 0;
14907:         foreach my $provider (@allpos) {
14908:             if ($provider ne '') {
14909:                 $confhash{$provider}{'order'} = $idx;
14910:                 unless ($changes{$provider}) {
14911:                     if (ref($domconfig{$action}) eq 'HASH') {
14912:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
14913:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
14914:                                 $changes{$provider} = 1;
14915:                             }
14916:                         }
14917:                     }
14918:                 }
14919:                 $idx ++;
14920:             }
14921:         }
14922:     }
14923:     my %proc_hash = (
14924:                           $action => { %confhash }
14925:                        );
14926:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
14927:                                              $dom);
14928:     if ($putresult eq 'ok') {
14929:         my %proc_enchash = (
14930:                              $action => { %encconfhash }
14931:                          );
14932:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom,undef,1);
14933:         if (keys(%changes) > 0) {
14934:             my $cachetime = 24*60*60;
14935:             my %procall = %confhash;
14936:             foreach my $provider (keys(%procall)) {
14937:                 if (ref($encconfhash{$provider}) eq 'HASH') {
14938:                     foreach my $key ('key','secret') {
14939:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
14940:                     }
14941:                 }
14942:             }
14943:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
14944:             if (ref($lastactref) eq 'HASH') {
14945:                 $lastactref->{'proctoring'} = 1;
14946:             }
14947:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
14948:             my %bynum;
14949:             foreach my $provider (sort(keys(%changes))) {
14950:                 my $position = $confhash{$provider}{'order'};
14951:                 $bynum{$position} = $provider;
14952:             }
14953:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
14954:                 my $provider = $bynum{$pos};
14955:                 my %lt = &proctoring_titles($provider);
14956:                 my %fieldtitles = &proctoring_fieldtitles($provider);
14957:                 if (!$confhash{$provider}{'available'}) {
14958:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
14959:                 } else {
14960:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
14961:                     if ($confhash{$provider}{'image'}) {
14962:                         $resulttext .= '&nbsp;'.
14963:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
14964:                                        ' alt="'.&mt('Proctoring icon').'" />';
14965:                     }
14966:                     $resulttext .= '<ul>';
14967:                     my $position = $pos + 1;
14968:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
14969:                     foreach my $key ('version','sigmethod','url','lifetime') {
14970:                         if ($confhash{$provider}{$key} ne '') {
14971:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
14972:                         }
14973:                     }
14974:                     if ($encconfhash{$provider}{'key'} ne '') {
14975:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
14976:                     }
14977:                     if ($encconfhash{$provider}{'secret'} ne '') {
14978:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
14979:                         my $num = length($encconfhash{$provider}{'secret'});
14980:                         $resulttext .= ('*'x$num).'</li>';
14981:                     }
14982:                     my (@fields,$showroles);
14983:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14984:                         push(@fields,@{$requserfields{$provider}});
14985:                     }
14986:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
14987:                         push(@fields,@{$confhash{$provider}{'fields'}});
14988:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
14989:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
14990:                     }
14991:                     if (@fields) {
14992:                         if (grep(/^roles$/,@fields)) {
14993:                             $showroles = 1;
14994:                         }
14995:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
14996:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
14997:                     }
14998:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14999:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
15000:                             if ($confhash{$provider}{'incdom'}) {
15001:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
15002:                             } else { 
15003:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
15004:                             }
15005:                         }
15006:                     }
15007:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15008:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
15009:                             $resulttext .= '<li>'.$lt{'defa'};
15010:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
15011:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
15012:                             }
15013:                             $resulttext =~ s/,$//;
15014:                             $resulttext .= '</li>';
15015:                         }
15016:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15017:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
15018:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
15019:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
15020:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
15021:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
15022:                                 }
15023:                             }
15024:                             $resulttext .= '</ul></li>';
15025:                         }
15026:                     }
15027:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
15028:                         if (@{$crsconf{$provider}} > 0) {
15029:                             $resulttext .= '<li>'.&mt('Configurable in course:');
15030:                             my $numconfig = 0;
15031:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
15032:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
15033:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
15034:                                         $numconfig ++;
15035:                                         if ($provider eq 'examity') {
15036:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
15037:                                         } else {
15038:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
15039:                                         }
15040:                                     }
15041:                                     $resulttext =~ s/,$//;
15042:                                 }
15043:                             }
15044:                             if (!$numconfig) {
15045:                                 $resulttext .= '&nbsp;'.&mt('None');
15046:                             }
15047:                             $resulttext .= '</li>';
15048:                         }
15049:                     }
15050:                     if ($showroles) {
15051:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
15052:                             my $rolemaps;
15053:                             foreach my $role (@courseroles) {
15054:                                 if ($confhash{$provider}{'roles'}{$role}) {
15055:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15056:                                                  $confhash{$provider}{'roles'}{$role}.',';
15057:                                 }
15058:                             }
15059:                             if ($rolemaps) {
15060:                                 $rolemaps =~ s/,$//;
15061:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15062:                             }
15063:                         }
15064:                     }
15065:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
15066:                         my $customlist;
15067:                         if (keys(%{$confhash{$provider}{'custom'}})) {
15068:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
15069:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
15070:                             }
15071:                             $customlist =~ s/,$//;
15072:                         }
15073:                         if ($customlist) {
15074:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15075:                         }
15076:                     } 
15077:                     $resulttext .= '</ul></li>';
15078:                 }
15079:             }
15080:             $resulttext .= '</ul>';
15081:         } else {
15082:             $resulttext = &mt('No changes made.');
15083:         }
15084:     } else {
15085:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15086:     }
15087:     if ($errors) {
15088:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15089:                        $errors.'</ul>';
15090:     }
15091:     return $resulttext;
15092: }
15093: 
15094: sub process_proctoring_image {
15095:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
15096:     my $filename = $env{'form.'.$caller.'.filename'};
15097:     my ($error,$url);
15098:     my ($width,$height) = (21,21);
15099:     if ($configuserok eq 'ok') {
15100:         if ($switchserver) {
15101:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
15102:                          $switchserver);
15103:         } elsif ($author_ok eq 'ok') {
15104:             my $modified = [];
15105:             my ($result,$imageurl,$madethumb) =
15106:                 &Apache::lonconfigsettings::publishlogo($r,'upload',$caller,$dom,$confname,
15107:                                                         "proctoring/$provider/icon",$width,$height,
15108:                                                         '',$modified);
15109:             if ($result eq 'ok') {
15110:                 if ($madethumb) {
15111:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15112:                     my $imagethumb = "$path/tn-".$imagefile;
15113:                     $url = $imagethumb;
15114:                 } else {
15115:                     $url = $imageurl;
15116:                 }
15117:                 &update_modify_urls($r,$modified);
15118:             } else {
15119:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15120:             }
15121:         } else {
15122:             $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);
15123:         }
15124:     } else {
15125:         $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);
15126:     }
15127:     return ($url,$error);
15128: }
15129: 
15130: sub modify_lti {
15131:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15132:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15133:     my ($newid,@allpos,%changes,%confhash,%ltienc,$errors,$resulttext);
15134:     my (%posslti,%posslticrs,%posscrstype);
15135:     my @courseroles = ('cc','in','ta','ep','st');
15136:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
15137:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
15138:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
15139:     my %coursetypetitles = &Apache::lonlocal::texthash (
15140:                                official   => 'Official',
15141:                                unofficial => 'Unofficial',
15142:                                community  => 'Community',
15143:                                textbook   => 'Textbook',
15144:                                placement  => 'Placement Test',
15145:                                lti        => 'LTI Provider',
15146:     );
15147:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15148:     my %lt = &lti_names();
15149:     map { $posslti{$_} = 1; } @ltiroles;
15150:     map { $posslticrs{$_} = 1; } @lticourseroles;
15151:     map { $posscrstype{$_} = 1; } @coursetypes;
15152: 
15153:     my %menutitles = &ltimenu_titles();
15154:     my (%currltisec,%secchanges,%newltisec,%newltienc,%newkeyset);
15155: 
15156:     &fetch_secrets($dom,'ltisec',\%domconfig,\%currltisec,\%secchanges,\%newltisec,\%newkeyset);
15157: 
15158:     my (%linkprotchg,$linkprotoutput,$is_home);
15159:     my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
15160:                                                            \%linkprotchg,'domain');
15161:     my $home = &Apache::lonnet::domain($dom,'primary');
15162:     unless (($home eq 'no_host') || ($home eq '')) {
15163:         my @ids=&Apache::lonnet::current_machine_ids();
15164:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; } }
15165:     }
15166: 
15167:     if (keys(%linkprotchg)) {
15168:         $secchanges{'linkprot'} = 1;
15169:         my %oldlinkprot;
15170:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
15171:             %oldlinkprot = %{$currltisec{'linkprot'}};
15172:         }
15173:         foreach my $id (keys(%linkprotchg)) {
15174:             if (ref($linkprotchg{$id}) eq 'HASH') {
15175:                 foreach my $inner (keys(%{$linkprotchg{$id}})) {
15176:                     if (($inner eq 'secret') || ($inner eq 'key')) {
15177:                         if ($is_home) {
15178:                             $newltienc{$id}{$inner} = $linkprotchg{$id}{$inner};
15179:                         }
15180:                     }
15181:                 }
15182:             } else {
15183:                 $newltisec{'linkprot'}{$id} = $linkprotchg{$id};
15184:             }
15185:         }
15186:         $linkprotoutput = &Apache::courseprefs::store_linkprot($dom,'','domain',\%linkprotchg,\%oldlinkprot);
15187:         if (keys(%linkprotchg)) {
15188:             %{$newltisec{'linkprot'}} = %linkprotchg;
15189:         }
15190:     }
15191:     if (ref($currltisec{'linkprot'}) eq 'HASH') {
15192:         foreach my $id (%{$currltisec{'linkprot'}}) {
15193:             next if ($id !~ /^\d+$/);
15194:             unless (exists($linkprotchg{$id})) {
15195:                 if (ref($currltisec{'linkprot'}{$id}) eq 'HASH') {
15196:                     foreach my $inner (keys(%{$currltisec{'linkprot'}{$id}})) {
15197:                         if (($inner eq 'secret') || ($inner eq 'key')) {
15198:                             if ($is_home) {
15199:                                 $newltienc{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
15200:                             }
15201:                         } else {
15202:                             $newltisec{'linkprot'}{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
15203:                         }
15204:                     }
15205:                 } else {
15206:                     $newltisec{'linkprot'}{$id} = $currltisec{'linkprot'}{$id};
15207:                 }
15208:             }
15209:         }
15210:     }
15211:     if ($proterror) {
15212:         $errors .= '<li>'.$proterror.'</li>';
15213:     }
15214:     my (@items,%deletions,%itemids);
15215:     if ($env{'form.lti_add'}) {
15216:         my $consumer = $env{'form.lti_consumer_add'};
15217:         $consumer =~ s/(`)/'/g;
15218:         ($newid,my $error) = &get_lti_id($dom,$consumer);
15219:         if ($newid) {
15220:             $itemids{'add'} = $newid;
15221:             push(@items,'add');
15222:             $changes{$newid} = 1;
15223:         } else {
15224:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
15225:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15226:         }
15227:     }
15228:     if (ref($domconfig{$action}) eq 'HASH') {
15229:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
15230:         if (@todelete) {
15231:             map { $deletions{$_} = 1; } @todelete;
15232:         }
15233:         my $maxnum = $env{'form.lti_maxnum'};
15234:         for (my $i=0; $i<$maxnum; $i++) {
15235:             my $itemid = $env{'form.lti_id_'.$i};
15236:             $itemid =~ s/\D+//g;
15237:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15238:                 if ($deletions{$itemid}) {
15239:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
15240:                 } else {
15241:                     push(@items,$i);
15242:                     $itemids{$i} = $itemid;
15243:                 }
15244:             }
15245:         }
15246:     }
15247:     my (%keystore,$secstored);
15248:     if ($is_home) {
15249:         &store_security($dom,'lti',\%secchanges,\%newkeyset,\%keystore);
15250:     }
15251: 
15252:     my ($cipher,$privnum);
15253:     if ((@items > 0) && ($is_home)) {
15254:         ($cipher,$privnum) = &get_priv_creds($dom,$home,$secchanges{'encrypt'},
15255:                                              $newltisec{'encrypt'},$keystore{$home});
15256:     }
15257:     foreach my $idx (@items) {
15258:         my $itemid = $itemids{$idx};
15259:         next unless ($itemid);
15260:         my %currlti;
15261:         unless ($idx eq 'add') {
15262:             if (ref($domconfig{$action}) eq 'HASH') {
15263:                 if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15264:                     %currlti = %{$domconfig{$action}{$itemid}};
15265:                 }
15266:             }
15267:         }
15268:         my $position = $env{'form.lti_pos_'.$itemid};
15269:         $position =~ s/\D+//g;
15270:         if ($position ne '') {
15271:             $allpos[$position] = $itemid;
15272:         }
15273:         foreach my $item ('consumer','lifetime','requser','crsinc') {
15274:             my $formitem = 'form.lti_'.$item.'_'.$idx;
15275:             $env{$formitem} =~ s/(`)/'/g;
15276:             if ($item eq 'lifetime') {
15277:                 $env{$formitem} =~ s/[^\d.]//g;
15278:             }
15279:             if ($env{$formitem} ne '') {
15280:                 $confhash{$itemid}{$item} = $env{$formitem};
15281:                 unless (($idx eq 'add') || ($changes{$itemid})) {
15282:                     if ($currlti{$item} ne $confhash{$itemid}{$item}) {
15283:                         $changes{$itemid} = 1;
15284:                     }
15285:                 }
15286:             }
15287:         }
15288:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
15289:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
15290:         }
15291:         if ($confhash{$itemid}{'requser'}) {
15292:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
15293:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid';
15294:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
15295:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
15296:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
15297:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
15298:                 $mapuser =~ s/(`)/'/g;
15299:                 $mapuser =~ s/^\s+|\s+$//g;
15300:                 $confhash{$itemid}{'mapuser'} = $mapuser;
15301:             }
15302:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
15303:             my @makeuser;
15304:             foreach my $ltirole (sort(@possmakeuser)) {
15305:                 if ($posslti{$ltirole}) {
15306:                     push(@makeuser,$ltirole);
15307:                 }
15308:             }
15309:             $confhash{$itemid}{'makeuser'} = \@makeuser;
15310:             if (@makeuser) {
15311:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
15312:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
15313:                     $confhash{$itemid}{'lcauth'} = $lcauth;
15314:                     if ($lcauth ne 'internal') {
15315:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
15316:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
15317:                         $lcauthparm =~ s/`//g;
15318:                         if ($lcauthparm ne '') {
15319:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
15320:                         }
15321:                     }
15322:                 } else {
15323:                     $confhash{$itemid}{'lcauth'} = 'lti';
15324:                 }
15325:             }
15326:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
15327:             if (@possinstdata) {
15328:                 foreach my $field (@possinstdata) {
15329:                     if (exists($fieldtitles{$field})) {
15330:                         push(@{$confhash{$itemid}{'instdata'}});
15331:                     }
15332:                 }
15333:             }
15334:             if ($env{'form.lti_callback_'.$idx}) {
15335:                 if ($env{'form.lti_callbackparam_'.$idx}) {
15336:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
15337:                     $callback =~ s/^\s+|\s+$//g;
15338:                     $confhash{$itemid}{'callback'} = $callback;
15339:                 }
15340:             }
15341:             foreach my $field ('topmenu','inlinemenu') {
15342:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
15343:                     $confhash{$itemid}{$field} = 1;
15344:                 }
15345:             }
15346:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
15347:                 $confhash{$itemid}{lcmenu} = [];
15348:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
15349:                 foreach my $field (@possmenu) {
15350:                     if (exists($menutitles{$field})) {
15351:                         if ($field eq 'grades') {
15352:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
15353:                         }
15354:                         push(@{$confhash{$itemid}{lcmenu}},$field);
15355:                     }
15356:                 }
15357:             }
15358:             if ($confhash{$itemid}{'crsinc'}) {
15359:                 if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
15360:                     ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
15361:                     $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
15362:                 } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
15363:                     my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
15364:                     $mapcrs =~ s/(`)/'/g;
15365:                     $mapcrs =~ s/^\s+|\s+$//g;
15366:                     $confhash{$itemid}{'mapcrs'} = $mapcrs;
15367:                 }
15368:                 my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
15369:                 my @crstypes;
15370:                 foreach my $type (sort(@posstypes)) {
15371:                     if ($posscrstype{$type}) {
15372:                         push(@crstypes,$type);
15373:                     }
15374:                 }
15375:                 $confhash{$itemid}{'mapcrstype'} = \@crstypes;
15376:                 if ($env{'form.lti_storecrs_'.$idx}) {
15377:                     $confhash{$itemid}{'storecrs'} = 1;
15378:                 }       
15379:                 if ($env{'form.lti_makecrs_'.$idx}) {
15380:                     $confhash{$itemid}{'makecrs'} = 1;
15381:                 }
15382:                 foreach my $ltirole (@lticourseroles) {
15383:                     my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
15384:                     if (grep(/^\Q$possrole\E$/,@courseroles)) {
15385:                         $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
15386:                     }
15387:                 }
15388:                 my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
15389:                 my @selfenroll;
15390:                 foreach my $type (sort(@possenroll)) {
15391:                     if ($posslticrs{$type}) {
15392:                         push(@selfenroll,$type);
15393:                     }
15394:                 }
15395:                 $confhash{$itemid}{'selfenroll'} = \@selfenroll;
15396:                 if ($env{'form.lti_crssec_'.$idx}) {
15397:                     if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
15398:                         $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
15399:                     } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
15400:                         my $section = $env{'form.lti_customsection_'.$idx};
15401:                         $section =~ s/(`)/'/g;
15402:                         $section =~ s/^\s+|\s+$//g;
15403:                         if ($section ne '') {
15404:                             $confhash{$itemid}{'section'} = $section;
15405:                         }
15406:                     }
15407:                 }
15408:                 foreach my $field ('passback','roster') {
15409:                     if ($env{'form.lti_'.$field.'_'.$idx}) {
15410:                         $confhash{$itemid}{$field} = 1;
15411:                     }
15412:                 }
15413:                 if ($env{'form.lti_passback_'.$idx}) {
15414:                     if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
15415:                         $confhash{$itemid}{'passbackformat'} = '1.0';
15416:                     } else {
15417:                         $confhash{$itemid}{'passbackformat'} = '1.1';
15418:                     }
15419:                 }
15420:             }
15421:             unless (($idx eq 'add') || ($changes{$itemid})) {
15422:                 if ($confhash{$itemid}{'crsinc'}) {
15423:                     foreach my $field ('mapcrs','storecrs','makecrs','section','passback','roster') {
15424:                         if ($currlti{$field} ne $confhash{$itemid}{$field}) {
15425:                             $changes{$itemid} = 1;
15426:                         }
15427:                     }
15428:                     unless ($changes{$itemid}) {
15429:                         if ($currlti{'passback'} eq $confhash{$itemid}{'passback'}) {
15430:                             if ($currlti{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
15431:                                 $changes{$itemid} = 1;
15432:                             }
15433:                         }
15434:                     }
15435:                     foreach my $field ('mapcrstype','selfenroll') {
15436:                         unless ($changes{$itemid}) {
15437:                             if (ref($currlti{$field}) eq 'ARRAY') {
15438:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
15439:                                     my @diffs = &Apache::loncommon::compare_arrays($currlti{$field},
15440:                                                                                    $confhash{$itemid}{$field});
15441:                                     if (@diffs) {
15442:                                         $changes{$itemid} = 1;
15443:                                     }
15444:                                 } elsif (@{$currlti{$field}} > 0) {
15445:                                     $changes{$itemid} = 1;
15446:                                 }
15447:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
15448:                                 if (@{$confhash{$itemid}{$field}} > 0) {
15449:                                     $changes{$itemid} = 1;
15450:                                 }
15451:                             }
15452:                         }
15453:                     }
15454:                     unless ($changes{$itemid}) {
15455:                         if (ref($currlti{'maproles'}) eq 'HASH') {
15456:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
15457:                                 foreach my $ltirole (keys(%{$currlti{'maproles'}})) {
15458:                                     if ($currlti{'maproles'}{$ltirole} ne 
15459:                                         $confhash{$itemid}{'maproles'}{$ltirole}) {
15460:                                         $changes{$itemid} = 1;
15461:                                         last;
15462:                                     }
15463:                                 }
15464:                                 unless ($changes{$itemid}) {
15465:                                     foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
15466:                                         if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
15467:                                             $currlti{'maproles'}{$ltirole}) {
15468:                                             $changes{$itemid} = 1;
15469:                                             last;
15470:                                         }
15471:                                     }
15472:                                 }
15473:                             } elsif (keys(%{$currlti{'maproles'}}) > 0) {
15474:                                 $changes{$itemid} = 1;
15475:                             }
15476:                         } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
15477:                             unless ($changes{$itemid}) {
15478:                                 if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
15479:                                     $changes{$itemid} = 1;
15480:                                 }
15481:                             }
15482:                         }
15483:                     }
15484:                 }
15485:                 unless ($changes{$itemid}) {
15486:                     foreach my $field ('mapuser','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
15487:                         if ($currlti{$field} ne $confhash{$itemid}{$field}) {
15488:                             $changes{$itemid} = 1;
15489:                         }
15490:                     }
15491:                     unless ($changes{$itemid}) {
15492:                         foreach my $field ('makeuser','lcmenu') {
15493:                             if (ref($currlti{$field}) eq 'ARRAY') {
15494:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
15495:                                     my @diffs = &Apache::loncommon::compare_arrays($currlti{$field},
15496:                                                                                    $confhash{$itemid}{$field});
15497:                                     if (@diffs) {
15498:                                         $changes{$itemid} = 1;
15499:                                     }
15500:                                 } elsif (@{$currlti{$field}} > 0) {
15501:                                     $changes{$itemid} = 1;
15502:                                 }
15503:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
15504:                                 if (@{$confhash{$itemid}{$field}} > 0) {
15505:                                     $changes{$itemid} = 1;
15506:                                 }
15507:                             }
15508:                         }
15509:                     }
15510:                 }
15511:             }
15512:         }
15513:         if ($is_home) {
15514:             my $keyitem = 'form.lti_key_'.$idx;
15515:             $env{$keyitem} =~ s/(`)/'/g;
15516:             if ($env{$keyitem} ne '') {
15517:                 $ltienc{$itemid}{'key'} = $env{$keyitem};
15518:                 unless ($changes{$itemid}) {
15519:                     if ($currlti{'key'} ne $env{$keyitem}) {
15520:                         $changes{$itemid} = 1;
15521:                     }
15522:                 }
15523:             }
15524:             my $secretitem = 'form.lti_secret_'.$idx;
15525:             $env{$secretitem} =~ s/(`)/'/g;
15526:             if ($currlti{'usable'}) {
15527:                 if ($env{'form.lti_changesecret_'.$idx}) {
15528:                     if ($env{$secretitem} ne '') {
15529:                         if ($privnum && $cipher) {
15530:                             $ltienc{$itemid}{'secret'} = $cipher->encrypt_hex($env{$secretitem});
15531:                             $confhash{$itemid}{'cipher'} = $privnum;
15532:                         } else {
15533:                             $ltienc{$itemid}{'secret'} = $env{$secretitem};
15534:                         }
15535:                         $changes{$itemid} = 1;
15536:                     }
15537:                 } else {
15538:                     $ltienc{$itemid}{'secret'} = $currlti{'secret'};
15539:                     $confhash{$itemid}{'cipher'} = $currlti{'cipher'};
15540:                 }
15541:                 if (ref($ltienc{$itemid}) eq 'HASH') {
15542:                     if (($ltienc{$itemid}{'key'} ne '') && ($ltienc{$itemid}{'secret'} ne '')) {
15543:                         $confhash{$itemid}{'usable'} = 1;
15544:                     }
15545:                 }
15546:             } elsif ($env{$secretitem} ne '') {
15547:                 if ($privnum && $cipher) {
15548:                     $ltienc{$itemid}{'secret'} = $cipher->encrypt_hex($env{$secretitem});
15549:                     $confhash{$itemid}{'cipher'} = $privnum;
15550:                 } else {
15551:                     $ltienc{$itemid}{'secret'} = $env{$secretitem};
15552:                 }
15553:                 if (ref($ltienc{$itemid}) eq 'HASH') {
15554:                     if (($ltienc{$itemid}{'key'} ne '') && ($ltienc{$itemid}{'key'} ne '')) {
15555:                         $confhash{$itemid}{'usable'} = 1;
15556:                     }
15557:                 }
15558:                 $changes{$itemid} = 1;
15559:             }
15560:         }
15561:         unless ($changes{$itemid}) {
15562:             foreach my $key (keys(%currlti)) {
15563:                 if (ref($currlti{$key}) eq 'HASH') {
15564:                     if (ref($confhash{$itemid}{$key}) eq 'HASH') {
15565:                         foreach my $innerkey (keys(%{$currlti{$key}})) {
15566:                             unless (exists($confhash{$itemid}{$key}{$innerkey})) {
15567:                                 $changes{$itemid} = 1;
15568:                                 last;
15569:                             }
15570:                         }
15571:                     } elsif (keys(%{$currlti{$key}}) > 0) {
15572:                         $changes{$itemid} = 1;
15573:                     }
15574:                 }
15575:                 last if ($changes{$itemid});
15576:             }
15577:         }
15578:     }
15579:     if (@allpos > 0) {
15580:         my $idx = 0;
15581:         foreach my $itemid (@allpos) {
15582:             if ($itemid ne '') {
15583:                 $confhash{$itemid}{'order'} = $idx;
15584:                 if (ref($domconfig{$action}) eq 'HASH') {
15585:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15586:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
15587:                             $changes{$itemid} = 1;
15588:                         }
15589:                     }
15590:                 }
15591:                 $idx ++;
15592:             }
15593:         }
15594:     }
15595: 
15596:     if ((keys(%changes) == 0) && (keys(%secchanges) == 0)) {
15597:         return &mt('No changes made.');
15598:     }
15599: 
15600:     my %ltihash = (
15601:                       $action => { %confhash }
15602:                   );
15603:     my %ltienchash;
15604: 
15605:     if ($is_home) {
15606:         %ltienchash = (
15607:                          $action => { %ltienc }
15608:                       );
15609:     }
15610:     if (keys(%secchanges)) {
15611:         $ltihash{'ltisec'} = \%newltisec;
15612:         if ($secchanges{'linkprot'}) {
15613:             if ($is_home) {
15614:                 $ltienchash{'linkprot'} = \%newltienc;
15615:             }
15616:         }
15617:     }
15618:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
15619:     if ($putresult eq 'ok') {
15620:         if (keys(%ltienchash)) {
15621:             &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
15622:         }
15623:         $resulttext = &mt('Changes made:').'<ul>';
15624:         if (keys(%secchanges) > 0) {
15625:             $resulttext .= &lti_security_results($dom,'lti',\%secchanges,\%newltisec,\%newkeyset,\%keystore);
15626:             if (exists($secchanges{'linkprot'})) {
15627:                 $resulttext .= $linkprotoutput;
15628:             }
15629:         }
15630:         if (keys(%changes) > 0) {
15631:             my $cachetime = 24*60*60;
15632:             &Apache::lonnet::do_cache_new('lti',$dom,\%confhash,$cachetime);
15633:             if (ref($lastactref) eq 'HASH') {
15634:                 $lastactref->{'lti'} = 1;
15635:             }
15636:             my %bynum;
15637:             foreach my $itemid (sort(keys(%changes))) {
15638:                 if (ref($confhash{$itemid}) eq 'HASH') {
15639:                     my $position = $confhash{$itemid}{'order'};
15640:                     $bynum{$position} = $itemid;
15641:                 }
15642:             }
15643:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15644:                 my $itemid = $bynum{$pos};
15645:                 if (ref($confhash{$itemid}) eq 'HASH') {
15646:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b><ul>';
15647:                     my $position = $pos + 1;
15648:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15649:                     foreach my $item ('version','lifetime') {
15650:                         if ($confhash{$itemid}{$item} ne '') {
15651:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
15652:                         }
15653:                     }
15654:                     if ($ltienc{$itemid}{'key'} ne '') {
15655:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$ltienc{$itemid}{'key'}.'</li>';
15656:                     }
15657:                     if ($ltienc{$itemid}{'secret'} ne '') {
15658:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;['.&mt('not shown').']</li>';
15659:                     }
15660:                     if ($confhash{$itemid}{'requser'}) {
15661:                         if ($confhash{$itemid}{'callback'}) {
15662:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
15663:                         } else {
15664:                             $resulttext .= '<li>'.&mt('Callback to logout LON-CAPA on log out from Consumer').'</li>';
15665:                         }
15666:                         if ($confhash{$itemid}{'mapuser'}) {
15667:                             my $shownmapuser;
15668:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
15669:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
15670:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
15671:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
15672:                             } else {
15673:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
15674:                             }
15675:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
15676:                         }
15677:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
15678:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
15679:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
15680:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
15681:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
15682:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
15683:                                 } else {
15684:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
15685:                                                        $confhash{$itemid}{'lcauth'});
15686:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
15687:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
15688:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
15689:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
15690:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
15691:                                         }
15692:                                     } else {
15693:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
15694:                                     }
15695:                                 }
15696:                                 $resulttext .= '</li>';
15697:                             } else {
15698:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
15699:                             }
15700:                         }
15701:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
15702:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
15703:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
15704:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
15705:                             } else {
15706:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
15707:                             }
15708:                         }
15709:                         foreach my $item ('topmenu','inlinemenu') {
15710:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
15711:                             if ($confhash{$itemid}{$item}) {
15712:                                 $resulttext .= &mt('Yes');
15713:                             } else {
15714:                                 $resulttext .= &mt('No');
15715:                             }
15716:                             $resulttext .= '</li>';
15717:                         }
15718:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
15719:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
15720:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
15721:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>';
15722:                             } else {
15723:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>';
15724:                             }
15725:                         }
15726:                         if ($confhash{$itemid}{'crsinc'}) {
15727:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
15728:                                 my $rolemaps;
15729:                                 foreach my $role (@ltiroles) {
15730:                                     if ($confhash{$itemid}{'maproles'}{$role}) {
15731:                                         $rolemaps .= ('&nbsp;'x2).$role.'='.
15732:                                                      &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
15733:                                                                                 'Course').',';
15734:                                     }
15735:                                 }
15736:                                 if ($rolemaps) {
15737:                                     $rolemaps =~ s/,$//;
15738:                                     $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15739:                                 }
15740:                             }
15741:                             if ($confhash{$itemid}{'mapcrs'}) {
15742:                                 $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
15743:                             }
15744:                             if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
15745:                                 if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
15746:                                     $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
15747:                                                    join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
15748:                                                    '</li>';
15749:                                 } else {
15750:                                     $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
15751:                                 }
15752:                             }
15753:                             if ($confhash{$itemid}{'storecrs'}) {
15754:                                 $resulttext .= '<li>'.&mt('Store mapping of course identifier to LON-CAPA CourseID').': '.$confhash{$itemid}{'storecrs'}.'</li>';
15755:                             }
15756:                             if ($confhash{$itemid}{'makecrs'}) {
15757:                                 $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
15758:                             } else {
15759:                                 $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
15760:                             }
15761:                             if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
15762:                                 if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
15763:                                     $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
15764:                                                               join(', ',@{$confhash{$itemid}{'selfenroll'}})).
15765:                                                    '</li>';
15766:                                 } else {
15767:                                     $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
15768:                                 }
15769:                             }
15770:                             if ($confhash{$itemid}{'section'}) {
15771:                                 if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
15772:                                     $resulttext .= '<li>'.&mt('User section from standard field:').
15773:                                                          ' (course_section_sourcedid)'.'</li>';  
15774:                                 } else {
15775:                                     $resulttext .= '<li>'.&mt('User section from:').' '.
15776:                                                           $confhash{$itemid}{'section'}.'</li>';
15777:                                 }
15778:                             } else {
15779:                                 $resulttext .= '<li>'.&mt('No section assignment').'</li>';
15780:                             }
15781:                             foreach my $item ('passback','roster','topmenu','inlinemenu') {
15782:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
15783:                                 if ($confhash{$itemid}{$item}) {
15784:                                     $resulttext .= &mt('Yes');
15785:                                     if ($item eq 'passback') {
15786:                                         if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
15787:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
15788:                                         } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
15789:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
15790:                                         }
15791:                                     }
15792:                                 } else {
15793:                                     $resulttext .= &mt('No');
15794:                                 }
15795:                                 $resulttext .= '</li>';
15796:                             }
15797:                             if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
15798:                                 if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
15799:                                     $resulttext .= '<li>'.&mt('Menu items:').' '.
15800:                                                    join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
15801:                                 } else {
15802:                                     $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
15803:                                 }
15804:                             }
15805:                         }
15806:                     }
15807:                     $resulttext .= '</ul></li>';
15808:                 }
15809:             }
15810:             if (keys(%deletions)) {
15811:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
15812:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
15813:                 }
15814:             }
15815:         }
15816:         $resulttext .= '</ul>';
15817:         if (ref($lastactref) eq 'HASH') {
15818:             if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
15819:                 $lastactref->{'domdefaults'} = 1;
15820:             }
15821:         }
15822:     } else {
15823:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15824:     }
15825:     if ($errors) {
15826:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15827:                        $errors.'</ul>';
15828:     }
15829:     return $resulttext;
15830: }
15831: 
15832: sub get_priv_creds {
15833:     my ($dom,$home,$encchg,$encrypt,$storedsec) = @_;
15834:     my ($needenc,$cipher,$privnum);
15835:     my %domdefs = &Apache::lonnet::get_domain_defaults($dom);
15836:     if (($encchg) && (ref($encrypt) eq 'HASH')) {
15837:         $needenc = $encrypt->{'consumers'} 
15838:     } else {
15839:         $needenc = $domdefs{'ltienc_consumers'};
15840:     }
15841:     if ($needenc) {
15842:         if (($storedsec eq 'ok') || ((ref($domdefs{'ltiprivhosts'}) eq 'ARRAY') &&
15843:                                      (grep(/^\Q$home\E$/,@{$domdefs{'ltiprivhosts'}})))) {
15844:                         my %privhash  = &Apache::lonnet::restore_dom('lti','private',$dom,$home,1);
15845:             my $privkey = $privhash{'key'};
15846:             $privnum = $privhash{'version'};
15847:             if (($privnum) && ($privkey ne '')) {
15848:                 $cipher = Crypt::CBC->new({'key'     => $privkey,
15849:                                           'cipher'  => 'DES'});
15850:             }
15851:         }
15852:     }
15853:     return ($cipher,$privnum);
15854: }
15855: 
15856: sub get_lti_id {
15857:     my ($domain,$consumer) = @_;
15858:     # get lock on lti db
15859:     my $lockhash = {
15860:                       lock => $env{'user.name'}.
15861:                               ':'.$env{'user.domain'},
15862:                    };
15863:     my $tries = 0;
15864:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
15865:     my ($id,$error);
15866: 
15867:     while (($gotlock ne 'ok') && ($tries<10)) {
15868:         $tries ++;
15869:         sleep (0.1);
15870:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
15871:     }
15872:     if ($gotlock eq 'ok') {
15873:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
15874:         if ($currids{'lock'}) {
15875:             delete($currids{'lock'});
15876:             if (keys(%currids)) {
15877:                 my @curr = sort { $a <=> $b } keys(%currids);
15878:                 if ($curr[-1] =~ /^\d+$/) {
15879:                     $id = 1 + $curr[-1];
15880:                 }
15881:             } else {
15882:                 $id = 1;
15883:             }
15884:             if ($id) {
15885:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
15886:                     $error = 'nostore';
15887:                 }
15888:             } else {
15889:                 $error = 'nonumber';
15890:             }
15891:         }
15892:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
15893:     } else {
15894:         $error = 'nolock';
15895:     }
15896:     return ($id,$error);
15897: }
15898: 
15899: sub modify_autoenroll {
15900:     my ($dom,$lastactref,%domconfig) = @_;
15901:     my ($resulttext,%changes);
15902:     my %currautoenroll;
15903:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
15904:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
15905:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
15906:         }
15907:     }
15908:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
15909:     my %title = ( run => 'Auto-enrollment active',
15910:                   sender => 'Sender for notification messages',
15911:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
15912:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
15913:     my @offon = ('off','on');
15914:     my $sender_uname = $env{'form.sender_uname'};
15915:     my $sender_domain = $env{'form.sender_domain'};
15916:     if ($sender_domain eq '') {
15917:         $sender_uname = '';
15918:     } elsif ($sender_uname eq '') {
15919:         $sender_domain = '';
15920:     }
15921:     my $coowners = $env{'form.autoassign_coowners'};
15922:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
15923:     $autofailsafe =~ s{^\s+|\s+$}{}g;
15924:     if ($autofailsafe =~ /\D/) {
15925:         undef($autofailsafe);
15926:     }
15927:     my $failsafe = $env{'form.autoenroll_failsafe'};
15928:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
15929:         $failsafe = 'off';
15930:         undef($autofailsafe);
15931:     }
15932:     my %autoenrollhash =  (
15933:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
15934:                                        'sender_uname' => $sender_uname,
15935:                                        'sender_domain' => $sender_domain,
15936:                                        'co-owners' => $coowners,
15937:                                        'autofailsafe' => $autofailsafe,
15938:                                        'failsafe' => $failsafe,
15939:                                 }
15940:                      );
15941:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
15942:                                              $dom);
15943:     if ($putresult eq 'ok') {
15944:         if (exists($currautoenroll{'run'})) {
15945:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
15946:                  $changes{'run'} = 1;
15947:              }
15948:         } elsif ($autorun) {
15949:             if ($env{'form.autoenroll_run'} ne '1') {
15950:                  $changes{'run'} = 1;
15951:             }
15952:         }
15953:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
15954:             $changes{'sender'} = 1;
15955:         }
15956:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
15957:             $changes{'sender'} = 1;
15958:         }
15959:         if ($currautoenroll{'co-owners'} ne '') {
15960:             if ($currautoenroll{'co-owners'} ne $coowners) {
15961:                 $changes{'coowners'} = 1;
15962:             }
15963:         } elsif ($coowners) {
15964:             $changes{'coowners'} = 1;
15965:         }
15966:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
15967:             $changes{'autofailsafe'} = 1;
15968:         }
15969:         if ($currautoenroll{'failsafe'} ne $failsafe) {
15970:             $changes{'failsafe'} = 1;
15971:         }
15972:         if (keys(%changes) > 0) {
15973:             $resulttext = &mt('Changes made:').'<ul>';
15974:             if ($changes{'run'}) {
15975:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
15976:             }
15977:             if ($changes{'sender'}) {
15978:                 if ($sender_uname eq '' || $sender_domain eq '') {
15979:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
15980:                 } else {
15981:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
15982:                 }
15983:             }
15984:             if ($changes{'coowners'}) {
15985:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
15986:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
15987:                 if (ref($lastactref) eq 'HASH') {
15988:                     $lastactref->{'domainconfig'} = 1;
15989:                 }
15990:             }
15991:             if ($changes{'autofailsafe'}) {
15992:                 if ($autofailsafe ne '') {
15993:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
15994:                 } else {
15995:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
15996:                 }
15997:             }
15998:             if ($changes{'failsafe'}) {
15999:                 if ($failsafe eq 'off') {
16000:                     unless ($changes{'autofailsafe'}) {
16001:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16002:                     }
16003:                 } elsif ($failsafe eq 'zero') {
16004:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
16005:                 } else {
16006:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
16007:                 }
16008:             }
16009:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
16010:                 &Apache::lonnet::get_domain_defaults($dom,1);
16011:                 if (ref($lastactref) eq 'HASH') {
16012:                     $lastactref->{'domdefaults'} = 1;
16013:                 }
16014:             }
16015:             $resulttext .= '</ul>';
16016:         } else {
16017:             $resulttext = &mt('No changes made to auto-enrollment settings');
16018:         }
16019:     } else {
16020:         $resulttext = '<span class="LC_error">'.
16021: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16022:     }
16023:     return $resulttext;
16024: }
16025: 
16026: sub modify_autoupdate {
16027:     my ($dom,%domconfig) = @_;
16028:     my ($resulttext,%currautoupdate,%fields,%changes);
16029:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
16030:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
16031:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
16032:         }
16033:     }
16034:     my @offon = ('off','on');
16035:     my %title = &Apache::lonlocal::texthash (
16036:                     run        => 'Auto-update:',
16037:                     classlists => 'Updates to user information in classlists?',
16038:                     unexpired  => 'Skip updates for users without active or future roles?',
16039:                     lastactive => 'Skip updates for inactive users?',
16040:                 );
16041:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16042:     my %fieldtitles = &Apache::lonlocal::texthash (
16043:                         id => 'Student/Employee ID',
16044:                         permanentemail => 'E-mail address',
16045:                         lastname => 'Last Name',
16046:                         firstname => 'First Name',
16047:                         middlename => 'Middle Name',
16048:                         generation => 'Generation',
16049:                       );
16050:     $othertitle = &mt('All users');
16051:     if (keys(%{$usertypes}) >  0) {
16052:         $othertitle = &mt('Other users');
16053:     }
16054:     foreach my $key (keys(%env)) {
16055:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
16056:             my ($usertype,$item) = ($1,$2);
16057:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
16058:                 if ($usertype eq 'default') {   
16059:                     push(@{$fields{$1}},$2);
16060:                 } elsif (ref($types) eq 'ARRAY') {
16061:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
16062:                         push(@{$fields{$1}},$2);
16063:                     }
16064:                 }
16065:             }
16066:         }
16067:     }
16068:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
16069:     @lockablenames = sort(@lockablenames);
16070:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
16071:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16072:         if (@changed) {
16073:             $changes{'lockablenames'} = 1;
16074:         }
16075:     } else {
16076:         if (@lockablenames) {
16077:             $changes{'lockablenames'} = 1;
16078:         }
16079:     }
16080:     my %updatehash = (
16081:                       autoupdate => { run => $env{'form.autoupdate_run'},
16082:                                       classlists => $env{'form.classlists'},
16083:                                       unexpired  => $env{'form.unexpired'},
16084:                                       fields => {%fields},
16085:                                       lockablenames => \@lockablenames,
16086:                                     }
16087:                      );
16088:     my $lastactivedays;
16089:     if ($env{'form.lastactive'}) {
16090:         $lastactivedays = $env{'form.lastactivedays'};
16091:         $lastactivedays =~ s/^\s+|\s+$//g;
16092:         unless ($lastactivedays =~ /^\d+$/) {
16093:             undef($lastactivedays);
16094:             $env{'form.lastactive'} = 0;
16095:         }
16096:     }
16097:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
16098:     foreach my $key (keys(%currautoupdate)) {
16099:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
16100:             if (exists($updatehash{autoupdate}{$key})) {
16101:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
16102:                     $changes{$key} = 1;
16103:                 }
16104:             }
16105:         } elsif ($key eq 'fields') {
16106:             if (ref($currautoupdate{$key}) eq 'HASH') {
16107:                 foreach my $item (@{$types},'default') {
16108:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
16109:                         my $change = 0;
16110:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
16111:                             if (!exists($fields{$item})) {
16112:                                 $change = 1;
16113:                                 last;
16114:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
16115:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
16116:                                     $change = 1;
16117:                                     last;
16118:                                 }
16119:                             }
16120:                         }
16121:                         if ($change) {
16122:                             push(@{$changes{$key}},$item);
16123:                         }
16124:                     } 
16125:                 }
16126:             }
16127:         } elsif ($key eq 'lockablenames') {
16128:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
16129:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16130:                 if (@changed) {
16131:                     $changes{'lockablenames'} = 1;
16132:                 }
16133:             } else {
16134:                 if (@lockablenames) {
16135:                     $changes{'lockablenames'} = 1;
16136:                 }
16137:             }
16138:         }
16139:     }
16140:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
16141:         if (@lockablenames) {
16142:             $changes{'lockablenames'} = 1;
16143:         }
16144:     }
16145:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
16146:         if ($updatehash{'autoupdate'}{'unexpired'}) {
16147:             $changes{'unexpired'} = 1;
16148:         }
16149:     }
16150:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
16151:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
16152:             $changes{'lastactive'} = 1;
16153:         }
16154:     }
16155:     foreach my $item (@{$types},'default') {
16156:         if (defined($fields{$item})) {
16157:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
16158:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
16159:                     my $change = 0;
16160:                     if (ref($fields{$item}) eq 'ARRAY') {
16161:                         foreach my $type (@{$fields{$item}}) {
16162:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
16163:                                 $change = 1;
16164:                                 last;
16165:                             }
16166:                         }
16167:                     }
16168:                     if ($change) {
16169:                         push(@{$changes{'fields'}},$item);
16170:                     }
16171:                 } else {
16172:                     push(@{$changes{'fields'}},$item);
16173:                 }
16174:             } else {
16175:                 push(@{$changes{'fields'}},$item);
16176:             }
16177:         }
16178:     }
16179:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
16180:                                              $dom);
16181:     if ($putresult eq 'ok') {
16182:         if (keys(%changes) > 0) {
16183:             $resulttext = &mt('Changes made:').'<ul>';
16184:             foreach my $key (sort(keys(%changes))) {
16185:                 if ($key eq 'lockablenames') {
16186:                     $resulttext .= '<li>';
16187:                     if (@lockablenames) {
16188:                         $usertypes->{'default'} = $othertitle;
16189:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
16190:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
16191:                     } else {
16192:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
16193:                     }
16194:                     $resulttext .= '</li>';
16195:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
16196:                     foreach my $item (@{$changes{$key}}) {
16197:                         my @newvalues;
16198:                         foreach my $type (@{$fields{$item}}) {
16199:                             push(@newvalues,$fieldtitles{$type});
16200:                         }
16201:                         my $newvaluestr;
16202:                         if (@newvalues > 0) {
16203:                             $newvaluestr = join(', ',@newvalues);
16204:                         } else {
16205:                             $newvaluestr = &mt('none');
16206:                         }
16207:                         if ($item eq 'default') {
16208:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
16209:                         } else {
16210:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
16211:                         }
16212:                     }
16213:                 } else {
16214:                     my $newvalue;
16215:                     if ($key eq 'run') {
16216:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
16217:                     } elsif ($key eq 'lastactive') {
16218:                         $newvalue = $offon[$env{'form.lastactive'}];
16219:                         unless ($lastactivedays eq '') {
16220:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
16221:                         }
16222:                     } else {
16223:                         $newvalue = $offon[$env{'form.'.$key}];
16224:                     }
16225:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
16226:                 }
16227:             }
16228:             $resulttext .= '</ul>';
16229:         } else {
16230:             $resulttext = &mt('No changes made to autoupdates');
16231:         }
16232:     } else {
16233:         $resulttext = '<span class="LC_error">'.
16234: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16235:     }
16236:     return $resulttext;
16237: }
16238: 
16239: sub modify_autocreate {
16240:     my ($dom,%domconfig) = @_;
16241:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
16242:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
16243:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
16244:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
16245:         }
16246:     }
16247:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
16248:                  req => 'Auto-creation of validated requests for official courses',
16249:                  xmldc => 'Identity of course creator of courses from XML files',
16250:                );
16251:     my @types = ('xml','req');
16252:     foreach my $item (@types) {
16253:         $newvals{$item} = $env{'form.autocreate_'.$item};
16254:         $newvals{$item} =~ s/\D//g;
16255:         $newvals{$item} = 0 if ($newvals{$item} eq '');
16256:     }
16257:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
16258:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
16259:     unless (exists($domcoords{$newvals{'xmldc'}})) {
16260:         $newvals{'xmldc'} = '';
16261:     } 
16262:     %autocreatehash =  (
16263:                         autocreate => { xml => $newvals{'xml'},
16264:                                         req => $newvals{'req'},
16265:                                       }
16266:                        );
16267:     if ($newvals{'xmldc'} ne '') {
16268:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
16269:     }
16270:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
16271:                                              $dom);
16272:     if ($putresult eq 'ok') {
16273:         my @items = @types;
16274:         if ($newvals{'xml'}) {
16275:             push(@items,'xmldc');
16276:         }
16277:         foreach my $item (@items) {
16278:             if (exists($currautocreate{$item})) {
16279:                 if ($currautocreate{$item} ne $newvals{$item}) {
16280:                     $changes{$item} = 1;
16281:                 }
16282:             } elsif ($newvals{$item}) {
16283:                 $changes{$item} = 1;
16284:             }
16285:         }
16286:         if (keys(%changes) > 0) {
16287:             my @offon = ('off','on'); 
16288:             $resulttext = &mt('Changes made:').'<ul>';
16289:             foreach my $item (@types) {
16290:                 if ($changes{$item}) {
16291:                     my $newtxt = $offon[$newvals{$item}];
16292:                     $resulttext .= '<li>'.
16293:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
16294:                                        '<b>','</b>').
16295:                                    '</li>';
16296:                 }
16297:             }
16298:             if ($changes{'xmldc'}) {
16299:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
16300:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
16301:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
16302:             }
16303:             $resulttext .= '</ul>';
16304:         } else {
16305:             $resulttext = &mt('No changes made to auto-creation settings');
16306:         }
16307:     } else {
16308:         $resulttext = '<span class="LC_error">'.
16309:             &mt('An error occurred: [_1]',$putresult).'</span>';
16310:     }
16311:     return $resulttext;
16312: }
16313: 
16314: sub modify_directorysrch {
16315:     my ($dom,$lastactref,%domconfig) = @_;
16316:     my ($resulttext,%changes);
16317:     my %currdirsrch;
16318:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
16319:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
16320:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
16321:         }
16322:     }
16323:     my %title = ( available => 'Institutional directory search available',
16324:                   localonly => 'Other domains can search institution',
16325:                   lcavailable => 'LON-CAPA directory search available',
16326:                   lclocalonly => 'Other domains can search LON-CAPA domain',
16327:                   searchby => 'Search types',
16328:                   searchtypes => 'Search latitude');
16329:     my @offon = ('off','on');
16330:     my @otherdoms = ('Yes','No');
16331: 
16332:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
16333:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
16334:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
16335: 
16336:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16337:     if (keys(%{$usertypes}) == 0) {
16338:         @cansearch = ('default');
16339:     } else {
16340:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
16341:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
16342:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
16343:                     push(@{$changes{'cansearch'}},$type);
16344:                 }
16345:             }
16346:             foreach my $type (@cansearch) {
16347:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
16348:                     push(@{$changes{'cansearch'}},$type);
16349:                 }
16350:             }
16351:         } else {
16352:             push(@{$changes{'cansearch'}},@cansearch);
16353:         }
16354:     }
16355: 
16356:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
16357:         foreach my $by (@{$currdirsrch{'searchby'}}) {
16358:             if (!grep(/^\Q$by\E$/,@searchby)) {
16359:                 push(@{$changes{'searchby'}},$by);
16360:             }
16361:         }
16362:         foreach my $by (@searchby) {
16363:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
16364:                 push(@{$changes{'searchby'}},$by);
16365:             }
16366:         }
16367:     } else {
16368:         push(@{$changes{'searchby'}},@searchby);
16369:     }
16370: 
16371:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
16372:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
16373:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
16374:                 push(@{$changes{'searchtypes'}},$type);
16375:             }
16376:         }
16377:         foreach my $type (@searchtypes) {
16378:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
16379:                 push(@{$changes{'searchtypes'}},$type);
16380:             }
16381:         }
16382:     } else {
16383:         if (exists($currdirsrch{'searchtypes'})) {
16384:             foreach my $type (@searchtypes) {  
16385:                 if ($type ne $currdirsrch{'searchtypes'}) { 
16386:                     push(@{$changes{'searchtypes'}},$type);
16387:                 }
16388:             }
16389:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
16390:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
16391:             }   
16392:         } else {
16393:             push(@{$changes{'searchtypes'}},@searchtypes); 
16394:         }
16395:     }
16396: 
16397:     my %dirsrch_hash =  (
16398:             directorysrch => { available => $env{'form.dirsrch_available'},
16399:                                cansearch => \@cansearch,
16400:                                localonly => $env{'form.dirsrch_instlocalonly'},
16401:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
16402:                                lcavailable => $env{'form.dirsrch_domavailable'},
16403:                                searchby => \@searchby,
16404:                                searchtypes => \@searchtypes,
16405:                              }
16406:             );
16407:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
16408:                                              $dom);
16409:     if ($putresult eq 'ok') {
16410:         if (exists($currdirsrch{'available'})) {
16411:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
16412:                  $changes{'available'} = 1;
16413:              }
16414:         } else {
16415:             if ($env{'form.dirsrch_available'} eq '1') {
16416:                 $changes{'available'} = 1;
16417:             }
16418:         }
16419:         if (exists($currdirsrch{'lcavailable'})) {
16420:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
16421:                 $changes{'lcavailable'} = 1;
16422:             }
16423:         } else {
16424:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
16425:                 $changes{'lcavailable'} = 1;
16426:             }
16427:         }
16428:         if (exists($currdirsrch{'localonly'})) {
16429:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
16430:                 $changes{'localonly'} = 1;
16431:             }
16432:         } else {
16433:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
16434:                 $changes{'localonly'} = 1;
16435:             }
16436:         }
16437:         if (exists($currdirsrch{'lclocalonly'})) {
16438:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
16439:                 $changes{'lclocalonly'} = 1;
16440:             }
16441:         } else {
16442:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
16443:                 $changes{'lclocalonly'} = 1;
16444:             }
16445:         }
16446:         if (keys(%changes) > 0) {
16447:             $resulttext = &mt('Changes made:').'<ul>';
16448:             if ($changes{'available'}) {
16449:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
16450:             }
16451:             if ($changes{'lcavailable'}) {
16452:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
16453:             }
16454:             if ($changes{'localonly'}) {
16455:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
16456:             }
16457:             if ($changes{'lclocalonly'}) {
16458:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
16459:             }
16460:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
16461:                 my $chgtext;
16462:                 if (ref($usertypes) eq 'HASH') {
16463:                     if (keys(%{$usertypes}) > 0) {
16464:                         foreach my $type (@{$types}) {
16465:                             if (grep(/^\Q$type\E$/,@cansearch)) {
16466:                                 $chgtext .= $usertypes->{$type}.'; ';
16467:                             }
16468:                         }
16469:                         if (grep(/^default$/,@cansearch)) {
16470:                             $chgtext .= $othertitle;
16471:                         } else {
16472:                             $chgtext =~ s/\; $//;
16473:                         }
16474:                         $resulttext .=
16475:                             '<li>'.
16476:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
16477:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
16478:                             '</li>';
16479:                     }
16480:                 }
16481:             }
16482:             if (ref($changes{'searchby'}) eq 'ARRAY') {
16483:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
16484:                 my $chgtext;
16485:                 foreach my $type (@{$titleorder}) {
16486:                     if (grep(/^\Q$type\E$/,@searchby)) {
16487:                         if (defined($searchtitles->{$type})) {
16488:                             $chgtext .= $searchtitles->{$type}.'; ';
16489:                         }
16490:                     }
16491:                 }
16492:                 $chgtext =~ s/\; $//;
16493:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
16494:             }
16495:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
16496:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
16497:                 my $chgtext;
16498:                 foreach my $type (@{$srchtypeorder}) {
16499:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
16500:                         if (defined($srchtypes_desc->{$type})) {
16501:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
16502:                         }
16503:                     }
16504:                 }
16505:                 $chgtext =~ s/\; $//;
16506:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
16507:             }
16508:             $resulttext .= '</ul>';
16509:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
16510:             if (ref($lastactref) eq 'HASH') {
16511:                 $lastactref->{'directorysrch'} = 1;
16512:             }
16513:         } else {
16514:             $resulttext = &mt('No changes made to directory search settings');
16515:         }
16516:     } else {
16517:         $resulttext = '<span class="LC_error">'.
16518:                       &mt('An error occurred: [_1]',$putresult).'</span>';
16519:     }
16520:     return $resulttext;
16521: }
16522: 
16523: sub modify_contacts {
16524:     my ($dom,$lastactref,%domconfig) = @_;
16525:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
16526:     if (ref($domconfig{'contacts'}) eq 'HASH') {
16527:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
16528:             $currsetting{$key} = $domconfig{'contacts'}{$key};
16529:         }
16530:     }
16531:     my (%others,%to,%bcc,%includestr,%includeloc);
16532:     my @contacts = ('supportemail','adminemail');
16533:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
16534:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
16535:     my @toggles = ('reporterrors','reportupdates','reportstatus');
16536:     my @lonstatus = ('threshold','sysmail','weights','excluded');
16537:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
16538:     foreach my $type (@mailings) {
16539:         @{$newsetting{$type}} = 
16540:             &Apache::loncommon::get_env_multiple('form.'.$type);
16541:         foreach my $item (@contacts) {
16542:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
16543:                 $contacts_hash{contacts}{$type}{$item} = 1;
16544:             } else {
16545:                 $contacts_hash{contacts}{$type}{$item} = 0;
16546:             }
16547:         }
16548:         $others{$type} = $env{'form.'.$type.'_others'};
16549:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
16550:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16551:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
16552:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
16553:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
16554:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
16555:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
16556:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
16557:             }
16558:         }
16559:     }
16560:     foreach my $item (@contacts) {
16561:         $to{$item} = $env{'form.'.$item};
16562:         $contacts_hash{'contacts'}{$item} = $to{$item};
16563:     }
16564:     foreach my $item (@toggles) {
16565:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
16566:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
16567:         }
16568:     }
16569:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
16570:     foreach my $item (@lonstatus) {
16571:         if ($item eq 'excluded') {
16572:             my (%serverhomes,@excluded);
16573:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
16574:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
16575:             if (@possexcluded) {
16576:                 foreach my $id (sort(@possexcluded)) {
16577:                     if ($serverhomes{$id}) {
16578:                         push(@excluded,$id);
16579:                     }
16580:                 }
16581:             }
16582:             if (@excluded) {
16583:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
16584:             }
16585:         } elsif ($item eq 'weights') {
16586:             foreach my $type ('E','W','N','U') {
16587:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
16588:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
16589:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
16590:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
16591:                             $env{'form.error'.$item.'_'.$type};
16592:                     }
16593:                 }
16594:             }
16595:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
16596:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
16597:             if ($env{'form.error'.$item} =~ /^\d+$/) {
16598:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
16599:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
16600:                 }
16601:             }
16602:         }
16603:     }
16604:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
16605:         foreach my $field (@{$fields}) {
16606:             if (ref($possoptions->{$field}) eq 'ARRAY') {
16607:                 my $value = $env{'form.helpform_'.$field};
16608:                 $value =~ s/^\s+|\s+$//g;
16609:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
16610:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
16611:                     if ($field eq 'screenshot') {
16612:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
16613:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
16614:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
16615:                         }
16616:                     }
16617:                 }
16618:             }
16619:         }
16620:     }
16621:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16622:     my (@statuses,%usertypeshash,@overrides);
16623:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
16624:         @statuses = @{$types};
16625:         if (ref($usertypes) eq 'HASH') {
16626:             %usertypeshash = %{$usertypes};
16627:         }
16628:     }
16629:     if (@statuses) {
16630:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
16631:         foreach my $type (@possoverrides) {
16632:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
16633:                 push(@overrides,$type);
16634:             }
16635:         }
16636:         if (@overrides) {
16637:             foreach my $type (@overrides) {
16638:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
16639:                 foreach my $item (@contacts) {
16640:                     if (grep(/^\Q$item\E$/,@standard)) {
16641:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
16642:                         $newsetting{'override_'.$type}{$item} = 1;
16643:                     } else {
16644:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
16645:                         $newsetting{'override_'.$type}{$item} = 0;
16646:                     }
16647:                 }
16648:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
16649:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
16650:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
16651:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
16652:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
16653:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
16654:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
16655:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
16656:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
16657:                 }
16658:             }
16659:         }
16660:     }
16661:     if (keys(%currsetting) > 0) {
16662:         foreach my $item (@contacts) {
16663:             if ($to{$item} ne $currsetting{$item}) {
16664:                 $changes{$item} = 1;
16665:             }
16666:         }
16667:         foreach my $type (@mailings) {
16668:             foreach my $item (@contacts) {
16669:                 if (ref($currsetting{$type}) eq 'HASH') {
16670:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
16671:                         push(@{$changes{$type}},$item);
16672:                     }
16673:                 } else {
16674:                     push(@{$changes{$type}},@{$newsetting{$type}});
16675:                 }
16676:             }
16677:             if ($others{$type} ne $currsetting{$type}{'others'}) {
16678:                 push(@{$changes{$type}},'others');
16679:             }
16680:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16681:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
16682:                     push(@{$changes{$type}},'bcc'); 
16683:                 }
16684:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
16685:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
16686:                     push(@{$changes{$type}},'include');
16687:                 }
16688:             }
16689:         }
16690:         if (ref($fields) eq 'ARRAY') {
16691:             if (ref($currsetting{'helpform'}) eq 'HASH') {
16692:                 foreach my $field (@{$fields}) {
16693:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
16694:                         push(@{$changes{'helpform'}},$field);
16695:                     }
16696:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
16697:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
16698:                             push(@{$changes{'helpform'}},'maxsize');
16699:                         }
16700:                     }
16701:                 }
16702:             } else {
16703:                 foreach my $field (@{$fields}) {
16704:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
16705:                         push(@{$changes{'helpform'}},$field);
16706:                     }
16707:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
16708:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
16709:                             push(@{$changes{'helpform'}},'maxsize');
16710:                         }
16711:                     }
16712:                 }
16713:             }
16714:         }
16715:         if (@statuses) {
16716:             if (ref($currsetting{'overrides'}) eq 'HASH') {
16717:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
16718:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
16719:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
16720:                             foreach my $item (@contacts,'bcc','others','include') {
16721:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) {
16722:                                     push(@{$changes{'overrides'}},$key);
16723:                                     last;
16724:                                 }
16725:                             }
16726:                         } else {
16727:                             push(@{$changes{'overrides'}},$key);
16728:                         }
16729:                     }
16730:                 }
16731:                 foreach my $key (@overrides) {
16732:                     unless (exists($currsetting{'overrides'}{$key})) {
16733:                         push(@{$changes{'overrides'}},$key);
16734:                     }
16735:                 }
16736:             } else {
16737:                 foreach my $key (@overrides) {
16738:                     push(@{$changes{'overrides'}},$key);
16739:                 }
16740:             }
16741:         }
16742:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
16743:             foreach my $key ('excluded','weights','threshold','sysmail') {
16744:                 if ($key eq 'excluded') {
16745:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
16746:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
16747:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
16748:                             (@{$currsetting{'lonstatus'}{$key}})) {
16749:                             my @diffs =
16750:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
16751:                                                                    $currsetting{'lonstatus'}{$key});
16752:                             if (@diffs) {
16753:                                 push(@{$changes{'lonstatus'}},$key);
16754:                             }
16755:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
16756:                             push(@{$changes{'lonstatus'}},$key);
16757:                         }
16758:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
16759:                              (@{$currsetting{'lonstatus'}{$key}})) {
16760:                         push(@{$changes{'lonstatus'}},$key);
16761:                     }
16762:                 } elsif ($key eq 'weights') {
16763:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
16764:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
16765:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
16766:                             foreach my $type ('E','W','N','U') {
16767:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
16768:                                         $currsetting{'lonstatus'}{$key}{$type}) {
16769:                                     push(@{$changes{'lonstatus'}},$key);
16770:                                     last;
16771:                                 }
16772:                             }
16773:                         } else {
16774:                             foreach my $type ('E','W','N','U') {
16775:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
16776:                                     push(@{$changes{'lonstatus'}},$key);
16777:                                     last;
16778:                                 }
16779:                             }
16780:                         }
16781:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
16782:                         foreach my $type ('E','W','N','U') {
16783:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
16784:                                 push(@{$changes{'lonstatus'}},$key);
16785:                                 last;
16786:                             }
16787:                         }
16788:                     }
16789:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
16790:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16791:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
16792:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
16793:                                 push(@{$changes{'lonstatus'}},$key);
16794:                             }
16795:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
16796:                             push(@{$changes{'lonstatus'}},$key);
16797:                         }
16798:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
16799:                         push(@{$changes{'lonstatus'}},$key);
16800:                     }
16801:                 }
16802:             }
16803:         } else {
16804:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16805:                 foreach my $key ('excluded','weights','threshold','sysmail') {
16806:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
16807:                         push(@{$changes{'lonstatus'}},$key);
16808:                     }
16809:                 }
16810:             }
16811:         }
16812:     } else {
16813:         my %default;
16814:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
16815:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
16816:         $default{'errormail'} = 'adminemail';
16817:         $default{'packagesmail'} = 'adminemail';
16818:         $default{'helpdeskmail'} = 'supportemail';
16819:         $default{'otherdomsmail'} = 'supportemail';
16820:         $default{'lonstatusmail'} = 'adminemail';
16821:         $default{'requestsmail'} = 'adminemail';
16822:         $default{'updatesmail'} = 'adminemail';
16823:         $default{'hostipmail'} = 'adminemail';
16824:         foreach my $item (@contacts) {
16825:            if ($to{$item} ne $default{$item}) {
16826:                $changes{$item} = 1;
16827:            }
16828:         }
16829:         foreach my $type (@mailings) {
16830:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
16831:                 push(@{$changes{$type}},@{$newsetting{$type}});
16832:             }
16833:             if ($others{$type} ne '') {
16834:                 push(@{$changes{$type}},'others');
16835:             }
16836:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16837:                 if ($bcc{$type} ne '') {
16838:                     push(@{$changes{$type}},'bcc');
16839:                 }
16840:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
16841:                     push(@{$changes{$type}},'include');
16842:                 }
16843:             }
16844:         }
16845:         if (ref($fields) eq 'ARRAY') {
16846:             foreach my $field (@{$fields}) {
16847:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
16848:                     push(@{$changes{'helpform'}},$field);
16849:                 }
16850:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
16851:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
16852:                         push(@{$changes{'helpform'}},'maxsize');
16853:                     }
16854:                 }
16855:             }
16856:         }
16857:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16858:             foreach my $key ('excluded','weights','threshold','sysmail') {
16859:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
16860:                     push(@{$changes{'lonstatus'}},$key);
16861:                 }
16862:             }
16863:         }
16864:     }
16865:     foreach my $item (@toggles) {
16866:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
16867:             $changes{$item} = 1;
16868:         } elsif ((!$env{'form.'.$item}) &&
16869:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
16870:             $changes{$item} = 1;
16871:         }
16872:     }
16873:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
16874:                                              $dom);
16875:     if ($putresult eq 'ok') {
16876:         if (keys(%changes) > 0) {
16877:             &Apache::loncommon::devalidate_domconfig_cache($dom);
16878:             if (ref($lastactref) eq 'HASH') {
16879:                 $lastactref->{'domainconfig'} = 1;
16880:             }
16881:             my ($titles,$short_titles)  = &contact_titles();
16882:             $resulttext = &mt('Changes made:').'<ul>';
16883:             foreach my $item (@contacts) {
16884:                 if ($changes{$item}) {
16885:                     $resulttext .= '<li>'.$titles->{$item}.
16886:                                     &mt(' set to: ').
16887:                                     '<span class="LC_cusr_emph">'.
16888:                                     $to{$item}.'</span></li>';
16889:                 }
16890:             }
16891:             foreach my $type (@mailings) {
16892:                 if (ref($changes{$type}) eq 'ARRAY') {
16893:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16894:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
16895:                     } else {
16896:                         $resulttext .= '<li>'.$titles->{$type}.': ';
16897:                     }
16898:                     my @text;
16899:                     foreach my $item (@{$newsetting{$type}}) {
16900:                         push(@text,$short_titles->{$item});
16901:                     }
16902:                     if ($others{$type} ne '') {
16903:                         push(@text,$others{$type});
16904:                     }
16905:                     if (@text) {
16906:                         $resulttext .= '<span class="LC_cusr_emph">'.
16907:                                        join(', ',@text).'</span>';
16908:                     }
16909:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16910:                         if ($bcc{$type} ne '') {
16911:                             my $bcctext;
16912:                             if (@text) {
16913:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
16914:                             } else {
16915:                                 $bcctext = '(Bcc)';
16916:                             }
16917:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
16918:                         } elsif (!@text) {
16919:                             $resulttext .= &mt('No one');
16920:                         }
16921:                         if ($includestr{$type} ne '') {
16922:                             if ($includeloc{$type} eq 'b') {
16923:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
16924:                             } elsif ($includeloc{$type} eq 's') {
16925:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
16926:                             }
16927:                         }
16928:                     } elsif (!@text) {
16929:                         $resulttext .= &mt('No recipients');
16930:                     }
16931:                     $resulttext .= '</li>';
16932:                 }
16933:             }
16934:             if (ref($changes{'overrides'}) eq 'ARRAY') {
16935:                 my @deletions;
16936:                 foreach my $type (@{$changes{'overrides'}}) {
16937:                     if ($usertypeshash{$type}) {
16938:                         if (grep(/^\Q$type\E/,@overrides)) {
16939:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
16940:                                                       $usertypeshash{$type}).'<ul><li>';
16941:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
16942:                                 my @text;
16943:                                 foreach my $item (@contacts) {
16944:                                     if ($newsetting{'override_'.$type}{$item}) {
16945:                                         push(@text,$short_titles->{$item});
16946:                                     }
16947:                                 }
16948:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
16949:                                     push(@text,$newsetting{'override_'.$type}{'others'});
16950:                                 }
16951: 
16952:                                 if (@text) {
16953:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
16954:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
16955:                                 }
16956:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
16957:                                     my $bcctext;
16958:                                     if (@text) {
16959:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
16960:                                     } else {
16961:                                         $bcctext = '(Bcc)';
16962:                                     }
16963:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
16964:                                 } elsif (!@text) {
16965:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
16966:                                 }
16967:                                 $resulttext .= '</li>';
16968:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
16969:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
16970:                                     if ($loc eq 'b') {
16971:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
16972:                                     } elsif ($loc eq 's') {
16973:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
16974:                                     }
16975:                                 }
16976:                             }
16977:                             $resulttext .= '</li></ul></li>';
16978:                         } else {
16979:                             push(@deletions,$usertypeshash{$type});
16980:                         }
16981:                     }
16982:                 }
16983:                 if (@deletions) {
16984:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
16985:                                               join(', ',@deletions)).'</li>';
16986:                 }
16987:             }
16988:             my @offon = ('off','on');
16989:             my $corelink = &core_link_msu();
16990:             if ($changes{'reporterrors'}) {
16991:                 $resulttext .= '<li>'.
16992:                                &mt('E-mail error reports to [_1] set to "'.
16993:                                    $offon[$env{'form.reporterrors'}].'".',
16994:                                    $corelink).
16995:                                '</li>';
16996:             }
16997:             if ($changes{'reportupdates'}) {
16998:                 $resulttext .= '<li>'.
16999:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
17000:                                     $offon[$env{'form.reportupdates'}].'".',
17001:                                     $corelink).
17002:                                 '</li>';
17003:             }
17004:             if ($changes{'reportstatus'}) {
17005:                 $resulttext .= '<li>'.
17006:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
17007:                                     $offon[$env{'form.reportstatus'}].'".',
17008:                                     $corelink).
17009:                                 '</li>';
17010:             }
17011:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
17012:                 $resulttext .= '<li>'.
17013:                                &mt('Nightly status check e-mail settings').':<ul>';
17014:                 my (%defval,%use_def,%shown);
17015:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
17016:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
17017:                 $defval{'weights'} =
17018:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
17019:                 $defval{'excluded'} = &mt('None');
17020:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
17021:                     foreach my $item ('threshold','sysmail','weights','excluded') {
17022:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
17023:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
17024:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
17025:                             } elsif ($item eq 'weights') {
17026:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
17027:                                     foreach my $type ('E','W','N','U') {
17028:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
17029:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
17030:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
17031:                                         } else {
17032:                                             $shown{$item} .= $lonstatus_defs->{$type};
17033:                                         }
17034:                                         $shown{$item} .= ', ';
17035:                                     }
17036:                                     $shown{$item} =~ s/, $//;
17037:                                 } else {
17038:                                     $shown{$item} = $defval{$item};
17039:                                 }
17040:                             } elsif ($item eq 'excluded') {
17041:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
17042:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
17043:                                 } else {
17044:                                     $shown{$item} = $defval{$item};
17045:                                 }
17046:                             }
17047:                         } else {
17048:                             $shown{$item} = $defval{$item};
17049:                         }
17050:                     }
17051:                 } else {
17052:                     foreach my $item ('threshold','weights','excluded','sysmail') {
17053:                         $shown{$item} = $defval{$item};
17054:                     }
17055:                 }
17056:                 foreach my $item ('threshold','weights','excluded','sysmail') {
17057:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
17058:                                           $shown{$item}).'</li>';
17059:                 }
17060:                 $resulttext .= '</ul></li>';
17061:             }
17062:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
17063:                 my (@optional,@required,@unused,$maxsizechg);
17064:                 foreach my $field (@{$changes{'helpform'}}) {
17065:                     if ($field eq 'maxsize') {
17066:                         $maxsizechg = 1;
17067:                         next;
17068:                     }
17069:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
17070:                         push(@optional,$field);
17071:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
17072:                         push(@unused,$field);
17073:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
17074:                         push(@required,$field);
17075:                     }
17076:                 }
17077:                 if (@optional) {
17078:                     $resulttext .= '<li>'.
17079:                                    &mt('Help form fields changed to "Optional": [_1].',
17080:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
17081:                                    '</li>';
17082:                 }
17083:                 if (@required) {
17084:                     $resulttext .= '<li>'.
17085:                                    &mt('Help form fields changed to "Required": [_1].',
17086:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
17087:                                    '</li>';
17088:                 }
17089:                 if (@unused) {
17090:                     $resulttext .= '<li>'.
17091:                                    &mt('Help form fields changed to "Not shown": [_1].',
17092:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
17093:                                    '</li>';
17094:                 }
17095:                 if ($maxsizechg) {
17096:                     $resulttext .= '<li>'.
17097:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
17098:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
17099:                                    '</li>';
17100:                 }
17101:             }
17102:             $resulttext .= '</ul>';
17103:         } else {
17104:             $resulttext = &mt('No changes made to contacts and form settings');
17105:         }
17106:     } else {
17107:         $resulttext = '<span class="LC_error">'.
17108:             &mt('An error occurred: [_1].',$putresult).'</span>';
17109:     }
17110:     return $resulttext;
17111: }
17112: 
17113: sub modify_privacy {
17114:     my ($dom,%domconfig) = @_;
17115:     my ($resulttext,%current,%changes);
17116:     if (ref($domconfig{'privacy'}) eq 'HASH') {
17117:         %current = %{$domconfig{'privacy'}};
17118:     }
17119:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
17120:     my @items = ('domain','author','course','community');
17121:     my %names = &Apache::lonlocal::texthash (
17122:                    domain => 'Assigned domain role(s)',
17123:                    author => 'Assigned co-author role(s)',
17124:                    course => 'Assigned course role(s)',
17125:                    community => 'Assigned community role(s)',
17126:                 );
17127:     my %roles = &Apache::lonlocal::texthash (
17128:                    domain => 'Domain role',
17129:                    author => 'Co-author role',
17130:                    course => 'Course role',
17131:                    community => 'Community role',
17132:                 );
17133:     my %titles = &Apache::lonlocal::texthash (
17134:                   approval => 'Approval for role in different domain',
17135:                   othdom   => 'User information available in other domain',
17136:                   priv     => 'Information viewable by privileged user in same domain',
17137:                   unpriv   => 'Information viewable by unprivileged user in same domain',
17138:                   instdom  => 'Other domain shares institution/provider',
17139:                   extdom   => 'Other domain has different institution/provider',
17140:                   none     => 'Not allowed',
17141:                   user     => 'User authorizes',
17142:                   domain   => 'Domain Coordinator authorizes',
17143:                   auto     => 'Unrestricted',
17144:                   notify   => 'Notify when role needs authorization',
17145:     );
17146:     my %fieldnames = &Apache::lonlocal::texthash (
17147:                         id => 'Student/Employee ID',
17148:                         permanentemail => 'E-mail address',
17149:                         lastname => 'Last Name',
17150:                         firstname => 'First Name',
17151:                         middlename => 'Middle Name',
17152:                         generation => 'Generation',
17153:     );
17154:     my ($othertitle,$usertypes,$types) =
17155:         &Apache::loncommon::sorted_inst_types($dom);
17156:     my (%by_ip,%by_location,@intdoms,@instdoms);
17157:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
17158: 
17159:     my %privacyhash = (
17160:                        'approval' => {
17161:                                        instdom => {},
17162:                                        extdom  => {},
17163:                                      },
17164:                        'othdom'   => {},
17165:                        'priv'     => {},
17166:                        'unpriv'   => {},
17167:                       );
17168:     foreach my $item (@items) {
17169:         if (@instdoms > 1) {
17170:             if ($env{'form.privacy_approval_instdom_'.$item} =~ /^(none|user|domain|auto)$/) {
17171:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
17172:             }
17173:             if (ref($current{'approval'}) eq 'HASH') {
17174:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
17175:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
17176:                         $changes{'approval'} = 1;
17177:                     }
17178:                 }
17179:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
17180:                 $changes{'approval'} = 1;
17181:             }
17182:         }
17183:         if (keys(%by_location) > 0) {
17184:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
17185:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
17186:             }
17187:             if (ref($current{'approval'}) eq 'HASH') {
17188:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
17189:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
17190:                         $changes{'approval'} = 1;
17191:                     }
17192:                 }
17193:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
17194:                 $changes{'approval'} = 1;
17195:             }
17196:         }
17197:         foreach my $status ('priv','unpriv') {
17198:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
17199:             my @newvalues;
17200:             foreach my $field (@possibles) {
17201:                 if (grep(/^\Q$field\E$/,@fields)) {
17202:                     $privacyhash{$status}{$item}{$field} = 1;
17203:                     push(@newvalues,$field);
17204:                 }
17205:             }
17206:             @newvalues = sort(@newvalues);
17207:             if (ref($current{$status}) eq 'HASH') {
17208:                 if (ref($current{$status}{$item}) eq 'HASH') {
17209:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
17210:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
17211:                     if (@diffs > 0) {
17212:                         $changes{$status} = 1;
17213:                     }
17214:                 }
17215:             } else {
17216:                 my @stdfields;
17217:                 foreach my $field (@fields) {
17218:                     if ($field eq 'id') {
17219:                         next if ($status eq 'unpriv');
17220:                         next if (($status eq 'priv') && ($item eq 'community'));
17221:                     }
17222:                     push(@stdfields,$field);
17223:                 }
17224:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
17225:                 if (@diffs > 0) {
17226:                     $changes{$status} = 1;
17227:                 }
17228:             }
17229:         }
17230:     }
17231:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
17232:         my @statuses;
17233:         if (ref($types) eq 'ARRAY') {
17234:             @statuses = @{$types};
17235:         }
17236:         foreach my $type (@statuses,'default') {
17237:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
17238:             my @newvalues;
17239:             foreach my $field (sort(@possfields)) {
17240:                 if (grep(/^\Q$field\E$/,@fields)) {
17241:                     $privacyhash{'othdom'}{$type}{$field} = 1;
17242:                     push(@newvalues,$field);
17243:                 }
17244:             }
17245:             @newvalues = sort(@newvalues);
17246:             if (ref($current{'othdom'}) eq 'HASH') {
17247:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
17248:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
17249:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
17250:                     if (@diffs > 0) {
17251:                         $changes{'othdom'} = 1;
17252:                     }
17253:                 }
17254:             } else {
17255:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
17256:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
17257:                 if (@diffs > 0) {
17258:                     $changes{'othdom'} = 1;
17259:                 }
17260:             }
17261:         }
17262:         my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
17263:         my %notify;
17264:         foreach my $possdc (&Apache::loncommon::get_env_multiple('form.privacy_notify')) {
17265:             if (exists($domcoords{$possdc})) {
17266:                 $notify{$possdc} = 1;
17267:             }
17268:         }
17269:         my $notify = join(',',sort(keys(%notify)));
17270:         if ($current{'notify'} ne $notify) {
17271:             $changes{'notify'} = 1;
17272:         }
17273:         $privacyhash{'notify'} = $notify;
17274:     }
17275:     my %confighash = (
17276:                         privacy => \%privacyhash,
17277:                      );
17278:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
17279:     if ($putresult eq 'ok') {
17280:         if (keys(%changes) > 0) {
17281:             $resulttext = &mt('Changes made: ').'<ul>';
17282:             foreach my $key ('approval','notify','othdom','priv','unpriv') {
17283:                 if ($changes{$key}) {
17284:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
17285:                     if ($key eq 'approval') {
17286:                         if (keys(%{$privacyhash{$key}{instdom}})) {
17287:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
17288:                             foreach my $item (@items) {
17289:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
17290:                             }
17291:                             $resulttext .= '</ul></li>';
17292:                         }
17293:                         if (keys(%{$privacyhash{$key}{extdom}})) {
17294:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
17295:                             foreach my $item (@items) {
17296:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
17297:                             }
17298:                             $resulttext .= '</ul></li>';
17299:                         }
17300:                     } elsif ($key eq 'notify') {
17301:                         if ($privacyhash{$key}) {
17302:                             foreach my $dc (split(/,/,$privacyhash{$key})) {
17303:                                 my ($dcname,$dcdom) = split(/:/,$dc);
17304:                                 $resulttext .= '<li>'.&Apache::loncommon::plainname($dcname,$dcdom).'</li>';
17305:                             }
17306:                         } else {
17307:                             $resulttext .= '<li>'.&mt('No DCs to notify').'</li>';
17308:                         }
17309:                     } elsif ($key eq 'othdom') {
17310:                         my @statuses;
17311:                         if (ref($types) eq 'ARRAY') {
17312:                             @statuses = @{$types};
17313:                         }
17314:                         if (ref($privacyhash{$key}) eq 'HASH') {
17315:                             foreach my $status (@statuses,'default') {
17316:                                 if ($status eq 'default') {
17317:                                     $resulttext .= '<li>'.$othertitle.': ';
17318:                                 } elsif (ref($usertypes) eq 'HASH') {
17319:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
17320:                                 } else {
17321:                                     next;
17322:                                 }
17323:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
17324:                                     if (keys(%{$privacyhash{$key}{$status}})) {
17325:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
17326:                                     } else {
17327:                                         $resulttext .= &mt('none');
17328:                                     }
17329:                                 }
17330:                                 $resulttext .= '</li>';
17331:                             }
17332:                         }
17333:                     } else {
17334:                         foreach my $item (@items) {
17335:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
17336:                                 $resulttext .= '<li>'.$names{$item}.': ';
17337:                                 if (keys(%{$privacyhash{$key}{$item}})) {
17338:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
17339:                                 } else {
17340:                                     $resulttext .= &mt('none');
17341:                                 }
17342:                                 $resulttext .= '</li>';
17343:                             }
17344:                         }
17345:                     }
17346:                     $resulttext .= '</ul></li>';
17347:                 }
17348:             }
17349:             $resulttext .= '</ul>';
17350:         } else {
17351:             $resulttext = &mt('No changes made to user information settings');
17352:         }
17353:     } else {
17354:         $resulttext = '<span class="LC_error">'.
17355:             &mt('An error occurred: [_1]',$putresult).'</span>';
17356:     }
17357:     return $resulttext;
17358: }
17359: 
17360: sub modify_passwords {
17361:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
17362:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
17363:         $updatedefaults,$updateconf);
17364:     my $customfn = 'resetpw.html';
17365:     if (ref($domconfig{'passwords'}) eq 'HASH') {
17366:         %current = %{$domconfig{'passwords'}};
17367:     }
17368:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17369:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17370:     if (ref($types) eq 'ARRAY') {
17371:         @oktypes = @{$types};
17372:     }
17373:     push(@oktypes,'default');
17374: 
17375:     my %titles = &Apache::lonlocal::texthash (
17376:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
17377:         intauth_check  => 'Check bcrypt cost if authenticated',
17378:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
17379:         permanent      => 'Permanent e-mail address',
17380:         critical       => 'Critical notification address',
17381:         notify         => 'Notification address',
17382:         min            => 'Minimum password length',
17383:         max            => 'Maximum password length',
17384:         chars          => 'Required characters',
17385:         expire         => 'Password expiration (days)',
17386:         numsaved       => 'Number of previous passwords to save',
17387:         reset          => 'Resetting Forgotten Password',
17388:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
17389:         rules          => 'Rules for LON-CAPA Passwords',
17390:         crsownerchg    => 'Course Owner Changing Student Passwords',
17391:         username       => 'Username',
17392:         email          => 'E-mail address',
17393:     );
17394: 
17395: #
17396: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
17397: #
17398:     my (%curr_defaults,%save_defaults);
17399:     if (ref($domconfig{'defaults'}) eq 'HASH') {
17400:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
17401:             if ($key =~ /^intauth_(cost|check|switch)$/) {
17402:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
17403:             } else {
17404:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
17405:             }
17406:         }
17407:     }
17408:     my %staticdefaults = (
17409:         'resetlink'      => 2,
17410:         'resetcase'      => \@oktypes,
17411:         'resetprelink'   => 'both',
17412:         'resetemail'     => ['critical','notify','permanent'],
17413:         'intauth_cost'   => 10,
17414:         'intauth_check'  => 0,
17415:         'intauth_switch' => 0,
17416:     );
17417:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
17418:     foreach my $type (@oktypes) {
17419:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
17420:     }
17421:     my $linklife = $env{'form.passwords_link'};
17422:     $linklife =~ s/^\s+|\s+$//g;
17423:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
17424:         $newvalues{'resetlink'} = $linklife;
17425:         if ($current{'resetlink'}) {
17426:             if ($current{'resetlink'} ne $linklife) {
17427:                 $changes{'reset'} = 1;
17428:             }
17429:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
17430:             if ($staticdefaults{'resetlink'} ne $linklife) {
17431:                 $changes{'reset'} = 1;
17432:             }
17433:         }
17434:     } elsif ($current{'resetlink'}) {
17435:         $changes{'reset'} = 1;
17436:     }
17437:     my @casesens;
17438:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
17439:     foreach my $case (sort(@posscase)) {
17440:         if (grep(/^\Q$case\E$/,@oktypes)) {
17441:             push(@casesens,$case);
17442:         }
17443:     }
17444:     $newvalues{'resetcase'} = \@casesens;
17445:     if (ref($current{'resetcase'}) eq 'ARRAY') {
17446:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
17447:         if (@diffs > 0) {
17448:             $changes{'reset'} = 1;
17449:         }
17450:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
17451:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
17452:         if (@diffs > 0) {
17453:             $changes{'reset'} = 1;
17454:         }
17455:     }
17456:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
17457:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
17458:         if (exists($current{'resetprelink'})) {
17459:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
17460:                 $changes{'reset'} = 1;
17461:             }
17462:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
17463:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
17464:                 $changes{'reset'} = 1;
17465:             }
17466:         }
17467:     } elsif ($current{'resetprelink'}) {
17468:         $changes{'reset'} = 1;
17469:     }
17470:     foreach my $type (@oktypes) {
17471:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
17472:         my @postlink;
17473:         foreach my $item (sort(@possplink)) {
17474:             if ($item =~ /^(email|username)$/) {
17475:                 push(@postlink,$item);
17476:             }
17477:         }
17478:         $newvalues{'resetpostlink'}{$type} = \@postlink;
17479:         unless ($changes{'reset'}) {
17480:             if (ref($current{'resetpostlink'}) eq 'HASH') {
17481:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
17482:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
17483:                     if (@diffs > 0) {
17484:                         $changes{'reset'} = 1;
17485:                     }
17486:                 } else {
17487:                     $changes{'reset'} = 1;
17488:                 }
17489:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
17490:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
17491:                 if (@diffs > 0) {
17492:                     $changes{'reset'} = 1;
17493:                 }
17494:             }
17495:         }
17496:     }
17497:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
17498:     my @resetemail;
17499:     foreach my $item (sort(@possemailsrc)) {
17500:         if ($item =~ /^(permanent|critical|notify)$/) {
17501:             push(@resetemail,$item);
17502:         }
17503:     }
17504:     $newvalues{'resetemail'} = \@resetemail;
17505:     unless ($changes{'reset'}) {
17506:         if (ref($current{'resetemail'}) eq 'ARRAY') {
17507:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
17508:             if (@diffs > 0) {
17509:                 $changes{'reset'} = 1;
17510:             }
17511:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
17512:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
17513:             if (@diffs > 0) {
17514:                 $changes{'reset'} = 1;
17515:             }
17516:         }
17517:     }
17518:     if ($env{'form.passwords_stdtext'} == 0) {
17519:         $newvalues{'resetremove'} = 1;
17520:         unless ($current{'resetremove'}) {
17521:             $changes{'reset'} = 1;
17522:         }
17523:     } elsif ($current{'resetremove'}) {
17524:         $changes{'reset'} = 1;
17525:     }
17526:     if ($env{'form.passwords_customfile.filename'} ne '') {
17527:         my $servadm = $r->dir_config('lonAdmEMail');
17528:         my ($configuserok,$author_ok,$switchserver) =
17529:             &config_check($dom,$confname,$servadm);
17530:         my $error;
17531:         if ($configuserok eq 'ok') {
17532:             if ($switchserver) {
17533:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
17534:             } else {
17535:                 if ($author_ok eq 'ok') {
17536:                     my $modified = [];
17537:                     my ($result,$customurl) =
17538:                         &Apache::lonconfigsettings::publishlogo($r,'upload','passwords_customfile',$dom,
17539:                                                                 $confname,'customtext/resetpw','','',$customfn,
17540:                                                                 $modified);
17541:                     if ($result eq 'ok') {
17542:                         $newvalues{'resetcustom'} = $customurl;
17543:                         $changes{'reset'} = 1;
17544:                         &update_modify_urls($r,$modified);
17545:                     } else {
17546:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
17547:                     }
17548:                 } else {
17549:                     $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);
17550:                 }
17551:             }
17552:         } else {
17553:             $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);
17554:         }
17555:         if ($error) {
17556:             &Apache::lonnet::logthis($error);
17557:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
17558:         }
17559:     } elsif ($current{'resetcustom'}) {
17560:         if ($env{'form.passwords_custom_del'}) {
17561:             $changes{'reset'} = 1;
17562:         } else {
17563:             $newvalues{'resetcustom'} = $current{'resetcustom'};
17564:         }
17565:     }
17566:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
17567:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
17568:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
17569:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
17570:             $changes{'intauth'} = 1;
17571:         }
17572:     } else {
17573:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
17574:     }
17575:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
17576:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
17577:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
17578:             $changes{'intauth'} = 1;
17579:         }
17580:     } else {
17581:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
17582:     }
17583:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
17584:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
17585:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
17586:             $changes{'intauth'} = 1;
17587:         }
17588:     } else {
17589:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
17590:     }
17591:     foreach my $item ('cost','check','switch') {
17592:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
17593:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
17594:             $updatedefaults = 1;
17595:         }
17596:     }
17597:     &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
17598:     my %crsownerchg = (
17599:                         by => [],
17600:                         for => [],
17601:                       );
17602:     foreach my $item ('by','for') {
17603:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
17604:         foreach my $type (sort(@posstypes)) {
17605:             if (grep(/^\Q$type\E$/,@oktypes)) {
17606:                 push(@{$crsownerchg{$item}},$type);
17607:             }
17608:         }
17609:     }
17610:     $newvalues{'crsownerchg'} = \%crsownerchg;
17611:     if (ref($current{'crsownerchg'}) eq 'HASH') {
17612:         foreach my $item ('by','for') {
17613:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
17614:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
17615:                 if (@diffs > 0) {
17616:                     $changes{'crsownerchg'} = 1;
17617:                     last;
17618:                 }
17619:             }
17620:         }
17621:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
17622:         foreach my $item ('by','for') {
17623:             if (@{$crsownerchg{$item}} > 0) {
17624:                 $changes{'crsownerchg'} = 1;
17625:                 last;
17626:             }
17627:         }
17628:     }
17629: 
17630:     my %confighash = (
17631:                         defaults  => \%save_defaults,
17632:                         passwords => \%newvalues,
17633:                      );
17634:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
17635: 
17636:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
17637:     if ($putresult eq 'ok') {
17638:         if (keys(%changes) > 0) {
17639:             $resulttext = &mt('Changes made: ').'<ul>';
17640:             foreach my $key ('reset','intauth','rules','crsownerchg') {
17641:                 if ($changes{$key}) {
17642:                     unless ($key eq 'intauth') {
17643:                         $updateconf = 1;
17644:                     }
17645:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
17646:                     if ($key eq 'reset') {
17647:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
17648:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
17649:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
17650:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
17651:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
17652:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
17653:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
17654:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
17655:                             }
17656:                         } else {
17657:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
17658:                         }
17659:                         if ($confighash{'passwords'}{'resetlink'}) {
17660:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
17661:                         } else {
17662:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
17663:                                                   &mt('Will default to 2 hours').'</li>';
17664:                         }
17665:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
17666:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
17667:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
17668:                             } else {
17669:                                 my $casesens;
17670:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
17671:                                     if ($type eq 'default') {
17672:                                         $casesens .= $othertitle.', ';
17673:                                     } elsif ($usertypes->{$type} ne '') {
17674:                                         $casesens .= $usertypes->{$type}.', ';
17675:                                     }
17676:                                 }
17677:                                 $casesens =~ s/\Q, \E$//;
17678:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
17679:                             }
17680:                         } else {
17681:                             $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>';
17682:                         }
17683:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
17684:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
17685:                         } else {
17686:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
17687:                         }
17688:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
17689:                             my $output;
17690:                             if (ref($types) eq 'ARRAY') {
17691:                                 foreach my $type (@{$types}) {
17692:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
17693:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
17694:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
17695:                                         } else {
17696:                                             $output .= $usertypes->{$type}.' -- '.
17697:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
17698:                                         }
17699:                                     }
17700:                                 }
17701:                             }
17702:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
17703:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
17704:                                     $output .= $othertitle.' -- '.&mt('none');
17705:                                 } else {
17706:                                     $output .= $othertitle.' -- '.
17707:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
17708:                                 }
17709:                             }
17710:                             if ($output) {
17711:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
17712:                             } else {
17713:                                 $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>';
17714:                             }
17715:                         } else {
17716:                             $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>';
17717:                         }
17718:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
17719:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
17720:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
17721:                             } else {
17722:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
17723:                             }
17724:                         } else {
17725:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
17726:                         }
17727:                         if ($confighash{'passwords'}{'resetremove'}) {
17728:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
17729:                         } else {
17730:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
17731:                         }
17732:                         if ($confighash{'passwords'}{'resetcustom'}) {
17733:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
17734:                                                                             &mt('custom text'),600,500,undef,undef,
17735:                                                                             undef,undef,'background-color:#ffffff');
17736:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
17737:                         } else {
17738:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
17739:                         }
17740:                     } elsif ($key eq 'intauth') {
17741:                         foreach my $item ('cost','switch','check') {
17742:                             my $value = $save_defaults{$key.'_'.$item};
17743:                             if ($item eq 'switch') {
17744:                                 my %optiondesc = &Apache::lonlocal::texthash (
17745:                                                      0 => 'No',
17746:                                                      1 => 'Yes',
17747:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
17748:                                                  );
17749:                                 if ($value =~ /^(0|1|2)$/) {
17750:                                     $value = $optiondesc{$value};
17751:                                 } else {
17752:                                     $value = &mt('none -- defaults to No');
17753:                                 }
17754:                             } elsif ($item eq 'check') {
17755:                                 my %optiondesc = &Apache::lonlocal::texthash (
17756:                                                      0 => 'No',
17757:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
17758:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
17759:                                                  );
17760:                                 if ($value =~ /^(0|1|2)$/) {
17761:                                     $value = $optiondesc{$value};
17762:                                 } else {
17763:                                     $value = &mt('none -- defaults to No');
17764:                                 }
17765:                             }
17766:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
17767:                         }
17768:                     } elsif ($key eq 'rules') {
17769:                         foreach my $rule ('min','max','expire','numsaved') {
17770:                             if ($confighash{'passwords'}{$rule} eq '') {
17771:                                 if ($rule eq 'min') {
17772:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
17773:                                                    ' '.&mt('Default of [_1] will be used',
17774:                                                            $Apache::lonnet::passwdmin).'</li>';
17775:                                 } else {
17776:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
17777:                                 }
17778:                             } else {
17779:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
17780:                             }
17781:                         }
17782:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
17783:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
17784:                                 my %rulenames = &Apache::lonlocal::texthash(
17785:                                                      uc => 'At least one upper case letter',
17786:                                                      lc => 'At least one lower case letter',
17787:                                                      num => 'At least one number',
17788:                                                      spec => 'At least one non-alphanumeric',
17789:                                                    );
17790:                                 my $needed = '<ul><li>'.
17791:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
17792:                                              '</li></ul>';
17793:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
17794:                             } else {
17795:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
17796:                             }
17797:                         } else {
17798:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
17799:                         }
17800:                     } elsif ($key eq 'crsownerchg') {
17801:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
17802:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
17803:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
17804:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
17805:                             } else {
17806:                                 my %crsownerstr;
17807:                                 foreach my $item ('by','for') {
17808:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
17809:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
17810:                                             if ($type eq 'default') {
17811:                                                 $crsownerstr{$item} .= $othertitle.', ';
17812:                                             } elsif ($usertypes->{$type} ne '') {
17813:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
17814:                                             }
17815:                                         }
17816:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
17817:                                     }
17818:                                 }
17819:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
17820:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
17821:                             }
17822:                         } else {
17823:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
17824:                         }
17825:                     }
17826:                     $resulttext .= '</ul></li>';
17827:                 }
17828:             }
17829:             $resulttext .= '</ul>';
17830:         } else {
17831:             $resulttext = &mt('No changes made to password settings');
17832:         }
17833:         my $cachetime = 24*60*60;
17834:         if ($updatedefaults) {
17835:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17836:             if (ref($lastactref) eq 'HASH') {
17837:                 $lastactref->{'domdefaults'} = 1;
17838:             }
17839:         }
17840:         if ($updateconf) {
17841:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
17842:             if (ref($lastactref) eq 'HASH') {
17843:                 $lastactref->{'passwdconf'} = 1;
17844:             }
17845:         }
17846:     } else {
17847:         $resulttext = '<span class="LC_error">'.
17848:             &mt('An error occurred: [_1]',$putresult).'</span>';
17849:     }
17850:     if ($errors) {
17851:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
17852:                        $errors.'</ul></p>';
17853:     }
17854:     return $resulttext;
17855: }
17856: 
17857: sub password_rule_changes {
17858:     my ($prefix,$newvalues,$current,$changes) = @_;
17859:     return unless ((ref($newvalues) eq 'HASH') &&
17860:                    (ref($current) eq 'HASH') &&
17861:                    (ref($changes) eq 'HASH'));
17862:     my (@rules,%staticdefaults);
17863:     if ($prefix eq 'passwords') {
17864:         @rules = ('min','max','expire','numsaved');
17865:     } elsif (($prefix eq 'ltisecrets') || ($prefix eq 'toolsecrets')) {
17866:         @rules = ('min','max');
17867:     }
17868:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
17869:     foreach my $rule (@rules) {
17870:         $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
17871:         my $ruleok;
17872:         if ($rule eq 'expire') {
17873:             if (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+(|\.\d*)$/) &&
17874:                 ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
17875:                 $ruleok = 1;
17876:             }
17877:         } elsif ($rule eq 'min') {
17878:             if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
17879:                 if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
17880:                     $ruleok = 1;
17881:                 }
17882:             }
17883:         } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
17884:                  ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
17885:             $ruleok = 1;
17886:         }
17887:         if ($ruleok) {
17888:             $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
17889:             if (exists($current->{$rule})) {
17890:                 if ($newvalues->{$rule} ne $current->{$rule}) {
17891:                     $changes->{'rules'} = 1;
17892:                 }
17893:             } elsif ($rule eq 'min') {
17894:                 if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
17895:                     $changes->{'rules'} = 1;
17896:                 }
17897:             } else {
17898:                 $changes->{'rules'} = 1;
17899:             }
17900:         } elsif (exists($current->{$rule})) {
17901:             $changes->{'rules'} = 1;
17902:         }
17903:     }
17904:     my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
17905:     my @chars;
17906:     foreach my $item (sort(@posschars)) {
17907:         if ($item =~ /^(uc|lc|num|spec)$/) {
17908:             push(@chars,$item);
17909:         }
17910:     }
17911:     $newvalues->{'chars'} = \@chars;
17912:     unless ($changes->{'rules'}) {
17913:         if (ref($current->{'chars'}) eq 'ARRAY') {
17914:             my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
17915:             if (@diffs > 0) {
17916:                 $changes->{'rules'} = 1;
17917:             }
17918:         } else {
17919:             if (@chars > 0) {
17920:                 $changes->{'rules'} = 1;
17921:             }
17922:         }
17923:     }
17924:     return;
17925: }
17926: 
17927: sub modify_usercreation {
17928:     my ($dom,%domconfig) = @_;
17929:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
17930:     my $warningmsg;
17931:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
17932:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
17933:             if ($key eq 'cancreate') {
17934:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
17935:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
17936:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
17937:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17938:                         } else {
17939:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17940:                         }
17941:                     }
17942:                 }
17943:             } elsif ($key eq 'email_rule') {
17944:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
17945:             } else {
17946:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
17947:             }
17948:         }
17949:     }
17950:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
17951:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
17952:     my @contexts = ('author','course','requestcrs');
17953:     foreach my $item(@contexts) {
17954:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
17955:     }
17956:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17957:         foreach my $item (@contexts) {
17958:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
17959:                 push(@{$changes{'cancreate'}},$item);
17960:             }
17961:         }
17962:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
17963:         foreach my $item (@contexts) {
17964:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
17965:                 if ($cancreate{$item} ne 'any') {
17966:                     push(@{$changes{'cancreate'}},$item);
17967:                 }
17968:             } else {
17969:                 if ($cancreate{$item} ne 'none') {
17970:                     push(@{$changes{'cancreate'}},$item);
17971:                 }
17972:             }
17973:         }
17974:     } else {
17975:         foreach my $item (@contexts)  {
17976:             push(@{$changes{'cancreate'}},$item);
17977:         }
17978:     }
17979: 
17980:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
17981:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
17982:             if (!grep(/^\Q$type\E$/,@username_rule)) {
17983:                 push(@{$changes{'username_rule'}},$type);
17984:             }
17985:         }
17986:         foreach my $type (@username_rule) {
17987:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
17988:                 push(@{$changes{'username_rule'}},$type);
17989:             }
17990:         }
17991:     } else {
17992:         push(@{$changes{'username_rule'}},@username_rule);
17993:     }
17994: 
17995:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
17996:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
17997:             if (!grep(/^\Q$type\E$/,@id_rule)) {
17998:                 push(@{$changes{'id_rule'}},$type);
17999:             }
18000:         }
18001:         foreach my $type (@id_rule) {
18002:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
18003:                 push(@{$changes{'id_rule'}},$type);
18004:             }
18005:         }
18006:     } else {
18007:         push(@{$changes{'id_rule'}},@id_rule);
18008:     }
18009: 
18010:     my @authen_contexts = ('author','course','domain');
18011:     my @authtypes = ('int','krb4','krb5','loc','lti');
18012:     my %authhash;
18013:     foreach my $item (@authen_contexts) {
18014:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
18015:         foreach my $auth (@authtypes) {
18016:             if (grep(/^\Q$auth\E$/,@authallowed)) {
18017:                 $authhash{$item}{$auth} = 1;
18018:             } else {
18019:                 $authhash{$item}{$auth} = 0;
18020:             }
18021:         }
18022:     }
18023:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
18024:         foreach my $item (@authen_contexts) {
18025:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
18026:                 foreach my $auth (@authtypes) {
18027:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
18028:                         push(@{$changes{'authtypes'}},$item);
18029:                         last;
18030:                     }
18031:                 }
18032:             }
18033:         }
18034:     } else {
18035:         foreach my $item (@authen_contexts) {
18036:             push(@{$changes{'authtypes'}},$item);
18037:         }
18038:     }
18039: 
18040:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
18041:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
18042:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
18043:     $save_usercreate{'id_rule'} = \@id_rule;
18044:     $save_usercreate{'username_rule'} = \@username_rule,
18045:     $save_usercreate{'authtypes'} = \%authhash;
18046: 
18047:     my %usercreation_hash =  (
18048:         usercreation     => \%save_usercreate,
18049:     );
18050: 
18051:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
18052:                                              $dom);
18053: 
18054:     if ($putresult eq 'ok') {
18055:         if (keys(%changes) > 0) {
18056:             $resulttext = &mt('Changes made:').'<ul>';
18057:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
18058:                 my %lt = &usercreation_types();
18059:                 foreach my $type (@{$changes{'cancreate'}}) {
18060:                     my $chgtext = $lt{$type}.', ';
18061:                     if ($cancreate{$type} eq 'none') {
18062:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
18063:                     } elsif ($cancreate{$type} eq 'any') {
18064:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
18065:                     } elsif ($cancreate{$type} eq 'official') {
18066:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
18067:                     } elsif ($cancreate{$type} eq 'unofficial') {
18068:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
18069:                     }
18070:                     $resulttext .= '<li>'.$chgtext.'</li>';
18071:                 }
18072:             }
18073:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
18074:                 my ($rules,$ruleorder) = 
18075:                     &Apache::lonnet::inst_userrules($dom,'username');
18076:                 my $chgtext = '<ul>';
18077:                 foreach my $type (@username_rule) {
18078:                     if (ref($rules->{$type}) eq 'HASH') {
18079:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
18080:                     }
18081:                 }
18082:                 $chgtext .= '</ul>';
18083:                 if (@username_rule > 0) {
18084:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
18085:                 } else {
18086:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
18087:                 }
18088:             }
18089:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
18090:                 my ($idrules,$idruleorder) = 
18091:                     &Apache::lonnet::inst_userrules($dom,'id');
18092:                 my $chgtext = '<ul>';
18093:                 foreach my $type (@id_rule) {
18094:                     if (ref($idrules->{$type}) eq 'HASH') {
18095:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
18096:                     }
18097:                 }
18098:                 $chgtext .= '</ul>';
18099:                 if (@id_rule > 0) {
18100:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
18101:                 } else {
18102:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
18103:                 }
18104:             }
18105:             my %authname = &authtype_names();
18106:             my %context_title = &context_names();
18107:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
18108:                 my $chgtext = '<ul>';
18109:                 foreach my $type (@{$changes{'authtypes'}}) {
18110:                     my @allowed;
18111:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
18112:                     foreach my $auth (@authtypes) {
18113:                         if ($authhash{$type}{$auth}) {
18114:                             push(@allowed,$authname{$auth});
18115:                         }
18116:                     }
18117:                     if (@allowed > 0) {
18118:                         $chgtext .= join(', ',@allowed).'</li>';
18119:                     } else {
18120:                         $chgtext .= &mt('none').'</li>';
18121:                     }
18122:                 }
18123:                 $chgtext .= '</ul>';
18124:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
18125:                 $resulttext .= '</li>';
18126:             }
18127:             $resulttext .= '</ul>';
18128:         } else {
18129:             $resulttext = &mt('No changes made to user creation settings');
18130:         }
18131:     } else {
18132:         $resulttext = '<span class="LC_error">'.
18133:             &mt('An error occurred: [_1]',$putresult).'</span>';
18134:     }
18135:     if ($warningmsg ne '') {
18136:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
18137:     }
18138:     return $resulttext;
18139: }
18140: 
18141: sub modify_selfcreation {
18142:     my ($dom,$lastactref,%domconfig) = @_;
18143:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
18144:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
18145:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18146:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
18147:     if (ref($typesref) eq 'ARRAY') {
18148:         @types = @{$typesref};
18149:     }
18150:     if (ref($usertypesref) eq 'HASH') {
18151:         %usertypes = %{$usertypesref};
18152:     }
18153:     $usertypes{'default'} = $othertitle;
18154: #
18155: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
18156: #
18157:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18158:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18159:             if ($key eq 'cancreate') {
18160:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18161:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18162:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
18163:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
18164:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
18165:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
18166:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
18167:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
18168:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18169:                         } else {
18170:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18171:                         }
18172:                     }
18173:                 }
18174:             } elsif ($key eq 'email_rule') {
18175:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18176:             } else {
18177:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18178:             }
18179:         }
18180:     }
18181: #
18182: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
18183: #
18184:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
18185:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
18186:             if ($key eq 'selfcreate') {
18187:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
18188:             } else {
18189:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
18190:             }
18191:         }
18192:     }
18193: #
18194: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
18195: #
18196:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18197:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
18198:             if ($key eq 'inststatusguest') {
18199:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
18200:             } else {
18201:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
18202:             }
18203:         }
18204:     }
18205: 
18206:     my @contexts = ('selfcreate');
18207:     @{$cancreate{'selfcreate'}} = ();
18208:     %{$cancreate{'emailusername'}} = ();
18209:     if (@types) {
18210:         @{$cancreate{'statustocreate'}} = ();
18211:     }
18212:     %{$cancreate{'selfcreateprocessing'}} = ();
18213:     %{$cancreate{'shibenv'}} = ();
18214:     %{$cancreate{'emailverified'}} = ();
18215:     %{$cancreate{'emailoptions'}} = ();
18216:     %{$cancreate{'emaildomain'}} = ();
18217:     my %selfcreatetypes = (
18218:                              sso   => 'users authenticated by institutional single sign on',
18219:                              login => 'users authenticated by institutional log-in',
18220:                              email => 'users verified by e-mail',
18221:                           );
18222: #
18223: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
18224: # is permitted.
18225: #
18226:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
18227: 
18228:     my (@statuses,%email_rule);
18229:     foreach my $item ('login','sso','email') {
18230:         if ($item eq 'email') {
18231:             if ($env{'form.cancreate_email'}) {
18232:                 if (@types) {
18233:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
18234:                     foreach my $status (@poss_statuses) {
18235:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
18236:                             push(@statuses,$status);
18237:                         }
18238:                     }
18239:                     $save_inststatus{'inststatusguest'} = \@statuses;
18240:                 } else {
18241:                     push(@statuses,'default');
18242:                 }
18243:                 if (@statuses) {
18244:                     my %curr_rule;
18245:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
18246:                         foreach my $type (@statuses) {
18247:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
18248:                         }
18249:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
18250:                         foreach my $type (@statuses) {
18251:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
18252:                         }
18253:                     }
18254:                     push(@{$cancreate{'selfcreate'}},'email');
18255:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
18256:                     my %curremaildom;
18257:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
18258:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
18259:                     }
18260:                     foreach my $type (@statuses) {
18261:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
18262:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
18263:                         }
18264:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
18265:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
18266:                         }
18267:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
18268: #
18269: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
18270: #
18271:                             my $chosen = $1;
18272:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
18273:                                 my $emaildom;
18274:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
18275:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type};
18276:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
18277:                                     if (ref($curremaildom{$type}) eq 'HASH') {
18278:                                         if (exists($curremaildom{$type}{$chosen})) {
18279:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
18280:                                                 push(@{$changes{'cancreate'}},'emaildomain');
18281:                                             }
18282:                                         } elsif ($emaildom ne '') {
18283:                                             push(@{$changes{'cancreate'}},'emaildomain');
18284:                                         }
18285:                                     } elsif ($emaildom ne '') {
18286:                                         push(@{$changes{'cancreate'}},'emaildomain');
18287:                                     }
18288:                                 }
18289:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
18290:                             } elsif ($chosen eq 'custom') {
18291:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
18292:                                 $email_rule{$type} = [];
18293:                                 if (ref($emailrules) eq 'HASH') {
18294:                                     foreach my $rule (@possemail_rules) {
18295:                                         if (exists($emailrules->{$rule})) {
18296:                                             push(@{$email_rule{$type}},$rule);
18297:                                         }
18298:                                     }
18299:                                 }
18300:                                 if (@{$email_rule{$type}}) {
18301:                                     $cancreate{'emailoptions'}{$type} = 'custom';
18302:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
18303:                                         if (@{$curr_rule{$type}} > 0) {
18304:                                             foreach my $rule (@{$curr_rule{$type}}) {
18305:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
18306:                                                     push(@{$changes{'email_rule'}},$type);
18307:                                                 }
18308:                                             }
18309:                                         }
18310:                                         foreach my $type (@{$email_rule{$type}}) {
18311:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
18312:                                                 push(@{$changes{'email_rule'}},$type);
18313:                                             }
18314:                                         }
18315:                                     } else {
18316:                                         push(@{$changes{'email_rule'}},$type);
18317:                                     }
18318:                                 }
18319:                             } else {
18320:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
18321:                             }
18322:                         }
18323:                     }
18324:                     if (@types) {
18325:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
18326:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
18327:                             if (@changed) {
18328:                                 push(@{$changes{'inststatus'}},'inststatusguest');
18329:                             }
18330:                         } else {
18331:                             push(@{$changes{'inststatus'}},'inststatusguest');
18332:                         }
18333:                     }
18334:                 } else {
18335:                     delete($env{'form.cancreate_email'});
18336:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
18337:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
18338:                             push(@{$changes{'inststatus'}},'inststatusguest');
18339:                         }
18340:                     }
18341:                 }
18342:             } else {
18343:                 $save_inststatus{'inststatusguest'} = [];
18344:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
18345:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
18346:                         push(@{$changes{'inststatus'}},'inststatusguest');
18347:                     }
18348:                 }
18349:             }
18350:         } else {
18351:             if ($env{'form.cancreate_'.$item}) {
18352:                 push(@{$cancreate{'selfcreate'}},$item);
18353:             }
18354:         }
18355:     }
18356:     my (%userinfo,%savecaptcha);
18357:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
18358: #
18359: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
18360: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
18361: #
18362: 
18363:     if ($env{'form.cancreate_email'}) {
18364:         push(@contexts,'emailusername');
18365:         if (@statuses) {
18366:             foreach my $type (@statuses) {
18367:                 if (ref($infofields) eq 'ARRAY') {
18368:                     foreach my $field (@{$infofields}) {
18369:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
18370:                             $cancreate{'emailusername'}{$type}{$field} = $1;
18371:                         }
18372:                     }
18373:                 }
18374:             }
18375:         }
18376: #
18377: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
18378: # queued requests for self-creation of account verified by e-mail.
18379: #
18380: 
18381:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
18382:         @approvalnotify = sort(@approvalnotify);
18383:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
18384:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
18385:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
18386:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
18387:                     push(@{$changes{'cancreate'}},'notify');
18388:                 }
18389:             } else {
18390:                 if ($cancreate{'notify'}{'approval'}) {
18391:                     push(@{$changes{'cancreate'}},'notify');
18392:                 }
18393:             }
18394:         } elsif ($cancreate{'notify'}{'approval'}) {
18395:             push(@{$changes{'cancreate'}},'notify');
18396:         }
18397: 
18398:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
18399:     }
18400: #  
18401: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
18402: # institutional log-in.
18403: #
18404:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
18405:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
18406:                ($domdefaults{'auth_def'} eq 'localauth'))) {
18407:             $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.').' '.
18408:                           &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.');
18409:         }
18410:     }
18411:     my @fields = ('lastname','firstname','middlename','generation',
18412:                   'permanentemail','id');
18413:     my @shibfields = (@fields,'inststatus');
18414:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
18415: #
18416: # Where usernames may created for institutional log-in and/or institutional single sign on:
18417: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
18418: # may self-create accounts 
18419: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
18420: # which the user may supply, if institutional data is unavailable.
18421: #
18422:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
18423:         if (@types) {
18424:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
18425:             push(@contexts,'statustocreate');
18426:             foreach my $type (@types) {
18427:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
18428:                 foreach my $field (@fields) {
18429:                     if (grep(/^\Q$field\E$/,@modifiable)) {
18430:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
18431:                     } else {
18432:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
18433:                     }
18434:                 }
18435:             }
18436:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
18437:                 foreach my $type (@types) {
18438:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
18439:                         foreach my $field (@fields) {
18440:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
18441:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
18442:                                 push(@{$changes{'selfcreate'}},$type);
18443:                                 last;
18444:                             }
18445:                         }
18446:                     }
18447:                 }
18448:             } else {
18449:                 foreach my $type (@types) {
18450:                     push(@{$changes{'selfcreate'}},$type);
18451:                 }
18452:             }
18453:         }
18454:         foreach my $field (@shibfields) {
18455:             if ($env{'form.shibenv_'.$field} ne '') {
18456:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
18457:             }
18458:         }
18459:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
18460:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
18461:                 foreach my $field (@shibfields) {
18462:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
18463:                         push(@{$changes{'cancreate'}},'shibenv');
18464:                     }
18465:                 }
18466:             } else {
18467:                 foreach my $field (@shibfields) {
18468:                     if ($env{'form.shibenv_'.$field}) {
18469:                         push(@{$changes{'cancreate'}},'shibenv');
18470:                         last;
18471:                     }
18472:                 }
18473:             }
18474:         }
18475:     }
18476:     foreach my $item (@contexts) {
18477:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
18478:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
18479:                 if (ref($cancreate{$item}) eq 'ARRAY') {
18480:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
18481:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18482:                             push(@{$changes{'cancreate'}},$item);
18483:                         }
18484:                     }
18485:                 }
18486:             }
18487:             if (ref($cancreate{$item}) eq 'ARRAY') {
18488:                 foreach my $type (@{$cancreate{$item}}) {
18489:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
18490:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18491:                             push(@{$changes{'cancreate'}},$item);
18492:                         }
18493:                     }
18494:                 }
18495:             }
18496:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
18497:             if (ref($cancreate{$item}) eq 'HASH') {
18498:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
18499:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
18500:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
18501:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
18502:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18503:                                     push(@{$changes{'cancreate'}},$item);
18504:                                 }
18505:                             }
18506:                         }
18507:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
18508:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
18509:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18510:                                 push(@{$changes{'cancreate'}},$item);
18511:                             }
18512:                         }
18513:                     }
18514:                 }
18515:                 foreach my $type (keys(%{$cancreate{$item}})) {
18516:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
18517:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
18518:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
18519:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
18520:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18521:                                         push(@{$changes{'cancreate'}},$item);
18522:                                     }
18523:                                 }
18524:                             } else {
18525:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18526:                                     push(@{$changes{'cancreate'}},$item);
18527:                                 }
18528:                             }
18529:                         }
18530:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
18531:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
18532:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18533:                                 push(@{$changes{'cancreate'}},$item);
18534:                             }
18535:                         }
18536:                     }
18537:                 }
18538:             }
18539:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
18540:             if (ref($cancreate{$item}) eq 'ARRAY') {
18541:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
18542:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18543:                         push(@{$changes{'cancreate'}},$item);
18544:                     }
18545:                 }
18546:             }
18547:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
18548:             if (ref($cancreate{$item}) eq 'HASH') {
18549:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18550:                     push(@{$changes{'cancreate'}},$item);
18551:                 }
18552:             }
18553:         } elsif ($item eq 'emailusername') {
18554:             if (ref($cancreate{$item}) eq 'HASH') {
18555:                 foreach my $type (keys(%{$cancreate{$item}})) {
18556:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
18557:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
18558:                             if ($cancreate{$item}{$type}{$field}) {
18559:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
18560:                                     push(@{$changes{'cancreate'}},$item);
18561:                                 }
18562:                                 last;
18563:                             }
18564:                         }
18565:                     }
18566:                 }
18567:             }
18568:         }
18569:     }
18570: #
18571: # Populate %save_usercreate hash with updates to self-creation configuration.
18572: #
18573:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
18574:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
18575:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
18576:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
18577:     if (ref($cancreate{'notify'}) eq 'HASH') {
18578:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
18579:     }
18580:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
18581:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
18582:     }
18583:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
18584:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
18585:     }
18586:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
18587:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
18588:     }
18589:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
18590:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
18591:     }
18592:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
18593:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
18594:     }
18595:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
18596:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
18597:     }
18598:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
18599:     $save_usercreate{'email_rule'} = \%email_rule;
18600: 
18601:     my %userconfig_hash = (
18602:             usercreation     => \%save_usercreate,
18603:             usermodification => \%save_usermodify,
18604:             inststatus       => \%save_inststatus,
18605:     );
18606: 
18607:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
18608:                                              $dom);
18609: #
18610: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
18611: #
18612:     if ($putresult eq 'ok') {
18613:         if (keys(%changes) > 0) {
18614:             $resulttext = &mt('Changes made:').'<ul>';
18615:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
18616:                 my %lt = &selfcreation_types();
18617:                 foreach my $type (@{$changes{'cancreate'}}) {
18618:                     my $chgtext = '';
18619:                     if ($type eq 'selfcreate') {
18620:                         if (@{$cancreate{$type}} == 0) {
18621:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
18622:                         } else {
18623:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
18624:                                         '<ul>';
18625:                             foreach my $case (@{$cancreate{$type}}) {
18626:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
18627:                             }
18628:                             $chgtext .= '</ul>';
18629:                             if (ref($cancreate{$type}) eq 'ARRAY') {
18630:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
18631:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
18632:                                         if (@{$cancreate{'statustocreate'}} == 0) {
18633:                                             $chgtext .= '<span class="LC_warning">'.
18634:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
18635:                                                         '</span><br />';
18636:                                         }
18637:                                     }
18638:                                 }
18639:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
18640:                                     if (!@statuses) {
18641:                                         $chgtext .= '<span class="LC_warning">'.
18642:                                                     &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.").
18643:                                                     '</span><br />';
18644: 
18645:                                     }
18646:                                 }
18647:                             }
18648:                         }
18649:                     } elsif ($type eq 'shibenv') {
18650:                         if (keys(%{$cancreate{$type}}) == 0) {
18651:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
18652:                         } else {
18653:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
18654:                                         '<ul>';
18655:                             foreach my $field (@shibfields) {
18656:                                 next if ($cancreate{$type}{$field} eq '');
18657:                                 if ($field eq 'inststatus') {
18658:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
18659:                                 } else {
18660:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
18661:                                 }
18662:                             }
18663:                             $chgtext .= '</ul>';
18664:                         }
18665:                     } elsif ($type eq 'statustocreate') {
18666:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
18667:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
18668:                             if (@{$cancreate{'selfcreate'}} > 0) {
18669:                                 if (@{$cancreate{'statustocreate'}} == 0) {
18670:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
18671:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
18672:                                         $chgtext .= '<br />'.
18673:                                                     '<span class="LC_warning">'.
18674:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
18675:                                                     '</span>';
18676:                                     }
18677:                                 } elsif (keys(%usertypes) > 0) {
18678:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
18679:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
18680:                                     } else {
18681:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
18682:                                     }
18683:                                     $chgtext .= '<ul>';
18684:                                     foreach my $case (@{$cancreate{$type}}) {
18685:                                         if ($case eq 'default') {
18686:                                             $chgtext .= '<li>'.$othertitle.'</li>';
18687:                                         } else {
18688:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
18689:                                         }
18690:                                     }
18691:                                     $chgtext .= '</ul>';
18692:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
18693:                                         $chgtext .= '<span class="LC_warning">'.
18694:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
18695:                                                     '</span>';
18696:                                     }
18697:                                 }
18698:                             } else {
18699:                                 if (@{$cancreate{$type}} == 0) {
18700:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
18701:                                 } else {
18702:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
18703:                                 }
18704:                             }
18705:                             $chgtext .= '<br />';
18706:                         }
18707:                     } elsif ($type eq 'selfcreateprocessing') {
18708:                         my %choices = &Apache::lonlocal::texthash (
18709:                                                                     automatic => 'Automatic approval',
18710:                                                                     approval  => 'Queued for approval',
18711:                                                                   );
18712:                         if (@types) {
18713:                             if (@statuses) {
18714:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:').
18715:                                             '<ul>';
18716:                                 foreach my $status (@statuses) {
18717:                                     if ($status eq 'default') {
18718:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
18719:                                     } else {
18720:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
18721:                                     }
18722:                                 }
18723:                                 $chgtext .= '</ul>';
18724:                             }
18725:                         } else {
18726:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
18727:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
18728:                         }
18729:                     } elsif ($type eq 'emailverified') {
18730:                         my %options = &Apache::lonlocal::texthash (
18731:                                                                     all   => 'Same as e-mail',
18732:                                                                     first => 'Omit @domain',
18733:                                                                     free  => 'Free to choose',
18734:                                                                   );
18735:                         if (@types) {
18736:                             if (@statuses) {
18737:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
18738:                                             '<ul>';
18739:                                 foreach my $status (@statuses) {
18740:                                     if ($status eq 'default') {
18741:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
18742:                                     } else {
18743:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
18744:                                     }
18745:                                 }
18746:                                 $chgtext .= '</ul>';
18747:                             }
18748:                         } else {
18749:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
18750:                                             $options{$cancreate{'emailverified'}{'default'}});
18751:                         }
18752:                     } elsif ($type eq 'emailoptions') {
18753:                         my %options = &Apache::lonlocal::texthash (
18754:                                                                     any     => 'Any e-mail',
18755:                                                                     inst    => 'Institutional only',
18756:                                                                     noninst => 'Non-institutional only',
18757:                                                                     custom  => 'Custom restrictions',
18758:                                                                   );
18759:                         if (@types) {
18760:                             if (@statuses) {
18761:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
18762:                                             '<ul>';
18763:                                 foreach my $status (@statuses) {
18764:                                     if ($type eq 'default') {
18765:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
18766:                                     } else {
18767:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
18768:                                     }
18769:                                 }
18770:                                 $chgtext .= '</ul>';
18771:                             }
18772:                         } else {
18773:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
18774:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
18775:                             } else {
18776:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
18777:                                                 $options{$cancreate{'emailoptions'}{'default'}});
18778:                             }
18779:                         }
18780:                     } elsif ($type eq 'emaildomain') {
18781:                         my $output;
18782:                         if (@statuses) {
18783:                             foreach my $type (@statuses) {
18784:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
18785:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
18786:                                         if ($type eq 'default') {
18787:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18788:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
18789:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
18790:                                             } else {
18791:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
18792:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
18793:                                             }
18794:                                         } else {
18795:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18796:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
18797:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
18798:                                             } else {
18799:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
18800:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
18801:                                             }
18802:                                         }
18803:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
18804:                                         if ($type eq 'default') {
18805:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18806:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
18807:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
18808:                                             } else {
18809:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
18810:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
18811:                                             }
18812:                                         } else {
18813:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18814:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
18815:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
18816:                                             } else {
18817:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
18818:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
18819:                                             }
18820:                                         }
18821:                                     }
18822:                                 }
18823:                             }
18824:                         }
18825:                         if ($output ne '') {
18826:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
18827:                                         '<ul>'.$output.'</ul>';
18828:                         }
18829:                     } elsif ($type eq 'captcha') {
18830:                         if ($savecaptcha{$type} eq 'notused') {
18831:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
18832:                         } else {
18833:                             my %captchas = &captcha_phrases();
18834:                             if ($captchas{$savecaptcha{$type}}) {
18835:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
18836:                             } else {
18837:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
18838:                             }
18839:                         }
18840:                     } elsif ($type eq 'recaptchakeys') {
18841:                         my ($privkey,$pubkey);
18842:                         if (ref($savecaptcha{$type}) eq 'HASH') {
18843:                             $pubkey = $savecaptcha{$type}{'public'};
18844:                             $privkey = $savecaptcha{$type}{'private'};
18845:                         }
18846:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
18847:                         if (!$pubkey) {
18848:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
18849:                         } else {
18850:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
18851:                         }
18852:                         if (!$privkey) {
18853:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
18854:                         } else {
18855:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
18856:                         }
18857:                         $chgtext .= '</ul>';
18858:                     } elsif ($type eq 'recaptchaversion') {
18859:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
18860:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
18861:                         }
18862:                     } elsif ($type eq 'emailusername') {
18863:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
18864:                             if (@statuses) {
18865:                                 foreach my $type (@statuses) {
18866:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
18867:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
18868:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
18869:                                                     '<ul>';
18870:                                             foreach my $field (@{$infofields}) {
18871:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
18872:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
18873:                                                 }
18874:                                             }
18875:                                             $chgtext .= '</ul>';
18876:                                         } else {
18877:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
18878:                                         }
18879:                                     } else {
18880:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
18881:                                     }
18882:                                 }
18883:                             }
18884:                         }
18885:                     } elsif ($type eq 'notify') {
18886:                         my $numapprove = 0;
18887:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
18888:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
18889:                                 if ($cancreate{'notify'}{'approval'}) {
18890:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
18891:                                     $numapprove ++;
18892:                                 }
18893:                             }
18894:                         }
18895:                         unless ($numapprove) {
18896:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
18897:                         }
18898:                     }
18899:                     if ($chgtext) {
18900:                         $resulttext .= '<li>'.$chgtext.'</li>';
18901:                     }
18902:                 }
18903:             }
18904:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
18905:                 my ($emailrules,$emailruleorder) =
18906:                     &Apache::lonnet::inst_userrules($dom,'email');
18907:                 foreach my $type (@{$changes{'email_rule'}}) {
18908:                     if (ref($email_rule{$type}) eq 'ARRAY') {
18909:                         my $chgtext = '<ul>';
18910:                         foreach my $rule (@{$email_rule{$type}}) {
18911:                             if (ref($emailrules->{$rule}) eq 'HASH') {
18912:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
18913:                             }
18914:                         }
18915:                         $chgtext .= '</ul>';
18916:                         my $typename;
18917:                         if (@types) {
18918:                             if ($type eq 'default') {
18919:                                 $typename = $othertitle;
18920:                             } else {
18921:                                 $typename = $usertypes{$type};
18922:                             }
18923:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
18924:                         }
18925:                         if (@{$email_rule{$type}} > 0) {
18926:                             $resulttext .= '<li>'.
18927:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
18928:                                                $usertypes{$type}).
18929:                                            $chgtext.
18930:                                            '</li>';
18931:                         } else {
18932:                             $resulttext .= '<li>'.
18933:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
18934:                                            '</li>'.
18935:                                            &mt('(Affiliation: [_1])',$typename);
18936:                         }
18937:                     }
18938:                 }
18939:             }
18940:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
18941:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
18942:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
18943:                         my $chgtext = '<ul>';
18944:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
18945:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
18946:                         }
18947:                         $chgtext .= '</ul>';
18948:                         $resulttext .= '<li>'.
18949:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
18950:                                           $chgtext.
18951:                                        '</li>';
18952:                     } else {
18953:                         $resulttext .= '<li>'.
18954:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
18955:                                        '</li>';
18956:                     }
18957:                 }
18958:             }
18959:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
18960:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
18961:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
18962:                 foreach my $type (@{$changes{'selfcreate'}}) {
18963:                     my $typename = $type;
18964:                     if (keys(%usertypes) > 0) {
18965:                         if ($usertypes{$type} ne '') {
18966:                             $typename = $usertypes{$type};
18967:                         }
18968:                     }
18969:                     my @modifiable;
18970:                     $resulttext .= '<li>'.
18971:                                     &mt('Self-creation of account by users with status: [_1]',
18972:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
18973:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
18974:                     foreach my $field (@fields) {
18975:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
18976:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
18977:                         }
18978:                     }
18979:                     if (@modifiable > 0) {
18980:                         $resulttext .= join(', ',@modifiable);
18981:                     } else {
18982:                         $resulttext .= &mt('none');
18983:                     }
18984:                     $resulttext .= '</li>';
18985:                 }
18986:                 $resulttext .= '</ul></li>';
18987:             }
18988:             $resulttext .= '</ul>';
18989:             my $cachetime = 24*60*60;
18990:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
18991:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18992:             if (ref($lastactref) eq 'HASH') {
18993:                 $lastactref->{'domdefaults'} = 1;
18994:             }
18995:         } else {
18996:             $resulttext = &mt('No changes made to self-creation settings');
18997:         }
18998:     } else {
18999:         $resulttext = '<span class="LC_error">'.
19000:             &mt('An error occurred: [_1]',$putresult).'</span>';
19001:     }
19002:     if ($warningmsg ne '') {
19003:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
19004:     }
19005:     return $resulttext;
19006: }
19007: 
19008: sub process_captcha {
19009:     my ($container,$changes,$newsettings,$currsettings) = @_;
19010:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
19011:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
19012:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
19013:         $newsettings->{'captcha'} = 'original';
19014:     }
19015:     my %current;
19016:     if (ref($currsettings) eq 'HASH') {
19017:         %current = %{$currsettings};
19018:     }
19019:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
19020:         if ($container eq 'cancreate') {
19021:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19022:                 push(@{$changes->{'cancreate'}},'captcha');
19023:             } elsif (!defined($changes->{'cancreate'})) {
19024:                 $changes->{'cancreate'} = ['captcha'];
19025:             }
19026:         } elsif ($container eq 'passwords') {
19027:             $changes->{'reset'} = 1;
19028:         } else {
19029:             $changes->{'captcha'} = 1;
19030:         }
19031:     }
19032:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
19033:     if ($newsettings->{'captcha'} eq 'recaptcha') {
19034:         $newpub = $env{'form.'.$container.'_recaptchapub'};
19035:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
19036:         $newpub =~ s/[^\w\-]//g;
19037:         $newpriv =~ s/[^\w\-]//g;
19038:         $newsettings->{'recaptchakeys'} = {
19039:                                              public  => $newpub,
19040:                                              private => $newpriv,
19041:                                           };
19042:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
19043:         $newversion =~ s/\D//g;
19044:         if ($newversion ne '2') {
19045:             $newversion = 1;
19046:         }
19047:         $newsettings->{'recaptchaversion'} = $newversion;
19048:     }
19049:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
19050:         $currpub = $current{'recaptchakeys'}{'public'};
19051:         $currpriv = $current{'recaptchakeys'}{'private'};
19052:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
19053:             $newsettings->{'recaptchakeys'} = {
19054:                                                  public  => '',
19055:                                                  private => '',
19056:                                               }
19057:         }
19058:     }
19059:     if ($current{'captcha'} eq 'recaptcha') {
19060:         $currversion = $current{'recaptchaversion'};
19061:         if ($currversion ne '2') {
19062:             $currversion = 1;
19063:         }
19064:     }
19065:     if ($currversion ne $newversion) {
19066:         if ($container eq 'cancreate') {
19067:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19068:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
19069:             } elsif (!defined($changes->{'cancreate'})) {
19070:                 $changes->{'cancreate'} = ['recaptchaversion'];
19071:             }
19072:         } elsif ($container eq 'passwords') {
19073:             $changes->{'reset'} = 1;
19074:         } else {
19075:             $changes->{'recaptchaversion'} = 1;
19076:         }
19077:     }
19078:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
19079:         if ($container eq 'cancreate') {
19080:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19081:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
19082:             } elsif (!defined($changes->{'cancreate'})) {
19083:                 $changes->{'cancreate'} = ['recaptchakeys'];
19084:             }
19085:         } elsif ($container eq 'passwords') {
19086:             $changes->{'reset'} = 1;
19087:         } else {
19088:             $changes->{'recaptchakeys'} = 1;
19089:         }
19090:     }
19091:     return;
19092: }
19093: 
19094: sub modify_usermodification {
19095:     my ($dom,%domconfig) = @_;
19096:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
19097:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
19098:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
19099:             if ($key eq 'selfcreate') {
19100:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
19101:             } else {  
19102:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
19103:             }
19104:         }
19105:     }
19106:     my @contexts = ('author','course');
19107:     my %context_title = (
19108:                            author => 'In author context',
19109:                            course => 'In course context',
19110:                         );
19111:     my @fields = ('lastname','firstname','middlename','generation',
19112:                   'permanentemail','id');
19113:     my %roles = (
19114:                   author => ['ca','aa'],
19115:                   course => ['st','ep','ta','in','cr'],
19116:                 );
19117:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19118:     foreach my $context (@contexts) {
19119:         foreach my $role (@{$roles{$context}}) {
19120:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
19121:             foreach my $item (@fields) {
19122:                 if (grep(/^\Q$item\E$/,@modifiable)) {
19123:                     $modifyhash{$context}{$role}{$item} = 1;
19124:                 } else {
19125:                     $modifyhash{$context}{$role}{$item} = 0;
19126:                 }
19127:             }
19128:         }
19129:         if (ref($curr_usermodification{$context}) eq 'HASH') {
19130:             foreach my $role (@{$roles{$context}}) {
19131:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
19132:                     foreach my $field (@fields) {
19133:                         if ($modifyhash{$context}{$role}{$field} ne 
19134:                                 $curr_usermodification{$context}{$role}{$field}) {
19135:                             push(@{$changes{$context}},$role);
19136:                             last;
19137:                         }
19138:                     }
19139:                 }
19140:             }
19141:         } else {
19142:             foreach my $context (@contexts) {
19143:                 foreach my $role (@{$roles{$context}}) {
19144:                     push(@{$changes{$context}},$role);
19145:                 }
19146:             }
19147:         }
19148:     }
19149:     my %usermodification_hash =  (
19150:                                    usermodification => \%modifyhash,
19151:                                  );
19152:     my $putresult = &Apache::lonnet::put_dom('configuration',
19153:                                              \%usermodification_hash,$dom);
19154:     if ($putresult eq 'ok') {
19155:         if (keys(%changes) > 0) {
19156:             $resulttext = &mt('Changes made: ').'<ul>';
19157:             foreach my $context (@contexts) {
19158:                 if (ref($changes{$context}) eq 'ARRAY') {
19159:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
19160:                     if (ref($changes{$context}) eq 'ARRAY') {
19161:                         foreach my $role (@{$changes{$context}}) {
19162:                             my $rolename;
19163:                             if ($role eq 'cr') {
19164:                                 $rolename = &mt('Custom');
19165:                             } else {
19166:                                 $rolename = &Apache::lonnet::plaintext($role);
19167:                             }
19168:                             my @modifiable;
19169:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
19170:                             foreach my $field (@fields) {
19171:                                 if ($modifyhash{$context}{$role}{$field}) {
19172:                                     push(@modifiable,$fieldtitles{$field});
19173:                                 }
19174:                             }
19175:                             if (@modifiable > 0) {
19176:                                 $resulttext .= join(', ',@modifiable);
19177:                             } else {
19178:                                 $resulttext .= &mt('none'); 
19179:                             }
19180:                             $resulttext .= '</li>';
19181:                         }
19182:                         $resulttext .= '</ul></li>';
19183:                     }
19184:                 }
19185:             }
19186:             $resulttext .= '</ul>';
19187:         } else {
19188:             $resulttext = &mt('No changes made to user modification settings');
19189:         }
19190:     } else {
19191:         $resulttext = '<span class="LC_error">'.
19192:             &mt('An error occurred: [_1]',$putresult).'</span>';
19193:     }
19194:     return $resulttext;
19195: }
19196: 
19197: sub modify_defaults {
19198:     my ($dom,$lastactref,%domconfig) = @_;
19199:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
19200:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19201:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
19202:                  'portal_def');
19203:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
19204:     foreach my $item (@items) {
19205:         $newvalues{$item} = $env{'form.'.$item};
19206:         if ($item eq 'auth_def') {
19207:             if ($newvalues{$item} ne '') {
19208:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
19209:                     push(@errors,$item);
19210:                 }
19211:             }
19212:         } elsif ($item eq 'lang_def') {
19213:             if ($newvalues{$item} ne '') {
19214:                 if ($newvalues{$item} =~ /^(\w+)/) {
19215:                     my $langcode = $1;
19216:                     if ($langcode ne 'x_chef') {
19217:                         if (code2language($langcode) eq '') {
19218:                             push(@errors,$item);
19219:                         }
19220:                     }
19221:                 } else {
19222:                     push(@errors,$item);
19223:                 }
19224:             }
19225:         } elsif ($item eq 'timezone_def') {
19226:             if ($newvalues{$item} ne '') {
19227:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
19228:                     push(@errors,$item);   
19229:                 }
19230:             }
19231:         } elsif ($item eq 'datelocale_def') {
19232:             if ($newvalues{$item} ne '') {
19233:                 my @datelocale_ids = DateTime::Locale->ids();
19234:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
19235:                     push(@errors,$item);
19236:                 }
19237:             }
19238:         } elsif ($item eq 'portal_def') {
19239:             if ($newvalues{$item} ne '') {
19240:                 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])\/?$/) {
19241:                     foreach my $field ('email','web') {
19242:                         if ($env{'form.'.$item.'_'.$field}) {
19243:                             $newvalues{$item.'_'.$field} = $env{'form.'.$item.'_'.$field};
19244:                         }
19245:                     }
19246:                 } else {
19247:                     push(@errors,$item);
19248:                 }
19249:             }
19250:         }
19251:         if (grep(/^\Q$item\E$/,@errors)) {
19252:             $newvalues{$item} = $domdefaults{$item};
19253:             if ($item eq 'portal_def') {
19254:                 if ($domdefaults{$item}) {
19255:                     foreach my $field ('email','web') {
19256:                         if (exists($domdefaults{$item.'_'.$field})) {
19257:                             $newvalues{$item.'_'.$field} = $domdefaults{$item.'_'.$field};
19258:                         }
19259:                     }
19260:                 }
19261:             }
19262:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
19263:             $changes{$item} = 1;
19264:         }
19265:         if ($item eq 'portal_def') {
19266:             unless (grep(/^\Q$item\E$/,@errors)) {
19267:                 if ($newvalues{$item} eq '') {
19268:                     foreach my $field ('email','web') {
19269:                         if (exists($domdefaults{$item.'_'.$field})) {
19270:                             delete($domdefaults{$item.'_'.$field});
19271:                         }
19272:                     }
19273:                 } else {
19274:                     unless ($changes{$item}) {
19275:                         foreach my $field ('email','web') {
19276:                             if ($domdefaults{$item.'_'.$field} ne $newvalues{$item.'_'.$field}) {
19277:                                 $changes{$item} = 1;
19278:                                 last;
19279:                             }
19280:                         }
19281:                     }
19282:                     foreach my $field ('email','web') {
19283:                         if ($newvalues{$item.'_'.$field}) {
19284:                             $domdefaults{$item.'_'.$field} = $newvalues{$item.'_'.$field};
19285:                         } elsif (exists($domdefaults{$item.'_'.$field})) {
19286:                             delete($domdefaults{$item.'_'.$field});
19287:                         }
19288:                     }
19289:                 }
19290:             }
19291:         }
19292:         $domdefaults{$item} = $newvalues{$item};
19293:     }
19294:     my %staticdefaults = (
19295:                            'intauth_cost'   => 10,
19296:                            'intauth_check'  => 0,
19297:                            'intauth_switch' => 0,
19298:                          );
19299:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
19300:         if (exists($domdefaults{$item})) {
19301:             $newvalues{$item} = $domdefaults{$item};
19302:         } else {
19303:             $newvalues{$item} = $staticdefaults{$item};
19304:         }
19305:     }
19306:     my ($unamemaprules,$ruleorder);
19307:     my @possunamemaprules = &Apache::loncommon::get_env_multiple('form.unamemap_rule');
19308:     if (@possunamemaprules) {
19309:         ($unamemaprules,$ruleorder) =
19310:             &Apache::lonnet::inst_userrules($dom,'unamemap');
19311:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
19312:             if (@{$ruleorder} > 0) {
19313:                 my %possrules;
19314:                 map { $possrules{$_} = 1; } @possunamemaprules;
19315:                 foreach my $rule (@{$ruleorder}) {
19316:                     if ($possrules{$rule}) {
19317:                         push(@{$newvalues{'unamemap_rule'}},$rule);
19318:                     }
19319:                 }
19320:             }
19321:         }
19322:     }
19323:     if (ref($domdefaults{'unamemap_rule'}) eq 'ARRAY') {
19324:         if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
19325:             my @rulediffs = &Apache::loncommon::compare_arrays($domdefaults{'unamemap_rule'},
19326:                                                                $newvalues{'unamemap_rule'});
19327:             if (@rulediffs) {
19328:                 $changes{'unamemap_rule'} = 1;
19329:                 $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
19330:             }
19331:         } elsif (@{$domdefaults{'unamemap_rule'}} > 0) {
19332:             $changes{'unamemap_rule'} = 1;
19333:             delete($domdefaults{'unamemap_rule'});
19334:         }
19335:     } elsif (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
19336:         if (@{$newvalues{'unamemap_rule'}} > 0) {
19337:             $changes{'unamemap_rule'} = 1;
19338:             $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
19339:         }
19340:     }
19341:     my %defaults_hash = (
19342:                          defaults => \%newvalues,
19343:                         );
19344:     my $title = &defaults_titles();
19345: 
19346:     my $currinststatus;
19347:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
19348:         $currinststatus = $domconfig{'inststatus'};
19349:     } else {
19350:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
19351:         $currinststatus = {
19352:                              inststatustypes => $usertypes,
19353:                              inststatusorder => $types,
19354:                              inststatusguest => [],
19355:                           };
19356:     }
19357:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
19358:     my @allpos;
19359:     my %alltypes;
19360:     my @inststatusguest;
19361:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
19362:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
19363:             unless (grep(/^\Q$type\E$/,@todelete)) {
19364:                 push(@inststatusguest,$type);
19365:             }
19366:         }
19367:     }
19368:     my ($currtitles,$currorder);
19369:     if (ref($currinststatus) eq 'HASH') {
19370:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
19371:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
19372:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
19373:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
19374:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
19375:                     }
19376:                 }
19377:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
19378:                     my $position = $env{'form.inststatus_pos_'.$type};
19379:                     $position =~ s/\D+//g;
19380:                     $allpos[$position] = $type;
19381:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
19382:                     $alltypes{$type} =~ s/`//g;
19383:                 }
19384:             }
19385:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
19386:             $currtitles =~ s/,$//;
19387:         }
19388:     }
19389:     if ($env{'form.addinststatus'}) {
19390:         my $newtype = $env{'form.addinststatus'};
19391:         $newtype =~ s/\W//g;
19392:         unless (exists($alltypes{$newtype})) {
19393:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
19394:             $alltypes{$newtype} =~ s/`//g; 
19395:             my $position = $env{'form.addinststatus_pos'};
19396:             $position =~ s/\D+//g;
19397:             if ($position ne '') {
19398:                 $allpos[$position] = $newtype;
19399:             }
19400:         }
19401:     }
19402:     my @orderedstatus;
19403:     foreach my $type (@allpos) {
19404:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
19405:             push(@orderedstatus,$type);
19406:         }
19407:     }
19408:     foreach my $type (keys(%alltypes)) {
19409:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
19410:             delete($alltypes{$type});
19411:         }
19412:     }
19413:     $defaults_hash{'inststatus'} = {
19414:                                      inststatustypes => \%alltypes,
19415:                                      inststatusorder => \@orderedstatus,
19416:                                      inststatusguest => \@inststatusguest,
19417:                                    };
19418:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
19419:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
19420:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
19421:         }
19422:     }
19423:     if ($currorder ne join(',',@orderedstatus)) {
19424:         $changes{'inststatus'}{'inststatusorder'} = 1;
19425:     }
19426:     my $newtitles;
19427:     foreach my $item (@orderedstatus) {
19428:         $newtitles .= $alltypes{$item}.',';
19429:     }
19430:     $newtitles =~ s/,$//;
19431:     if ($currtitles ne $newtitles) {
19432:         $changes{'inststatus'}{'inststatustypes'} = 1;
19433:     }
19434:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
19435:                                              $dom);
19436:     if ($putresult eq 'ok') {
19437:         if (keys(%changes) > 0) {
19438:             $resulttext = &mt('Changes made:').'<ul>';
19439:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
19440:             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";
19441:             foreach my $item (sort(keys(%changes))) {
19442:                 if ($item eq 'inststatus') {
19443:                     if (ref($changes{'inststatus'}) eq 'HASH') {
19444:                         if (@orderedstatus) {
19445:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
19446:                             foreach my $type (@orderedstatus) { 
19447:                                 $resulttext .= $alltypes{$type}.', ';
19448:                             }
19449:                             $resulttext =~ s/, $//;
19450:                             $resulttext .= '</li>';
19451:                         } else {
19452:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>';
19453:                         }
19454:                     }
19455:                 } elsif ($item eq 'unamemap_rule') {
19456:                     if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
19457:                         my @rulenames;
19458:                         if (ref($unamemaprules) eq 'HASH') {
19459:                             foreach my $rule (@{$newvalues{'unamemap_rule'}}) {
19460:                                 if (ref($unamemaprules->{$rule}) eq 'HASH') {
19461:                                     push(@rulenames,$unamemaprules->{$rule}->{'name'});
19462:                                 }
19463:                             }
19464:                         }
19465:                         if (@rulenames) {
19466:                             $resulttext .= '<li>'.&mt('Mapping for missing usernames includes: [_1]',
19467:                                                      '<ul><li>'.join('</li><li>',@rulenames).'</li></ul>').
19468:                                            '</li>';
19469:                         } else {
19470:                             $resulttext .= '<li>'.&mt('No mapping for missing usernames via standard log-in').'</li>';
19471:                         }
19472:                     } else {
19473:                         $resulttext .= '<li>'.&mt('Mapping for missing usernames via standard log-in deleted').'</li>';
19474:                     }
19475:                 } else {
19476:                     my $value = $env{'form.'.$item};
19477:                     if ($value eq '') {
19478:                         $value = &mt('none');
19479:                     } elsif ($item eq 'auth_def') {
19480:                         my %authnames = &authtype_names();
19481:                         my %shortauth = (
19482:                                           internal   => 'int',
19483:                                           krb4       => 'krb4',
19484:                                           krb5       => 'krb5',
19485:                                           localauth  => 'loc',
19486:                                           lti        => 'lti',
19487:                         );
19488:                         $value = $authnames{$shortauth{$value}};
19489:                     }
19490:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
19491:                     $mailmsgtext .= "$title->{$item} set to $value\n";
19492:                     if ($item eq 'portal_def') {
19493:                         if ($env{'form.'.$item} ne '') {
19494:                             foreach my $field ('email','web') {
19495:                                 $value = $env{'form.'.$item.'_'.$field};
19496:                                 if ($value) {
19497:                                     $value = &mt('Yes');
19498:                                 } else {
19499:                                     $value = &mt('No');
19500:                                 }
19501:                                 $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$field},$value).'</li>';
19502:                             }
19503:                         }
19504:                     }
19505:                 }
19506:             }
19507:             $resulttext .= '</ul>';
19508:             $mailmsgtext .= "\n";
19509:             my $cachetime = 24*60*60;
19510:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19511:             if (ref($lastactref) eq 'HASH') {
19512:                 $lastactref->{'domdefaults'} = 1;
19513:             }
19514:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
19515:                 my $notify = 1;
19516:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
19517:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
19518:                         $notify = 0;
19519:                     }
19520:                 }
19521:                 if ($notify) {
19522:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
19523:                                                "LON-CAPA Domain Settings Change - $dom",
19524:                                                $mailmsgtext);
19525:                 }
19526:             }
19527:         } else {
19528:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
19529:         }
19530:     } else {
19531:         $resulttext = '<span class="LC_error">'.
19532:             &mt('An error occurred: [_1]',$putresult).'</span>';
19533:     }
19534:     if (@errors > 0) {
19535:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
19536:         foreach my $item (@errors) {
19537:             $resulttext .= ' "'.$title->{$item}.'",';
19538:         }
19539:         $resulttext =~ s/,$//;
19540:     }
19541:     return $resulttext;
19542: }
19543: 
19544: sub modify_scantron {
19545:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
19546:     my ($resulttext,%confhash,%changes,$errors);
19547:     my $custom = 'custom.tab';
19548:     my $default = 'default.tab';
19549:     my $servadm = $r->dir_config('lonAdmEMail');
19550:     my ($configuserok,$author_ok,$switchserver) =
19551:         &config_check($dom,$confname,$servadm);
19552:     if ($env{'form.scantronformat.filename'} ne '') {
19553:         my $error;
19554:         if ($configuserok eq 'ok') {
19555:             if ($switchserver) {
19556:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
19557:             } else {
19558:                 if ($author_ok eq 'ok') {
19559:                     my $modified = [];
19560:                     my ($result,$scantronurl) =
19561:                         &Apache::lonconfigsettings::publishlogo($r,'upload','scantronformat',$dom,
19562:                                                                 $confname,'scantron','','',$custom,
19563:                                                                 $modified);
19564:                     if ($result eq 'ok') {
19565:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
19566:                         $changes{'scantronformat'} = 1;
19567:                         &update_modify_urls($r,$modified);
19568:                     } else {
19569:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
19570:                     }
19571:                 } else {
19572:                     $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);
19573:                 }
19574:             }
19575:         } else {
19576:             $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);
19577:         }
19578:         if ($error) {
19579:             &Apache::lonnet::logthis($error);
19580:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
19581:         }
19582:     }
19583:     if (ref($domconfig{'scantron'}) eq 'HASH') {
19584:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
19585:             if ($env{'form.scantronformat_del'}) {
19586:                 $confhash{'scantron'}{'scantronformat'} = '';
19587:                 $changes{'scantronformat'} = 1;
19588:             } else {
19589:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
19590:             }
19591:         }
19592:     }
19593:     my @options = ('hdr','pad','rem');
19594:     my @fields = &scantroncsv_fields();
19595:     my %titles = &scantronconfig_titles();
19596:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
19597:     my ($newdat,$currdat,%newcol,%currcol);
19598:     if (grep(/^dat$/,@formats)) {
19599:         $confhash{'scantron'}{config}{dat} = 1;
19600:         $newdat = 1;
19601:     } else {
19602:         $newdat = 0;
19603:     }
19604:     if (grep(/^csv$/,@formats)) {
19605:         my %bynum;
19606:         foreach my $field (@fields) {
19607:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
19608:                 my $posscol = $1;
19609:                 if (($posscol < 20) && (!$bynum{$posscol})) {
19610:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
19611:                     $bynum{$posscol} = $field;
19612:                     $newcol{$field} = $posscol;
19613:                 }
19614:             }
19615:         }
19616:         if (keys(%newcol)) {
19617:             foreach my $option (@options) {
19618:                 if ($env{'form.scantroncsv_'.$option}) {
19619:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
19620:                 }
19621:             }
19622:         }
19623:     }
19624:     $currdat = 1;
19625:     if (ref($domconfig{'scantron'}) eq 'HASH') {
19626:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
19627:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
19628:                 $currdat = 0;
19629:             }
19630:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
19631:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
19632:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
19633:                 }
19634:             }
19635:         }
19636:     }
19637:     if ($currdat != $newdat) {
19638:         $changes{'config'} = 1;
19639:     } else {
19640:         foreach my $field (@fields) {
19641:             if ($currcol{$field} ne '') {
19642:                 if ($currcol{$field} ne $newcol{$field}) {
19643:                     $changes{'config'} = 1;
19644:                     last;
19645:                 }
19646:             } elsif ($newcol{$field} ne '') {
19647:                 $changes{'config'} = 1;
19648:                 last;
19649:             }
19650:         }
19651:     }
19652:     if (keys(%confhash) > 0) {
19653:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
19654:                                                  $dom);
19655:         if ($putresult eq 'ok') {
19656:             if (keys(%changes) > 0) {
19657:                 if (ref($confhash{'scantron'}) eq 'HASH') {
19658:                     $resulttext = &mt('Changes made:').'<ul>';
19659:                     if ($changes{'scantronformat'}) {
19660:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
19661:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
19662:                         } else {
19663:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
19664:                         }
19665:                     }
19666:                     if ($changes{'config'}) {
19667:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
19668:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
19669:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
19670:                             }
19671:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
19672:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
19673:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
19674:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
19675:                                         foreach my $field (@fields) {
19676:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
19677:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
19678:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
19679:                                             }
19680:                                         }
19681:                                         $resulttext .= '</ul></li>';
19682:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
19683:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
19684:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
19685:                                                 foreach my $option (@options) {
19686:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
19687:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
19688:                                                     }
19689:                                                 }
19690:                                                 $resulttext .= '</ul></li>';
19691:                                             }
19692:                                         }
19693:                                     }
19694:                                 }
19695:                             }
19696:                         } else {
19697:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
19698:                         }
19699:                     }
19700:                     $resulttext .= '</ul>';
19701:                 } else {
19702:                     $resulttext = &mt('Changes made to bubblesheet format file.');
19703:                 }
19704:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
19705:                 if (ref($lastactref) eq 'HASH') {
19706:                     $lastactref->{'domainconfig'} = 1;
19707:                 }
19708:             } else {
19709:                 $resulttext = &mt('No changes made to bubblesheet format settings');
19710:             }
19711:         } else {
19712:             $resulttext = '<span class="LC_error">'.
19713:                 &mt('An error occurred: [_1]',$putresult).'</span>';
19714:         }
19715:     } else {
19716:         $resulttext = &mt('No changes made to bubblesheet format file'); 
19717:     }
19718:     if ($errors) {
19719:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
19720:                        $errors.'</ul></p>';
19721:     }
19722:     return $resulttext;
19723: }
19724: 
19725: sub modify_coursecategories {
19726:     my ($dom,$lastactref,%domconfig) = @_;
19727:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
19728:         $cathash);
19729:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
19730:     my @catitems = ('unauth','auth');
19731:     my @cattypes = ('std','domonly','codesrch','none');
19732:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
19733:         $cathash = $domconfig{'coursecategories'}{'cats'};
19734:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
19735:             $changes{'togglecats'} = 1;
19736:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
19737:         }
19738:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
19739:             $changes{'categorize'} = 1;
19740:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
19741:         }
19742:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
19743:             $changes{'togglecatscomm'} = 1;
19744:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
19745:         }
19746:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
19747:             $changes{'categorizecomm'} = 1;
19748:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
19749: 
19750:         }
19751:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
19752:             $changes{'togglecatsplace'} = 1;
19753:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
19754:         }
19755:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
19756:             $changes{'categorizeplace'} = 1;
19757:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
19758:         }
19759:         foreach my $item (@catitems) {
19760:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
19761:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
19762:                     $changes{$item} = 1;
19763:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
19764:                 }
19765:             }
19766:         }
19767:     } else {
19768:         $changes{'togglecats'} = 1;
19769:         $changes{'categorize'} = 1;
19770:         $changes{'togglecatscomm'} = 1;
19771:         $changes{'categorizecomm'} = 1;
19772:         $changes{'togglecatsplace'} = 1;
19773:         $changes{'categorizeplace'} = 1;
19774:         $domconfig{'coursecategories'} = {
19775:                                              togglecats => $env{'form.togglecats'},
19776:                                              categorize => $env{'form.categorize'},
19777:                                              togglecatscomm => $env{'form.togglecatscomm'},
19778:                                              categorizecomm => $env{'form.categorizecomm'},
19779:                                              togglecatsplace => $env{'form.togglecatsplace'},
19780:                                              categorizeplace => $env{'form.categorizeplace'},
19781:                                          };
19782:         foreach my $item (@catitems) {
19783:             if ($env{'form.coursecat_'.$item} ne 'std') {
19784:                 $changes{$item} = 1;
19785:             }
19786:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
19787:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
19788:             }
19789:         }
19790:     }
19791:     if (ref($cathash) eq 'HASH') {
19792:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
19793:             push (@deletecategory,'instcode::0');
19794:         }
19795:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
19796:             push(@deletecategory,'communities::0');
19797:         }
19798:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
19799:             push(@deletecategory,'placement::0');
19800:         }
19801:     }
19802:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
19803:     if (ref($cathash) eq 'HASH') {
19804:         if (@deletecategory > 0) {
19805:             #FIXME Need to remove category from all courses using a deleted category 
19806:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
19807:             foreach my $item (@deletecategory) {
19808:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
19809:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
19810:                     $deletions{$item} = 1;
19811:                     &recurse_cat_deletes($item,$cathash,\%deletions);
19812:                 }
19813:             }
19814:         }
19815:         foreach my $item (keys(%{$cathash})) {
19816:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
19817:             if ($cathash->{$item} ne $env{'form.'.$item}) {
19818:                 $reorderings{$item} = 1;
19819:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
19820:             }
19821:             if ($env{'form.addcategory_name_'.$item} ne '') {
19822:                 my $newcat = $env{'form.addcategory_name_'.$item};
19823:                 my $newdepth = $depth+1;
19824:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
19825:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
19826:                 $adds{$newitem} = 1; 
19827:             }
19828:             if ($env{'form.subcat_'.$item} ne '') {
19829:                 my $newcat = $env{'form.subcat_'.$item};
19830:                 my $newdepth = $depth+1;
19831:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
19832:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
19833:                 $adds{$newitem} = 1;
19834:             }
19835:         }
19836:     }
19837:     if ($env{'form.instcode'} eq '1') {
19838:         if (ref($cathash) eq 'HASH') {
19839:             my $newitem = 'instcode::0';
19840:             if ($cathash->{$newitem} eq '') {  
19841:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
19842:                 $adds{$newitem} = 1;
19843:             }
19844:         } else {
19845:             my $newitem = 'instcode::0';
19846:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
19847:             $adds{$newitem} = 1;
19848:         }
19849:     }
19850:     if ($env{'form.communities'} eq '1') {
19851:         if (ref($cathash) eq 'HASH') {
19852:             my $newitem = 'communities::0';
19853:             if ($cathash->{$newitem} eq '') {
19854:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
19855:                 $adds{$newitem} = 1;
19856:             }
19857:         } else {
19858:             my $newitem = 'communities::0';
19859:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
19860:             $adds{$newitem} = 1;
19861:         }
19862:     }
19863:     if ($env{'form.placement'} eq '1') {
19864:         if (ref($cathash) eq 'HASH') {
19865:             my $newitem = 'placement::0';
19866:             if ($cathash->{$newitem} eq '') {
19867:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
19868:                 $adds{$newitem} = 1;
19869:             }
19870:         } else {
19871:             my $newitem = 'placement::0';
19872:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
19873:             $adds{$newitem} = 1;
19874:         }
19875:     }
19876:     if ($env{'form.addcategory_name'} ne '') {
19877:         if (($env{'form.addcategory_name'} ne 'instcode') &&
19878:             ($env{'form.addcategory_name'} ne 'communities') &&
19879:             ($env{'form.addcategory_name'} ne 'placement')) {
19880:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
19881:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
19882:             $adds{$newitem} = 1;
19883:         }
19884:     }
19885:     my $putresult;
19886:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19887:         if (keys(%deletions) > 0) {
19888:             foreach my $key (keys(%deletions)) {
19889:                 if ($predelallitems{$key} ne '') {
19890:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
19891:                 }
19892:             }
19893:         }
19894:         my (@chkcats,@chktrails,%chkallitems);
19895:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
19896:         if (ref($chkcats[0]) eq 'ARRAY') {
19897:             my $depth = 0;
19898:             my $chg = 0;
19899:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
19900:                 my $name = $chkcats[0][$i];
19901:                 my $item;
19902:                 if ($name eq '') {
19903:                     $chg ++;
19904:                 } else {
19905:                     $item = &escape($name).'::0';
19906:                     if ($chg) {
19907:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
19908:                     }
19909:                     $depth ++; 
19910:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
19911:                     $depth --;
19912:                 }
19913:             }
19914:         }
19915:     }
19916:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19917:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
19918:         if ($putresult eq 'ok') {
19919:             my %title = (
19920:                          togglecats     => 'Show/Hide a course in catalog',
19921:                          categorize     => 'Assign a category to a course',
19922:                          togglecatscomm => 'Show/Hide a community in catalog',
19923:                          categorizecomm => 'Assign a category to a community',
19924:                         );
19925:             my %level = (
19926:                          dom  => 'set in Domain ("Modify Course/Community")',
19927:                          crs  => 'set in Course ("Course Configuration")',
19928:                          comm => 'set in Community ("Community Configuration")',
19929:                          none     => 'No catalog',
19930:                          std      => 'Standard catalog',
19931:                          domonly  => 'Domain-only catalog',
19932:                          codesrch => 'Code search form',
19933:                         );
19934:             $resulttext = &mt('Changes made:').'<ul>';
19935:             if ($changes{'togglecats'}) {
19936:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
19937:             }
19938:             if ($changes{'categorize'}) {
19939:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
19940:             }
19941:             if ($changes{'togglecatscomm'}) {
19942:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
19943:             }
19944:             if ($changes{'categorizecomm'}) {
19945:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
19946:             }
19947:             if ($changes{'unauth'}) {
19948:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
19949:             }
19950:             if ($changes{'auth'}) {
19951:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
19952:             }
19953:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19954:                 my $cathash;
19955:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
19956:                     $cathash = $domconfig{'coursecategories'}{'cats'};
19957:                 } else {
19958:                     $cathash = {};
19959:                 } 
19960:                 my (@cats,@trails,%allitems);
19961:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
19962:                 if (keys(%deletions) > 0) {
19963:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
19964:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
19965:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
19966:                     }
19967:                     $resulttext .= '</ul></li>';
19968:                 }
19969:                 if (keys(%reorderings) > 0) {
19970:                     my %sort_by_trail;
19971:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
19972:                     foreach my $key (keys(%reorderings)) {
19973:                         if ($allitems{$key} ne '') {
19974:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
19975:                         }
19976:                     }
19977:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
19978:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
19979:                     }
19980:                     $resulttext .= '</ul></li>';
19981:                 }
19982:                 if (keys(%adds) > 0) {
19983:                     my %sort_by_trail;
19984:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
19985:                     foreach my $key (keys(%adds)) {
19986:                         if ($allitems{$key} ne '') {
19987:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
19988:                         }
19989:                     }
19990:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
19991:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
19992:                     }
19993:                     $resulttext .= '</ul></li>';
19994:                 }
19995:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
19996:                 if (ref($lastactref) eq 'HASH') {
19997:                     $lastactref->{'cats'} = 1;
19998:                 }
19999:             }
20000:             $resulttext .= '</ul>';
20001:             if ($changes{'unauth'} || $changes{'auth'}) {
20002:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
20003:                 if ($changes{'auth'}) {
20004:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
20005:                 }
20006:                 if ($changes{'unauth'}) {
20007:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
20008:                 }
20009:                 my $cachetime = 24*60*60;
20010:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20011:                 if (ref($lastactref) eq 'HASH') {
20012:                     $lastactref->{'domdefaults'} = 1;
20013:                 }
20014:             }
20015:         } else {
20016:             $resulttext = '<span class="LC_error">'.
20017:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20018:         }
20019:     } else {
20020:         $resulttext = &mt('No changes made to course and community categories');
20021:     }
20022:     return $resulttext;
20023: }
20024: 
20025: sub modify_serverstatuses {
20026:     my ($dom,%domconfig) = @_;
20027:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
20028:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
20029:         %currserverstatus = %{$domconfig{'serverstatuses'}};
20030:     }
20031:     my @pages = &serverstatus_pages();
20032:     foreach my $type (@pages) {
20033:         $newserverstatus{$type}{'namedusers'} = '';
20034:         $newserverstatus{$type}{'machines'} = '';
20035:         if (defined($env{'form.'.$type.'_namedusers'})) {
20036:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
20037:             my @okusers;
20038:             foreach my $user (@users) {
20039:                 my ($uname,$udom) = split(/:/,$user);
20040:                 if (($udom =~ /^$match_domain$/) &&   
20041:                     (&Apache::lonnet::domain($udom)) &&
20042:                     ($uname =~ /^$match_username$/)) {
20043:                     if (!grep(/^\Q$user\E/,@okusers)) {
20044:                         push(@okusers,$user);
20045:                     }
20046:                 }
20047:             }
20048:             if (@okusers > 0) {
20049:                  @okusers = sort(@okusers);
20050:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
20051:             }
20052:         }
20053:         if (defined($env{'form.'.$type.'_machines'})) {
20054:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
20055:             my @okmachines;
20056:             foreach my $ip (@machines) {
20057:                 my @parts = split(/\./,$ip);
20058:                 next if (@parts < 4);
20059:                 my $badip = 0;
20060:                 for (my $i=0; $i<4; $i++) {
20061:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
20062:                         $badip = 1;
20063:                         last;
20064:                     }
20065:                 }
20066:                 if (!$badip) {
20067:                     push(@okmachines,$ip);     
20068:                 }
20069:             }
20070:             @okmachines = sort(@okmachines);
20071:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
20072:         }
20073:     }
20074:     my %serverstatushash =  (
20075:                                 serverstatuses => \%newserverstatus,
20076:                             );
20077:     foreach my $type (@pages) {
20078:         foreach my $setting ('namedusers','machines') {
20079:             my (@current,@new);
20080:             if (ref($currserverstatus{$type}) eq 'HASH') {
20081:                 if ($currserverstatus{$type}{$setting} ne '') { 
20082:                     @current = split(/,/,$currserverstatus{$type}{$setting});
20083:                 }
20084:             }
20085:             if ($newserverstatus{$type}{$setting} ne '') {
20086:                 @new = split(/,/,$newserverstatus{$type}{$setting});
20087:             }
20088:             if (@current > 0) {
20089:                 if (@new > 0) {
20090:                     foreach my $item (@current) {
20091:                         if (!grep(/^\Q$item\E$/,@new)) {
20092:                             $changes{$type}{$setting} = 1;
20093:                             last;
20094:                         }
20095:                     }
20096:                     foreach my $item (@new) {
20097:                         if (!grep(/^\Q$item\E$/,@current)) {
20098:                             $changes{$type}{$setting} = 1;
20099:                             last;
20100:                         }
20101:                     }
20102:                 } else {
20103:                     $changes{$type}{$setting} = 1;
20104:                 }
20105:             } elsif (@new > 0) {
20106:                 $changes{$type}{$setting} = 1;
20107:             }
20108:         }
20109:     }
20110:     if (keys(%changes) > 0) {
20111:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
20112:         my $putresult = &Apache::lonnet::put_dom('configuration',
20113:                                                  \%serverstatushash,$dom);
20114:         if ($putresult eq 'ok') {
20115:             $resulttext .= &mt('Changes made:').'<ul>';
20116:             foreach my $type (@pages) {
20117:                 if (ref($changes{$type}) eq 'HASH') {
20118:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
20119:                     if ($changes{$type}{'namedusers'}) {
20120:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
20121:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
20122:                         } else {
20123:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
20124:                         }
20125:                     }
20126:                     if ($changes{$type}{'machines'}) {
20127:                         if ($newserverstatus{$type}{'machines'} eq '') {
20128:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
20129:                         } else {
20130:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
20131:                         }
20132: 
20133:                     }
20134:                     $resulttext .= '</ul></li>';
20135:                 }
20136:             }
20137:             $resulttext .= '</ul>';
20138:         } else {
20139:             $resulttext = '<span class="LC_error">'.
20140:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
20141: 
20142:         }
20143:     } else {
20144:         $resulttext = &mt('No changes made to access to server status pages');
20145:     }
20146:     return $resulttext;
20147: }
20148: 
20149: sub modify_helpsettings {
20150:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20151:     my ($resulttext,$errors,%changes,%helphash);
20152:     my %defaultchecked = ('submitbugs' => 'on');
20153:     my @offon = ('off','on');
20154:     my @toggles = ('submitbugs');
20155:     my %current = ('submitbugs' => '',
20156:                    'adhoc'      => {},
20157:                   );
20158:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
20159:         %current = %{$domconfig{'helpsettings'}};
20160:     }
20161:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20162:     foreach my $item (@toggles) {
20163:         if ($defaultchecked{$item} eq 'on') { 
20164:             if ($current{$item} eq '') {
20165:                 if ($env{'form.'.$item} eq '0') {
20166:                     $changes{$item} = 1;
20167:                 }
20168:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20169:                 $changes{$item} = 1;
20170:             }
20171:         } elsif ($defaultchecked{$item} eq 'off') {
20172:             if ($current{$item} eq '') {
20173:                 if ($env{'form.'.$item} eq '1') {
20174:                     $changes{$item} = 1;
20175:                 }
20176:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20177:                 $changes{$item} = 1;
20178:             }
20179:         }
20180:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
20181:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
20182:         }
20183:     }
20184:     my $maxnum = $env{'form.helproles_maxnum'};
20185:     my $confname = $dom.'-domainconfig';
20186:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
20187:     my (@allpos,%newsettings,%changedprivs,$newrole);
20188:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
20189:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
20190:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
20191:     my %lt = &Apache::lonlocal::texthash(
20192:                     s      => 'system',
20193:                     d      => 'domain',
20194:                     order  => 'Display order',
20195:                     access => 'Role usage',
20196:                     all    => 'All with domain helpdesk or helpdesk assistant role',
20197:                     dh     => 'All with domain helpdesk role',
20198:                     da     => 'All with domain helpdesk assistant role',
20199:                     none   => 'None',
20200:                     status => 'Determined based on institutional status',
20201:                     inc    => 'Include all, but exclude specific personnel',
20202:                     exc    => 'Exclude all, but include specific personnel',
20203:     );
20204:     for (my $num=0; $num<=$maxnum; $num++) {
20205:         my ($prefix,$identifier,$rolename,%curr);
20206:         if ($num == $maxnum) {
20207:             next unless ($env{'form.newcusthelp'} == $maxnum);
20208:             $identifier = 'custhelp'.$num;
20209:             $prefix = 'helproles_'.$num;
20210:             $rolename = $env{'form.custhelpname'.$num};
20211:             $rolename=~s/[^A-Za-z0-9]//gs;
20212:             next if ($rolename eq '');
20213:             next if (exists($existing{'rolesdef_'.$rolename}));
20214:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20215:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20216:                                                      $newprivs{'c'},$confname,$dom);
20217:             if ($result ne 'ok') {
20218:                 $errors .= '<li><span class="LC_error">'.
20219:                            &mt('An error occurred storing the new custom role: [_1]',
20220:                            $result).'</span></li>';
20221:                 next;
20222:             } else {
20223:                 $changedprivs{$rolename} = \%newprivs;
20224:                 $newrole = $rolename;
20225:             }
20226:         } else {
20227:             $prefix = 'helproles_'.$num;
20228:             $rolename = $env{'form.'.$prefix};
20229:             next if ($rolename eq '');
20230:             next unless (exists($existing{'rolesdef_'.$rolename}));
20231:             $identifier = 'custhelp'.$num;
20232:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20233:             my %currprivs;
20234:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
20235:                 split(/\_/,$existing{'rolesdef_'.$rolename});
20236:             foreach my $level ('c','d','s') {
20237:                 if ($newprivs{$level} ne $currprivs{$level}) {
20238:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20239:                                                              $newprivs{'c'},$confname,$dom);
20240:                     if ($result ne 'ok') {
20241:                         $errors .= '<li><span class="LC_error">'.
20242:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
20243:                                        $rolename,$result).'</span></li>';
20244:                     } else {
20245:                         $changedprivs{$rolename} = \%newprivs;
20246:                     }
20247:                     last;
20248:                 }
20249:             }
20250:             if (ref($current{'adhoc'}) eq 'HASH') {
20251:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
20252:                     %curr = %{$current{'adhoc'}{$rolename}};
20253:                 }
20254:             }
20255:         }
20256:         my $newpos = $env{'form.'.$prefix.'_pos'};
20257:         $newpos =~ s/\D+//g;
20258:         $allpos[$newpos] = $rolename;
20259:         my $newdesc = $env{'form.'.$prefix.'_desc'};
20260:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
20261:         if ($curr{'desc'}) {
20262:             if ($curr{'desc'} ne $newdesc) {
20263:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
20264:                 $newsettings{$rolename}{'desc'} = $newdesc;
20265:             }
20266:         } elsif ($newdesc ne '') {
20267:             $changes{'customrole'}{$rolename}{'desc'} = 1;
20268:             $newsettings{$rolename}{'desc'} = $newdesc;
20269:         }
20270:         my $access = $env{'form.'.$prefix.'_access'};
20271:         if (grep(/^\Q$access\E$/,@accesstypes)) {
20272:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
20273:             if ($access eq 'status') {
20274:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
20275:                 if (scalar(@statuses) == 0) {
20276:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
20277:                 } else {
20278:                     my (@shownstatus,$numtypes);
20279:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20280:                     if (ref($types) eq 'ARRAY') {
20281:                         $numtypes = scalar(@{$types});
20282:                         foreach my $type (sort(@statuses)) {
20283:                             if ($type eq 'default') {
20284:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20285:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
20286:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20287:                                 push(@shownstatus,$usertypes->{$type});
20288:                             }
20289:                         }
20290:                     }
20291:                     if (grep(/^default$/,@statuses)) {
20292:                         push(@shownstatus,$othertitle);
20293:                     }
20294:                     if (scalar(@shownstatus) == 1+$numtypes) {
20295:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
20296:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
20297:                     } else {
20298:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
20299:                         if (ref($curr{'status'}) eq 'ARRAY') {
20300:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20301:                             if (@diffs) {
20302:                                 $changes{'customrole'}{$rolename}{$access} = 1;
20303:                             }
20304:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20305:                             $changes{'customrole'}{$rolename}{$access} = 1;
20306:                         }
20307:                     }
20308:                 }
20309:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
20310:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
20311:                 my @newspecstaff;
20312:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20313:                 foreach my $person (sort(@personnel)) {
20314:                     if ($domhelpdesk{$person}) {
20315:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
20316:                     }
20317:                 }
20318:                 if (ref($curr{$access}) eq 'ARRAY') {
20319:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20320:                     if (@diffs) {
20321:                         $changes{'customrole'}{$rolename}{$access} = 1;
20322:                     }
20323:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20324:                     $changes{'customrole'}{$rolename}{$access} = 1;
20325:                 }
20326:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20327:                     my ($uname,$udom) = split(/:/,$person);
20328:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
20329:                 }
20330:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
20331:             }
20332:         } else {
20333:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
20334:         }
20335:         unless ($curr{'access'} eq $access) {
20336:             $changes{'customrole'}{$rolename}{'access'} = 1;
20337:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
20338:         }
20339:     }
20340:     if (@allpos > 0) {
20341:         my $idx = 0;
20342:         foreach my $rolename (@allpos) {
20343:             if ($rolename ne '') {
20344:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
20345:                 if (ref($current{'adhoc'}) eq 'HASH') {
20346:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
20347:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
20348:                             $changes{'customrole'}{$rolename}{'order'} = 1;
20349:                             $newsettings{$rolename}{'order'} = $idx+1;
20350:                         }
20351:                     }
20352:                 }
20353:                 $idx ++;
20354:             }
20355:         }
20356:     }
20357:     my $putresult;
20358:     if (keys(%changes) > 0) {
20359:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
20360:         if ($putresult eq 'ok') {
20361:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
20362:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
20363:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
20364:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
20365:                 }
20366:             }
20367:             my $cachetime = 24*60*60;
20368:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20369:             if (ref($lastactref) eq 'HASH') {
20370:                 $lastactref->{'domdefaults'} = 1;
20371:             }
20372:         } else {
20373:             $errors .= '<li><span class="LC_error">'.
20374:                        &mt('An error occurred storing the settings: [_1]',
20375:                            $putresult).'</span></li>';
20376:         }
20377:     }
20378:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
20379:         $resulttext = &mt('Changes made:').'<ul>';
20380:         my (%shownprivs,@levelorder);
20381:         @levelorder = ('c','d','s');
20382:         if ((keys(%changes)) && ($putresult eq 'ok')) {
20383:             foreach my $item (sort(keys(%changes))) {
20384:                 if ($item eq 'submitbugs') {
20385:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
20386:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
20387:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
20388:                 } elsif ($item eq 'customrole') {
20389:                     if (ref($changes{'customrole'}) eq 'HASH') {
20390:                         my @keyorder = ('order','desc','access','status','exc','inc');
20391:                         my %keytext = &Apache::lonlocal::texthash(
20392:                                                                    order  => 'Order',
20393:                                                                    desc   => 'Role description',
20394:                                                                    access => 'Role usage',
20395:                                                                    status => 'Allowed institutional types',
20396:                                                                    exc    => 'Allowed personnel',
20397:                                                                    inc    => 'Disallowed personnel',
20398:                         );
20399:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
20400:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
20401:                                 if ($role eq $newrole) {
20402:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
20403:                                                               $role).'<ul>';
20404:                                 } else {
20405:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
20406:                                                               $role).'<ul>';
20407:                                 }
20408:                                 foreach my $key (@keyorder) {
20409:                                     if ($changes{'customrole'}{$role}{$key}) {
20410:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
20411:                                                                   $keytext{$key},$newsettings{$role}{$key}).
20412:                                                        '</li>';
20413:                                     }
20414:                                 }
20415:                                 if (ref($changedprivs{$role}) eq 'HASH') {
20416:                                     $shownprivs{$role} = 1;
20417:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
20418:                                     foreach my $level (@levelorder) {
20419:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
20420:                                             next if ($item eq '');
20421:                                             my ($priv) = split(/\&/,$item,2);
20422:                                             if (&Apache::lonnet::plaintext($priv)) {
20423:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
20424:                                                 unless ($level eq 'c') {
20425:                                                     $resulttext .= ' ('.$lt{$level}.')';
20426:                                                 }
20427:                                                 $resulttext .= '</li>';
20428:                                             }
20429:                                         }
20430:                                     }
20431:                                     $resulttext .= '</ul>';
20432:                                 }
20433:                                 $resulttext .= '</ul></li>';
20434:                             }
20435:                         }
20436:                     }
20437:                 }
20438:             }
20439:         }
20440:         if (keys(%changedprivs)) {
20441:             foreach my $role (sort(keys(%changedprivs))) {
20442:                 unless ($shownprivs{$role}) {
20443:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
20444:                                               $role).'<ul>'.
20445:                                    '<li>'.&mt('Privileges set to :').'<ul>';
20446:                     foreach my $level (@levelorder) {
20447:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
20448:                             next if ($item eq '');
20449:                             my ($priv) = split(/\&/,$item,2);
20450:                             if (&Apache::lonnet::plaintext($priv)) {
20451:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
20452:                                 unless ($level eq 'c') {
20453:                                     $resulttext .= ' ('.$lt{$level}.')';
20454:                                 }
20455:                                 $resulttext .= '</li>';
20456:                             }
20457:                         }
20458:                     }
20459:                     $resulttext .= '</ul></li></ul></li>';
20460:                 }
20461:             }
20462:         }
20463:         $resulttext .= '</ul>';
20464:     } else {
20465:         $resulttext = &mt('No changes made to help settings');
20466:     }
20467:     if ($errors) {
20468:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
20469:                                     $errors.'</ul>';
20470:     }
20471:     return $resulttext;
20472: }
20473: 
20474: sub modify_coursedefaults {
20475:     my ($dom,$lastactref,%domconfig) = @_;
20476:     my ($resulttext,$errors,%changes,%defaultshash);
20477:     my %defaultchecked = (
20478:                            'canuse_pdfforms' => 'off',
20479:                            'uselcmath'       => 'on',
20480:                            'usejsme'         => 'on',
20481:                            'inline_chem'     => 'on',
20482:                            'ltiauth'         => 'off',
20483:                          );
20484:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem','ltiauth');
20485:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
20486:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
20487:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
20488:                    'mysqltables_textbook','mysqltables_placement');
20489:     my @types = ('official','unofficial','community','textbook','placement');
20490:     my %staticdefaults = (
20491:                            anonsurvey_threshold => 10,
20492:                            uploadquota          => 500,
20493:                            postsubmit           => 60,
20494:                            mysqltables          => 172800,
20495:                            domexttool           => 1,
20496:                          );
20497:     my %texoptions = (
20498:                         MathJax  => 'MathJax',
20499:                         mimetex  => &mt('Convert to Images'),
20500:                         tth      => &mt('TeX to HTML'),
20501:                      );
20502:     $defaultshash{'coursedefaults'} = {};
20503: 
20504:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
20505:         if ($domconfig{'coursedefaults'} eq '') {
20506:             $domconfig{'coursedefaults'} = {};
20507:         }
20508:     }
20509: 
20510:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
20511:         foreach my $item (@toggles) {
20512:             if ($defaultchecked{$item} eq 'on') {
20513:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
20514:                     ($env{'form.'.$item} eq '0')) {
20515:                     $changes{$item} = 1;
20516:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
20517:                     $changes{$item} = 1;
20518:                 }
20519:             } elsif ($defaultchecked{$item} eq 'off') {
20520:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
20521:                     ($env{'form.'.$item} eq '1')) {
20522:                     $changes{$item} = 1;
20523:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
20524:                     $changes{$item} = 1;
20525:                 }
20526:             }
20527:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
20528:         }
20529:         foreach my $item (@numbers) {
20530:             my ($currdef,$newdef);
20531:             $newdef = $env{'form.'.$item};
20532:             if ($item eq 'anonsurvey_threshold') {
20533:                 $currdef = $domconfig{'coursedefaults'}{$item};
20534:                 $newdef =~ s/\D//g;
20535:                 if ($newdef eq '' || $newdef < 1) {
20536:                     $newdef = 1;
20537:                 }
20538:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
20539:             } else {
20540:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
20541:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
20542:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
20543:                 }
20544:                 $newdef =~ s/[^\w.\-]//g;
20545:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
20546:             }
20547:             if ($currdef ne $newdef) {
20548:                 if ($item eq 'anonsurvey_threshold') {
20549:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
20550:                         $changes{$item} = 1;
20551:                     }
20552:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
20553:                     my $setting = $1;
20554:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
20555:                         $changes{$setting} = 1;
20556:                     }
20557:                 }
20558:             }
20559:         }
20560:         my $texengine;
20561:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
20562:             $texengine = $env{'form.texengine'};
20563:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
20564:             if ($currdef eq '') {
20565:                 unless ($texengine eq $Apache::lonnet::deftex) {
20566:                     $changes{'texengine'} = 1;
20567:                 }
20568:             } elsif ($currdef ne $texengine) {
20569:                 $changes{'texengine'} = 1;
20570:             }
20571:         }
20572:         if ($texengine ne '') {
20573:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
20574:         }
20575:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
20576:         my @currclonecode;
20577:         if (ref($currclone) eq 'HASH') {
20578:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
20579:                 @currclonecode = @{$currclone->{'instcode'}};
20580:             }
20581:         }
20582:         my $newclone;
20583:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
20584:             $newclone = $env{'form.canclone'};
20585:         }
20586:         if ($newclone eq 'instcode') {
20587:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
20588:             my (%codedefaults,@code_order,@clonecode);
20589:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
20590:                                                     \@code_order);
20591:             foreach my $item (@code_order) {
20592:                 if (grep(/^\Q$item\E$/,@newcodes)) {
20593:                     push(@clonecode,$item);
20594:                 }
20595:             }
20596:             if (@clonecode) {
20597:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
20598:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
20599:                 if (@diffs) {
20600:                     $changes{'canclone'} = 1;
20601:                 }
20602:             } else {
20603:                 $newclone eq '';
20604:             }
20605:         } elsif ($newclone ne '') {
20606:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
20607:         }
20608:         if ($newclone ne $currclone) {
20609:             $changes{'canclone'} = 1;
20610:         }
20611:         my %credits;
20612:         foreach my $type (@types) {
20613:             unless ($type eq 'community') {
20614:                 $credits{$type} = $env{'form.'.$type.'_credits'};
20615:                 $credits{$type} =~ s/[^\d.]+//g;
20616:             }
20617:         }
20618:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
20619:             ($env{'form.coursecredits'} eq '1')) {
20620:             $changes{'coursecredits'} = 1;
20621:             foreach my $type (keys(%credits)) {
20622:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
20623:             }
20624:         } else {
20625:             if ($env{'form.coursecredits'} eq '1') {
20626:                 foreach my $type (@types) {
20627:                     unless ($type eq 'community') {
20628:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
20629:                             $changes{'coursecredits'} = 1;
20630:                         }
20631:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
20632:                     }
20633:                 }
20634:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
20635:                 foreach my $type (@types) {
20636:                     unless ($type eq 'community') {
20637:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
20638:                             $changes{'coursecredits'} = 1;
20639:                             last;
20640:                         }
20641:                     }
20642:                 }
20643:             }
20644:         }
20645:         if ($env{'form.postsubmit'} eq '1') {
20646:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
20647:             my %currtimeout;
20648:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
20649:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
20650:                     $changes{'postsubmit'} = 1;
20651:                 }
20652:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
20653:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
20654:                 }
20655:             } else {
20656:                 $changes{'postsubmit'} = 1;
20657:             }
20658:             foreach my $type (@types) {
20659:                 my $timeout = $env{'form.'.$type.'_timeout'};
20660:                 $timeout =~ s/\D//g;
20661:                 if ($timeout == $staticdefaults{'postsubmit'}) {
20662:                     $timeout = '';
20663:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
20664:                     $timeout = '0';
20665:                 }
20666:                 unless ($timeout eq '') {
20667:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
20668:                 }
20669:                 if (exists($currtimeout{$type})) {
20670:                     if ($timeout ne $currtimeout{$type}) {
20671:                         $changes{'postsubmit'} = 1;
20672:                     }
20673:                 } elsif ($timeout ne '') {
20674:                     $changes{'postsubmit'} = 1;
20675:                 }
20676:             }
20677:         } else {
20678:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
20679:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
20680:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
20681:                     $changes{'postsubmit'} = 1;
20682:                 }
20683:             } else {
20684:                 $changes{'postsubmit'} = 1;
20685:             }
20686:         }
20687:         my (%newdomexttool,%newexttool,%olddomexttool,%oldexttool);
20688:         map { $newdomexttool{$_} = 1; } &Apache::loncommon::get_env_multiple('form.domexttool');
20689:         map { $newexttool{$_} = 1; } &Apache::loncommon::get_env_multiple('form.exttool');
20690:         if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
20691:             %olddomexttool = %{$domconfig{'coursedefaults'}{'domexttool'}};
20692:         } else {
20693:            foreach my $type (@types) {
20694:                if ($staticdefaults{'domexttool'}) {
20695:                    $olddomexttool{$type} = 1;
20696:                } else {
20697:                    $olddomexttool{$type} = 0;
20698:                }
20699:             }
20700:         }
20701:         if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
20702:             %oldexttool = %{$domconfig{'coursedefaults'}{'exttool'}};
20703:         } else {
20704:             foreach my $type (@types) {
20705:                if ($staticdefaults{'exttool'}) {
20706:                    $oldexttool{$type} = 1;
20707:                } else {
20708:                    $oldexttool{$type} = 0;
20709:                }
20710:             }
20711:         }
20712:         foreach my $type (@types) {
20713:             unless ($newdomexttool{$type}) {
20714:                 $newdomexttool{$type} = 0;
20715:             }
20716:             unless ($newexttool{$type}) {
20717:                 $newexttool{$type} = 0;
20718:             }
20719:             if ($newdomexttool{$type} != $olddomexttool{$type}) {
20720:                 $changes{'domexttool'} = 1;
20721:             }
20722:             if ($newexttool{$type} != $oldexttool{$type}) {
20723:                 $changes{'exttool'} = 1;
20724:             }
20725:         }
20726:         $defaultshash{'coursedefaults'}{'domexttool'} = \%newdomexttool;
20727:         $defaultshash{'coursedefaults'}{'exttool'} = \%newexttool;
20728:     }
20729:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20730:                                              $dom);
20731:     if ($putresult eq 'ok') {
20732:         if (keys(%changes) > 0) {
20733:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20734:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
20735:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
20736:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
20737:                 ($changes{'inline_chem'}) || ($changes{'ltiauth'}) || ($changes{'domexttool'}) ||
20738:                 ($changes{'exttool'}) ) {
20739:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','inline_chem','texengine',
20740:                                   'ltiauth') {
20741:                     if ($changes{$item}) {
20742:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
20743:                     }
20744:                 }
20745:                 if ($changes{'coursecredits'}) {
20746:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
20747:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
20748:                             $domdefaults{$type.'credits'} =
20749:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
20750:                         }
20751:                     }
20752:                 }
20753:                 if ($changes{'postsubmit'}) {
20754:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
20755:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
20756:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
20757:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
20758:                                 $domdefaults{$type.'postsubtimeout'} =
20759:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
20760:                             }
20761:                         }
20762:                     }
20763:                 }
20764:                 if ($changes{'uploadquota'}) {
20765:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
20766:                         foreach my $type (@types) {
20767:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
20768:                         }
20769:                     }
20770:                 }
20771:                 if ($changes{'canclone'}) {
20772:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
20773:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
20774:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
20775:                             if (@clonecodes) {
20776:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
20777:                             }
20778:                         }
20779:                     } else {
20780:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
20781:                     }
20782:                 }
20783:                 if ($changes{'domexttool'}) {
20784:                     if (ref($defaultshash{'coursedefaults'}{'domexttool'}) eq 'HASH') {
20785:                         foreach my $type (@types) {
20786:                             $domdefaults{$type.'domexttool'}=$defaultshash{'coursedefaults'}{'domexttool'}{$type};
20787:                         }
20788:                     }
20789:                 }
20790:                 if ($changes{'exttool'}) {
20791:                     if (ref($defaultshash{'coursedefaults'}{'exttool'}) eq 'HASH') {
20792:                         foreach my $type (@types) {
20793:                             $domdefaults{$type.'exttool'}=$defaultshash{'coursedefaults'}{'exttool'}{$type};
20794:                         }
20795:                     }
20796:                 }
20797:                 my $cachetime = 24*60*60;
20798:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20799:                 if (ref($lastactref) eq 'HASH') {
20800:                     $lastactref->{'domdefaults'} = 1;
20801:                 }
20802:             }
20803:             $resulttext = &mt('Changes made:').'<ul>';
20804:             foreach my $item (sort(keys(%changes))) {
20805:                 if ($item eq 'canuse_pdfforms') {
20806:                     if ($env{'form.'.$item} eq '1') {
20807:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
20808:                     } else {
20809:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
20810:                     }
20811:                 } elsif ($item eq 'uselcmath') {
20812:                     if ($env{'form.'.$item} eq '1') {
20813:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
20814:                     } else {
20815:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
20816:                     }
20817:                 } elsif ($item eq 'usejsme') {
20818:                     if ($env{'form.'.$item} eq '1') {
20819:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
20820:                     } else {
20821:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
20822:                     }
20823:                 } elsif ($item eq 'inline_chem') {
20824:                     if ($env{'form.'.$item} eq '1') {
20825:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
20826:                     } else {
20827:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
20828:                     }
20829:                 } elsif ($item eq 'texengine') {
20830:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
20831:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
20832:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
20833:                     }
20834:                 } elsif ($item eq 'anonsurvey_threshold') {
20835:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
20836:                 } elsif ($item eq 'uploadquota') {
20837:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
20838:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
20839:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
20840:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
20841:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
20842:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
20843:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
20844:                                        '</ul>'.
20845:                                        '</li>';
20846:                     } else {
20847:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
20848:                     }
20849:                 } elsif ($item eq 'mysqltables') {
20850:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
20851:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
20852:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
20853:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
20854:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
20855:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
20856:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
20857:                                        '</ul>'.
20858:                                        '</li>';
20859:                     } else {
20860:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
20861:                     }
20862:                 } elsif ($item eq 'postsubmit') {
20863:                     if ($domdefaults{'postsubmit'} eq 'off') {
20864:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
20865:                     } else {
20866:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
20867:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
20868:                             $resulttext .= &mt('durations:').'<ul>';
20869:                             foreach my $type (@types) {
20870:                                 $resulttext .= '<li>';
20871:                                 my $timeout;
20872:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
20873:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
20874:                                 }
20875:                                 my $display;
20876:                                 if ($timeout eq '0') {
20877:                                     $display = &mt('unlimited');
20878:                                 } elsif ($timeout eq '') {
20879:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
20880:                                 } else {
20881:                                     $display = &mt('[quant,_1,second]',$timeout);
20882:                                 }
20883:                                 if ($type eq 'community') {
20884:                                     $resulttext .= &mt('Communities');
20885:                                 } elsif ($type eq 'official') {
20886:                                     $resulttext .= &mt('Official courses');
20887:                                 } elsif ($type eq 'unofficial') {
20888:                                     $resulttext .= &mt('Unofficial courses');
20889:                                 } elsif ($type eq 'textbook') {
20890:                                     $resulttext .= &mt('Textbook courses');
20891:                                 } elsif ($type eq 'placement') {
20892:                                     $resulttext .= &mt('Placement tests');
20893:                                 }
20894:                                 $resulttext .= ' -- '.$display.'</li>';
20895:                             }
20896:                             $resulttext .= '</ul>';
20897:                         }
20898:                         $resulttext .= '</li>';
20899:                     }
20900:                 } elsif ($item eq 'coursecredits') {
20901:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
20902:                         if (($domdefaults{'officialcredits'} eq '') &&
20903:                             ($domdefaults{'unofficialcredits'} eq '') &&
20904:                             ($domdefaults{'textbookcredits'} eq '')) {
20905:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
20906:                         } else {
20907:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
20908:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
20909:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
20910:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
20911:                                            '</ul>'.
20912:                                            '</li>';
20913:                         }
20914:                     } else {
20915:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
20916:                     }
20917:                 } elsif ($item eq 'canclone') {
20918:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
20919:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
20920:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
20921:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
20922:                         }
20923:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
20924:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
20925:                     } else {
20926:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
20927:                     }
20928:                 } elsif ($item eq 'ltiauth') {
20929:                     if ($env{'form.'.$item} eq '1') {
20930:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
20931:                     } else {
20932:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
20933:                     }
20934:                 } elsif ($item eq 'domexttool') {
20935:                     my @noyes = (&mt('no'),&mt('yes'));
20936:                     if (ref($defaultshash{'coursedefaults'}{'domexttool'}) eq 'HASH') {
20937:                         $resulttext .= '<li>'.&mt('External Tools defined in the domain may be used as follows:').'<ul>'.
20938:                                        '<li>'.&mt('Official courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'official'}].'</b>').'</li>'.
20939:                                        '<li>'.&mt('Unofficial courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'unofficial'}].'</b>').'</li>'.
20940:                                        '<li>'.&mt('Textbook courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'textbook'}].'</b>').'</li>'.
20941:                                        '<li>'.&mt('Placement tests: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'placement'}].'</b>').'</li>'.
20942:                                        '<li>'.&mt('Communities: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'domexttool'}{'community'}].'</b>').'</li>'.
20943:                                        '</ul>'.
20944:                                        '</li>';
20945:                     } else {
20946:                         $resulttext .= '<li>'.&mt('External Tools defined in the domain may be used in all course types, by default').'</li>';
20947:                     }
20948:                 } elsif ($item eq 'exttool') {
20949:                     my @noyes = (&mt('no'),&mt('yes'));
20950:                     if (ref($defaultshash{'coursedefaults'}{'exttool'}) eq 'HASH') {
20951:                         $resulttext .= '<li>'.&mt('External Tools can be defined and configured in course containers as follows:').'<ul>'.
20952:                                        '<li>'.&mt('Official courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'official'}].'</b>').'</li>'.
20953:                                        '<li>'.&mt('Unofficial courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'unofficial'}].'</b>').'</li>'.
20954:                                        '<li>'.&mt('Textbook courses: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'textbook'}].'</b>').'</li>'.
20955:                                        '<li>'.&mt('Placement tests: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'placement'}].'</b>').'</li>'.
20956:                                        '<li>'.&mt('Communities: [_1]','<b>'.$noyes[$defaultshash{'coursedefaults'}{'exttool'}{'community'}].'</b>').'</li>'.
20957:                                        '</ul>'.
20958:                                        '</li>';
20959:                     } else {
20960:                         $resulttext .= '<li>'.&mt('External Tools can not be defined in any course types, by default').'</li>';
20961:                     }
20962:                 }
20963:             }
20964:             $resulttext .= '</ul>';
20965:         } else {
20966:             $resulttext = &mt('No changes made to course defaults');
20967:         }
20968:     } else {
20969:         $resulttext = '<span class="LC_error">'.
20970:             &mt('An error occurred: [_1]',$putresult).'</span>';
20971:     }
20972:     return $resulttext;
20973: }
20974: 
20975: sub modify_selfenrollment {
20976:     my ($dom,$lastactref,%domconfig) = @_;
20977:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
20978:     my @types = ('official','unofficial','community','textbook','placement');
20979:     my %titles = &tool_titles();
20980:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
20981:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
20982:     $ordered{'default'} = ['types','registered','approval','limit'];
20983: 
20984:     my (%roles,%shown,%toplevel);
20985:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
20986: 
20987:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
20988:         if ($domconfig{'selfenrollment'} eq '') {
20989:             $domconfig{'selfenrollment'} = {};
20990:         }
20991:     }
20992:     %toplevel = (
20993:                   admin      => 'Configuration Rights',
20994:                   default    => 'Default settings',
20995:                   validation => 'Validation of self-enrollment requests',
20996:                 );
20997:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
20998: 
20999:     if (ref($ordered{'admin'}) eq 'ARRAY') {
21000:         foreach my $item (@{$ordered{'admin'}}) {
21001:             foreach my $type (@types) {
21002:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
21003:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
21004:                 } else {
21005:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
21006:                 }
21007:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
21008:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
21009:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
21010:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
21011:                             push(@{$changes{'admin'}{$type}},$item);
21012:                         }
21013:                     } else {
21014:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
21015:                             push(@{$changes{'admin'}{$type}},$item);
21016:                         }
21017:                     }
21018:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
21019:                     push(@{$changes{'admin'}{$type}},$item);
21020:                 }
21021:             }
21022:         }
21023:     }
21024: 
21025:     foreach my $item (@{$ordered{'default'}}) {
21026:         foreach my $type (@types) {
21027:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
21028:             if ($item eq 'types') {
21029:                 unless (($value eq 'all') || ($value eq 'dom')) {
21030:                     $value = '';
21031:                 }
21032:             } elsif ($item eq 'registered') {
21033:                 unless ($value eq '1') {
21034:                     $value = 0;
21035:                 }
21036:             } elsif ($item eq 'approval') {
21037:                 unless ($value =~ /^[012]$/) {
21038:                     $value = 0;
21039:                 }
21040:             } else {
21041:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21042:                     $value = 'none';
21043:                 }
21044:             }
21045:             $selfenrollhash{'default'}{$type}{$item} = $value;
21046:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
21047:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21048:                     if ($selfenrollhash{'default'}{$type}{$item} ne
21049:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
21050:                          push(@{$changes{'default'}{$type}},$item);
21051:                     }
21052:                 } else {
21053:                     push(@{$changes{'default'}{$type}},$item);
21054:                 }
21055:             } else {
21056:                 push(@{$changes{'default'}{$type}},$item);
21057:             }
21058:             if ($item eq 'limit') {
21059:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21060:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
21061:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
21062:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
21063:                     }
21064:                 } else {
21065:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
21066:                 }
21067:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21068:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
21069:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
21070:                          push(@{$changes{'default'}{$type}},'cap');
21071:                     }
21072:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
21073:                     push(@{$changes{'default'}{$type}},'cap');
21074:                 }
21075:             }
21076:         }
21077:     }
21078: 
21079:     foreach my $item (@{$itemsref}) {
21080:         if ($item eq 'fields') {
21081:             my @changed;
21082:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
21083:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
21084:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
21085:             }
21086:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21087:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
21088:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
21089:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
21090:                 } else {
21091:                     @changed = @{$selfenrollhash{'validation'}{$item}};
21092:                 }
21093:             } else {
21094:                 @changed = @{$selfenrollhash{'validation'}{$item}};
21095:             }
21096:             if (@changed) {
21097:                 if ($selfenrollhash{'validation'}{$item}) { 
21098:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
21099:                 } else {
21100:                     $changes{'validation'}{$item} = &mt('None');
21101:                 }
21102:             }
21103:         } else {
21104:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
21105:             if ($item eq 'markup') {
21106:                if ($env{'form.selfenroll_validation_'.$item}) {
21107:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
21108:                }
21109:             }
21110:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21111:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
21112:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
21113:                 }
21114:             }
21115:         }
21116:     }
21117: 
21118:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
21119:                                              $dom);
21120:     if ($putresult eq 'ok') {
21121:         if (keys(%changes) > 0) {
21122:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21123:             $resulttext = &mt('Changes made:').'<ul>';
21124:             foreach my $key ('admin','default','validation') {
21125:                 if (ref($changes{$key}) eq 'HASH') {
21126:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
21127:                     if ($key eq 'validation') {
21128:                         foreach my $item (@{$itemsref}) {
21129:                             if (exists($changes{$key}{$item})) {
21130:                                 if ($item eq 'markup') {
21131:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21132:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
21133:                                 } else {  
21134:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21135:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
21136:                                 }
21137:                             }
21138:                         }
21139:                     } else {
21140:                         foreach my $type (@types) {
21141:                             if ($type eq 'community') {
21142:                                 $roles{'1'} = &mt('Community personnel');
21143:                             } else {
21144:                                 $roles{'1'} = &mt('Course personnel');
21145:                             }
21146:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
21147:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
21148:                                     if ($key eq 'admin') {
21149:                                         my @mgrdc = ();
21150:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21151:                                             foreach my $item (@{$ordered{'admin'}}) {
21152:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
21153:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
21154:                                                         push(@mgrdc,$item);
21155:                                                     }
21156:                                                 }
21157:                                             }
21158:                                             if (@mgrdc) {
21159:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
21160:                                             } else {
21161:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
21162:                                             }
21163:                                         }
21164:                                     } else {
21165:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21166:                                             foreach my $item (@{$ordered{$key}}) {
21167:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21168:                                                     $domdefaults{$type.'selfenroll'.$item} =
21169:                                                         $selfenrollhash{$key}{$type}{$item};
21170:                                                 }
21171:                                             }
21172:                                         }
21173:                                     }
21174:                                 }
21175:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
21176:                                 foreach my $item (@{$ordered{$key}}) {
21177:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21178:                                         $resulttext .= '<li>';
21179:                                         if ($key eq 'admin') {
21180:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
21181:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
21182:                                         } else {
21183:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
21184:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
21185:                                         }
21186:                                         $resulttext .= '</li>';
21187:                                     }
21188:                                 }
21189:                                 $resulttext .= '</ul></li>';
21190:                             }
21191:                         }
21192:                         $resulttext .= '</ul></li>'; 
21193:                     }
21194:                 }
21195:             }
21196:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
21197:                 my $cachetime = 24*60*60;
21198:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21199:                 if (ref($lastactref) eq 'HASH') {
21200:                     $lastactref->{'domdefaults'} = 1;
21201:                 }
21202:             }
21203:             $resulttext .= '</ul>';
21204:         } else {
21205:             $resulttext = &mt('No changes made to self-enrollment settings');
21206:         }
21207:     } else {
21208:         $resulttext = '<span class="LC_error">'.
21209:             &mt('An error occurred: [_1]',$putresult).'</span>';
21210:     }
21211:     return $resulttext;
21212: }
21213: 
21214: sub modify_wafproxy {
21215:     my ($dom,$action,$lastactref,%domconfig) = @_;
21216:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21217:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
21218:         %wafproxy,%changes,%expirecache,%expiresaml);
21219:     foreach my $server (sort(keys(%servers))) {
21220:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21221:         if ($serverhome eq $server) {
21222:             my $serverdom = &Apache::lonnet::host_domain($server);
21223:             if ($serverdom eq $dom) {
21224:                 $canset{$server} = 1;
21225:             }
21226:         }
21227:     }
21228:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
21229:         %{$values{$dom}} = ();
21230:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
21231:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
21232:         }
21233:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
21234:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
21235:         }
21236:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21237:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
21238:         }
21239:     }
21240:     my $output;
21241:     if (keys(%canset)) {
21242:         %{$wafproxy{'alias'}} = ();
21243:         %{$wafproxy{'saml'}} = ();
21244:         foreach my $key (sort(keys(%canset))) {
21245:             if ($env{'form.wafproxy_'.$dom}) {
21246:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
21247:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
21248:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
21249:                     $changes{'alias'} = 1;
21250:                 }
21251:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
21252:                     $wafproxy{'saml'}{$key} = 1;
21253:                 }
21254:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
21255:                     $changes{'saml'} = 1;
21256:                 }
21257:             } else {
21258:                 $wafproxy{'alias'}{$key} = '';
21259:                 $wafproxy{'saml'}{$key} = '';
21260:                 if ($curralias{$key}) {
21261:                     $changes{'alias'} = 1;
21262:                 }
21263:                 if ($currsaml{$key}) {
21264:                     $changes{'saml'} = 1;
21265:                 }
21266:             }
21267:             if ($wafproxy{'alias'}{$key} eq '') {
21268:                 if ($curralias{$key}) {
21269:                     $expirecache{$key} = 1;
21270:                 }
21271:                 delete($wafproxy{'alias'}{$key});
21272:             }
21273:             if ($wafproxy{'saml'}{$key} eq '') {
21274:                 if ($currsaml{$key}) {
21275:                     $expiresaml{$key} = 1;
21276:                 }
21277:                 delete($wafproxy{'saml'}{$key});
21278:             }
21279:         }
21280:         unless (keys(%{$wafproxy{'alias'}})) {
21281:             delete($wafproxy{'alias'});
21282:         }
21283:         unless (keys(%{$wafproxy{'saml'}})) {
21284:             delete($wafproxy{'saml'});
21285:         }
21286:         # Localization for values in %warn occurs in &mt() calls separately.
21287:         my %warn = (
21288:                      trusted => 'trusted IP range(s)',
21289:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
21290:                      vpnext => 'IP range(s) for backend WAF connections',
21291:                    );
21292:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21293:             my $possible = $env{'form.wafproxy_'.$item};
21294:             $possible =~ s/^\s+|\s+$//g;
21295:             if ($possible ne '') {
21296:                 if ($item eq 'remoteip') {
21297:                     if ($possible =~ /^[mhn]$/) {
21298:                         $wafproxy{$item} = $possible;
21299:                     }
21300:                 } elsif ($item eq 'ipheader') {
21301:                     if ($wafproxy{'remoteip'} eq 'h') {
21302:                         $wafproxy{$item} = $possible;
21303:                     }
21304:                 } elsif ($item eq 'sslopt') {
21305:                     if ($possible =~ /^0|1$/) {
21306:                         $wafproxy{$item} = $possible;
21307:                     }
21308:                 } else {
21309:                     my (@ok,$count);
21310:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
21311:                         unless ($env{'form.wafproxy_vpnaccess'}) {
21312:                             $possible = '';
21313:                         }
21314:                     } elsif ($item eq 'trusted') {
21315:                         unless ($wafproxy{'remoteip'} eq 'h') {
21316:                             $possible = '';
21317:                         }
21318:                     }
21319:                     unless ($possible eq '') {
21320:                         $possible =~ s/[\r\n]+/\s/g;
21321:                         $possible =~ s/\s*-\s*/-/g;
21322:                         $possible =~ s/\s+/,/g;
21323:                         $possible =~ s/,+/,/g;
21324:                     }
21325:                     $count = 0;
21326:                     if ($possible ne '') {
21327:                         foreach my $poss (split(/\,/,$possible)) {
21328:                             $count ++;
21329:                             $poss = &validate_ip_pattern($poss);
21330:                             if ($poss ne '') {
21331:                                 push(@ok,$poss);
21332:                             }
21333:                         }
21334:                         my $diff = $count - scalar(@ok);
21335:                         if ($diff) {
21336:                             push(@warnings,'<li>'.
21337:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
21338:                                      $diff,$warn{$item}).
21339:                                  '</li>');
21340:                         }
21341:                         if (@ok) {
21342:                             my @cidr_list;
21343:                             foreach my $item (@ok) {
21344:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
21345:                             }
21346:                             $wafproxy{$item} = join(',',@cidr_list);
21347:                         }
21348:                     }
21349:                 }
21350:                 if ($wafproxy{$item} ne $currvalue{$item}) {
21351:                     $changes{$item} = 1;
21352:                 }
21353:             } elsif ($currvalue{$item}) {
21354:                 $changes{$item} = 1;
21355:             }
21356:         }
21357:     } else {
21358:         if (keys(%curralias)) {
21359:             $changes{'alias'} = 1;
21360:         }
21361:         if (keys(%currsaml)) {
21362:             $changes{'saml'} = 1;
21363:         }
21364:         if (keys(%currvalue)) {
21365:             foreach my $key (keys(%currvalue)) {
21366:                 $changes{$key} = 1;
21367:             }
21368:         }
21369:     }
21370:     if (keys(%changes)) {
21371:         my %defaultshash = (
21372:                               wafproxy => \%wafproxy,
21373:                            );
21374:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21375:                                                  $dom);
21376:         if ($putresult eq 'ok') {
21377:             my $cachetime = 24*60*60;
21378:             my (%domdefaults,$updatedomdefs);
21379:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
21380:                 if ($changes{$item}) {
21381:                     unless ($updatedomdefs) {
21382:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
21383:                         $updatedomdefs = 1;
21384:                     }
21385:                     if ($wafproxy{$item}) {
21386:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
21387:                     } elsif (exists($domdefaults{'waf_'.$item})) {
21388:                         delete($domdefaults{'waf_'.$item});
21389:                     }
21390:                 }
21391:             }
21392:             if ($updatedomdefs) {
21393:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21394:                 if (ref($lastactref) eq 'HASH') {
21395:                     $lastactref->{'domdefaults'} = 1;
21396:                 }
21397:             }
21398:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
21399:                 my %updates = %expirecache;
21400:                 foreach my $key (keys(%expirecache)) {
21401:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
21402:                 }
21403:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
21404:                     my $cachetime = 24*60*60;
21405:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
21406:                         $updates{$key} = 1;
21407:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
21408:                                                       $cachetime);
21409:                     }
21410:                 }
21411:                 if (ref($lastactref) eq 'HASH') {
21412:                     $lastactref->{'proxyalias'} = \%updates;
21413:                 }
21414:             }
21415:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
21416:                 my %samlupdates = %expiresaml;
21417:                 foreach my $key (keys(%expiresaml)) {
21418:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
21419:                 }
21420:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
21421:                     my $cachetime = 24*60*60;
21422:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
21423:                         $samlupdates{$key} = 1;
21424:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
21425:                                                       $cachetime);
21426:                     }
21427:                 }
21428:                 if (ref($lastactref) eq 'HASH') {
21429:                     $lastactref->{'proxysaml'} = \%samlupdates;
21430:                 }
21431:             }
21432:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
21433:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21434:                 if ($changes{$item}) {
21435:                     if ($item eq 'alias') {
21436:                         my $numaliased = 0;
21437:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
21438:                             my $shown;
21439:                             if (keys(%{$wafproxy{'alias'}})) {
21440:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
21441:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
21442:                                                          &Apache::lonnet::hostname($server),
21443:                                                          $wafproxy{'alias'}{$server}).'</li>';
21444:                                     $numaliased ++;
21445:                                 }
21446:                                 if ($numaliased) {
21447:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
21448:                                                           '<ul>'.$shown.'</ul>').'</li>';
21449:                                 }
21450:                             }
21451:                         }
21452:                         unless ($numaliased) {
21453:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
21454:                         }
21455:                     } elsif ($item eq 'saml') {
21456:                         my $shown;
21457:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
21458:                             if (keys(%{$wafproxy{'saml'}})) {
21459:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
21460:                             }
21461:                         }
21462:                         if ($shown) {
21463:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
21464:                                                   $shown).'</li>';
21465:                         } else {
21466:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
21467:                         }
21468:                     } else {
21469:                         if ($item eq 'remoteip') {
21470:                             my %ip_methods = &remoteip_methods();
21471:                             if ($wafproxy{$item} =~ /^[mh]$/) {
21472:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
21473:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
21474:                             } else {
21475:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
21476:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
21477:                                                '</li>';
21478:                                 } else {
21479:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
21480:                                 }
21481:                             }
21482:                         } elsif ($item eq 'ipheader') {
21483:                             if ($wafproxy{$item}) {
21484:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
21485:                                                       $wafproxy{$item}).'</li>';
21486:                             } else {
21487:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
21488:                             }
21489:                         } elsif ($item eq 'trusted') {
21490:                             if ($wafproxy{$item}) {
21491:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
21492:                                                       $wafproxy{$item}).'</li>';
21493:                             } else {
21494:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
21495:                             }
21496:                         } elsif ($item eq 'vpnint') {
21497:                             if ($wafproxy{$item}) {
21498:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
21499:                                                        $wafproxy{$item}).'</li>';
21500:                             } else {
21501:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
21502:                             }
21503:                         } elsif ($item eq 'vpnext') {
21504:                             if ($wafproxy{$item}) {
21505:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
21506:                                                        $wafproxy{$item}).'</li>';
21507:                             } else {
21508:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
21509:                             }
21510:                         } elsif ($item eq 'sslopt') {
21511:                             if ($wafproxy{$item}) {
21512:                                 $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>';
21513:                             } else {
21514:                                 $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>';
21515:                             }
21516:                         }
21517:                     }
21518:                 }
21519:             }
21520:             $output .= '</ul>';
21521:         } else {
21522:             $output = '<span class="LC_error">'.
21523:                       &mt('An error occurred: [_1]',$putresult).'</span>';
21524:         }
21525:     } elsif (keys(%canset)) {
21526:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
21527:     }
21528:     if (@warnings) {
21529:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
21530:                        join("\n",@warnings).'</ul>';
21531:     }
21532:     return $output;
21533: }
21534: 
21535: sub validate_ip_pattern {
21536:     my ($pattern) = @_;
21537:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
21538:         my ($start,$end) = ($1,$2);
21539:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
21540:             if (($start !~ m{/}) && ($end !~ m{/})) {
21541:                 return $start.'-'.$end;
21542:             }
21543:         }
21544:     } elsif ($pattern ne '') {
21545:         $pattern = &Net::CIDR::cidrvalidate($pattern);
21546:         if ($pattern ne '') {
21547:             return $pattern;
21548:         }
21549:     }
21550:     return;
21551: }
21552: 
21553: sub modify_usersessions {
21554:     my ($dom,$lastactref,%domconfig) = @_;
21555:     my @hostingtypes = ('version','excludedomain','includedomain');
21556:     my @offloadtypes = ('primary','default');
21557:     my %types = (
21558:                   remote => \@hostingtypes,
21559:                   hosted => \@hostingtypes,
21560:                   spares => \@offloadtypes,
21561:                 );
21562:     my @prefixes = ('remote','hosted','spares');
21563:     my @lcversions = &Apache::lonnet::all_loncaparevs();
21564:     my (%by_ip,%by_location,@intdoms,@instdoms);
21565:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
21566:     my @locations = sort(keys(%by_location));
21567:     my (%defaultshash,%changes);
21568:     foreach my $prefix (@prefixes) {
21569:         $defaultshash{'usersessions'}{$prefix} = {};
21570:     }
21571:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21572:     my $resulttext;
21573:     my %iphost = &Apache::lonnet::get_iphost();
21574:     foreach my $prefix (@prefixes) {
21575:         next if ($prefix eq 'spares');
21576:         foreach my $type (@{$types{$prefix}}) {
21577:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
21578:             if ($type eq 'version') {
21579:                 my $value = $env{'form.'.$prefix.'_'.$type};
21580:                 my $okvalue;
21581:                 if ($value ne '') {
21582:                     if (grep(/^\Q$value\E$/,@lcversions)) {
21583:                         $okvalue = $value;
21584:                     }
21585:                 }
21586:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
21587:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
21588:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
21589:                             if ($inuse == 0) {
21590:                                 $changes{$prefix}{$type} = 1;
21591:                             } else {
21592:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
21593:                                     $changes{$prefix}{$type} = 1;
21594:                                 }
21595:                                 if ($okvalue ne '') {
21596:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
21597:                                 } 
21598:                             }
21599:                         } else {
21600:                             if (($inuse == 1) && ($okvalue ne '')) {
21601:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
21602:                                 $changes{$prefix}{$type} = 1;
21603:                             }
21604:                         }
21605:                     } else {
21606:                         if (($inuse == 1) && ($okvalue ne '')) {
21607:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
21608:                             $changes{$prefix}{$type} = 1;
21609:                         }
21610:                     }
21611:                 } else {
21612:                     if (($inuse == 1) && ($okvalue ne '')) {
21613:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
21614:                         $changes{$prefix}{$type} = 1;
21615:                     }
21616:                 }
21617:             } else {
21618:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
21619:                 my @okvals;
21620:                 foreach my $val (@vals) {
21621:                     if ($val =~ /:/) {
21622:                         my @items = split(/:/,$val);
21623:                         foreach my $item (@items) {
21624:                             if (ref($by_location{$item}) eq 'ARRAY') {
21625:                                 push(@okvals,$item);
21626:                             }
21627:                         }
21628:                     } else {
21629:                         if (ref($by_location{$val}) eq 'ARRAY') {
21630:                             push(@okvals,$val);
21631:                         }
21632:                     }
21633:                 }
21634:                 @okvals = sort(@okvals);
21635:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
21636:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
21637:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
21638:                             if ($inuse == 0) {
21639:                                 $changes{$prefix}{$type} = 1; 
21640:                             } else {
21641:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
21642:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
21643:                                 if (@changed > 0) {
21644:                                     $changes{$prefix}{$type} = 1;
21645:                                 }
21646:                             }
21647:                         } else {
21648:                             if ($inuse == 1) {
21649:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
21650:                                 $changes{$prefix}{$type} = 1;
21651:                             }
21652:                         } 
21653:                     } else {
21654:                         if ($inuse == 1) {
21655:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
21656:                             $changes{$prefix}{$type} = 1;
21657:                         }
21658:                     }
21659:                 } else {
21660:                     if ($inuse == 1) {
21661:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
21662:                         $changes{$prefix}{$type} = 1;
21663:                     }
21664:                 }
21665:             }
21666:         }
21667:     }
21668: 
21669:     my @alldoms = &Apache::lonnet::all_domains();
21670:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21671:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
21672:     my $savespares;
21673: 
21674:     foreach my $lonhost (sort(keys(%servers))) {
21675:         my $serverhomeID =
21676:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
21677:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
21678:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
21679:         my %spareschg;
21680:         foreach my $type (@{$types{'spares'}}) {
21681:             my @okspares;
21682:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
21683:             foreach my $server (@checked) {
21684:                 if (&Apache::lonnet::hostname($server) ne '') {
21685:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
21686:                         unless (grep(/^\Q$server\E$/,@okspares)) {
21687:                             push(@okspares,$server);
21688:                         }
21689:                     }
21690:                 }
21691:             }
21692:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
21693:             my $newspare;
21694:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
21695:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
21696:                     $newspare = $new;
21697:                 }
21698:             }
21699:             my @spares;
21700:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
21701:                 @spares = sort(@okspares,$newspare);
21702:             } else {
21703:                 @spares = sort(@okspares);
21704:             }
21705:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
21706:             if (ref($spareid{$lonhost}) eq 'HASH') {
21707:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
21708:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
21709:                     if (@diffs > 0) {
21710:                         $spareschg{$type} = 1;
21711:                     }
21712:                 }
21713:             }
21714:         }
21715:         if (keys(%spareschg) > 0) {
21716:             $changes{'spares'}{$lonhost} = \%spareschg;
21717:         }
21718:     }
21719:     $defaultshash{'usersessions'}{'offloadnow'} = {};
21720:     $defaultshash{'usersessions'}{'offloadoth'} = {};
21721:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
21722:     my @okoffload;
21723:     if (@offloadnow) {
21724:         foreach my $server (@offloadnow) {
21725:             if (&Apache::lonnet::hostname($server) ne '') {
21726:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
21727:                     push(@okoffload,$server);
21728:                 }
21729:             }
21730:         }
21731:         if (@okoffload) {
21732:             foreach my $lonhost (@okoffload) {
21733:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
21734:             }
21735:         }
21736:     }
21737:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
21738:     my @okoffloadoth;
21739:     if (@offloadoth) {
21740:         foreach my $server (@offloadoth) {
21741:             if (&Apache::lonnet::hostname($server) ne '') {
21742:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
21743:                     push(@okoffloadoth,$server);
21744:                 }
21745:             }
21746:         }
21747:         if (@okoffloadoth) {
21748:             foreach my $lonhost (@okoffloadoth) {
21749:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
21750:             }
21751:         }
21752:     }
21753:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
21754:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
21755:             if (ref($changes{'spares'}) eq 'HASH') {
21756:                 if (keys(%{$changes{'spares'}}) > 0) {
21757:                     $savespares = 1;
21758:                 }
21759:             }
21760:         } else {
21761:             $savespares = 1;
21762:         }
21763:         foreach my $offload ('offloadnow','offloadoth') {
21764:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
21765:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
21766:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
21767:                         $changes{$offload} = 1;
21768:                         last;
21769:                     }
21770:                 }
21771:                 unless ($changes{$offload}) {
21772:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
21773:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
21774:                             $changes{$offload} = 1;
21775:                             last;
21776:                         }
21777:                     }
21778:                 }
21779:             } else {
21780:                 if (($offload eq 'offloadnow') && (@okoffload)) {
21781:                      $changes{'offloadnow'} = 1;
21782:                 }
21783:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
21784:                     $changes{'offloadoth'} = 1;
21785:                 }
21786:             }
21787:         }
21788:     } else {
21789:         if (@okoffload) {
21790:             $changes{'offloadnow'} = 1;
21791:         }
21792:         if (@okoffloadoth) {
21793:             $changes{'offloadoth'} = 1;
21794:         }
21795:     }
21796:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
21797:     if ((keys(%changes) > 0) || ($savespares)) {
21798:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21799:                                                  $dom);
21800:         if ($putresult eq 'ok') {
21801:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
21802:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
21803:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
21804:                 }
21805:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
21806:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
21807:                 }
21808:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
21809:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
21810:                 }
21811:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
21812:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
21813:                 }
21814:             }
21815:             my $cachetime = 24*60*60;
21816:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21817:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
21818:             if (ref($lastactref) eq 'HASH') {
21819:                 $lastactref->{'domdefaults'} = 1;
21820:                 $lastactref->{'usersessions'} = 1;
21821:             }
21822:             if (keys(%changes) > 0) {
21823:                 my %lt = &usersession_titles();
21824:                 $resulttext = &mt('Changes made:').'<ul>';
21825:                 foreach my $prefix (@prefixes) {
21826:                     if (ref($changes{$prefix}) eq 'HASH') {
21827:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
21828:                         if ($prefix eq 'spares') {
21829:                             if (ref($changes{$prefix}) eq 'HASH') {
21830:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
21831:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
21832:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
21833:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
21834:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
21835:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
21836:                                         foreach my $type (@{$types{$prefix}}) {
21837:                                             if ($changes{$prefix}{$lonhost}{$type}) {
21838:                                                 my $offloadto = &mt('None');
21839:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
21840:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
21841:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
21842:                                                     }
21843:                                                 }
21844:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
21845:                                             }
21846:                                         }
21847:                                     }
21848:                                     $resulttext .= '</li>';
21849:                                 }
21850:                             }
21851:                         } else {
21852:                             foreach my $type (@{$types{$prefix}}) {
21853:                                 if (defined($changes{$prefix}{$type})) {
21854:                                     my ($newvalue,$notinuse);
21855:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
21856:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
21857:                                             if ($type eq 'version') {
21858:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
21859:                                             } else {
21860:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
21861:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
21862:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
21863:                                                     }
21864:                                                 } else {
21865:                                                     $notinuse = 1;
21866:                                                 }
21867:                                             }
21868:                                         }
21869:                                     }
21870:                                     if ($newvalue eq '') {
21871:                                         if ($type eq 'version') {
21872:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
21873:                                         } elsif ($notinuse) {
21874:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
21875:                                         } else {
21876:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
21877:                                         }
21878:                                     } else {
21879:                                         if ($type eq 'version') {
21880:                                             $newvalue .= ' '.&mt('(or later)');
21881:                                         }
21882:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
21883:                                     }
21884:                                 }
21885:                             }
21886:                         }
21887:                         $resulttext .= '</ul>';
21888:                     }
21889:                 }
21890:                 if ($changes{'offloadnow'}) {
21891:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
21892:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
21893:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
21894:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
21895:                                 $resulttext .= '<li>'.$lonhost.'</li>';
21896:                             }
21897:                             $resulttext .= '</ul>';
21898:                         } else {
21899:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
21900:                         }
21901:                     } else {
21902:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
21903:                     }
21904:                 }
21905:                 if ($changes{'offloadoth'}) {
21906:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
21907:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
21908:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
21909:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
21910:                                 $resulttext .= '<li>'.$lonhost.'</li>';
21911:                             }
21912:                             $resulttext .= '</ul>';
21913:                         } else {
21914:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
21915:                         }
21916:                     } else {
21917:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
21918:                     }
21919:                 }
21920:                 $resulttext .= '</ul>';
21921:             } else {
21922:                 $resulttext = $nochgmsg;
21923:             }
21924:         } else {
21925:             $resulttext = '<span class="LC_error">'.
21926:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21927:         }
21928:     } else {
21929:         $resulttext = $nochgmsg;
21930:     }
21931:     return $resulttext;
21932: }
21933: 
21934: sub modify_ssl {
21935:     my ($dom,$lastactref,%domconfig) = @_;
21936:     my (%by_ip,%by_location,@intdoms,@instdoms);
21937:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
21938:     my @locations = sort(keys(%by_location));
21939:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21940:     my (%defaultshash,%changes);
21941:     my $action = 'ssl';
21942:     my @prefixes = ('connto','connfrom','replication');
21943:     foreach my $prefix (@prefixes) {
21944:         $defaultshash{$action}{$prefix} = {};
21945:     }
21946:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21947:     my $resulttext;
21948:     my %iphost = &Apache::lonnet::get_iphost();
21949:     my @reptypes = ('certreq','nocertreq');
21950:     my @connecttypes = ('dom','intdom','other');
21951:     my %types = (
21952:                   connto      => \@connecttypes,
21953:                   connfrom    => \@connecttypes,
21954:                   replication => \@reptypes,
21955:                 );
21956:     foreach my $prefix (sort(keys(%types))) {
21957:         foreach my $type (@{$types{$prefix}}) {
21958:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
21959:                 my $value = 'yes';
21960:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
21961:                     $value = $env{'form.'.$prefix.'_'.$type};
21962:                 }
21963:                 if (ref($domconfig{$action}) eq 'HASH') {
21964:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
21965:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
21966:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
21967:                                 $changes{$prefix}{$type} = 1;
21968:                             }
21969:                             $defaultshash{$action}{$prefix}{$type} = $value;
21970:                         } else {
21971:                             $defaultshash{$action}{$prefix}{$type} = $value;
21972:                             $changes{$prefix}{$type} = 1;
21973:                         }
21974:                     } else {
21975:                         $defaultshash{$action}{$prefix}{$type} = $value;
21976:                         $changes{$prefix}{$type} = 1;
21977:                     }
21978:                 } else {
21979:                     $defaultshash{$action}{$prefix}{$type} = $value;
21980:                     $changes{$prefix}{$type} = 1;
21981:                 }
21982:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
21983:                     delete($changes{$prefix}{$type});
21984:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
21985:                     delete($changes{$prefix}{$type});
21986:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
21987:                     delete($changes{$prefix}{$type});
21988:                 }
21989:             } elsif ($prefix eq 'replication') {
21990:                 if (@locations > 0) {
21991:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
21992:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
21993:                     my @okvals;
21994:                     foreach my $val (@vals) {
21995:                         if ($val =~ /:/) {
21996:                             my @items = split(/:/,$val);
21997:                             foreach my $item (@items) {
21998:                                 if (ref($by_location{$item}) eq 'ARRAY') {
21999:                                     push(@okvals,$item);
22000:                                 }
22001:                             }
22002:                         } else {
22003:                             if (ref($by_location{$val}) eq 'ARRAY') {
22004:                                 push(@okvals,$val);
22005:                             }
22006:                         }
22007:                     }
22008:                     @okvals = sort(@okvals);
22009:                     if (ref($domconfig{$action}) eq 'HASH') {
22010:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22011:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
22012:                                 if ($inuse == 0) {
22013:                                     $changes{$prefix}{$type} = 1;
22014:                                 } else {
22015:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22016:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
22017:                                     if (@changed > 0) {
22018:                                         $changes{$prefix}{$type} = 1;
22019:                                     }
22020:                                 }
22021:                             } else {
22022:                                 if ($inuse == 1) {
22023:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22024:                                     $changes{$prefix}{$type} = 1;
22025:                                 }
22026:                             }
22027:                         } else {
22028:                             if ($inuse == 1) {
22029:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
22030:                                 $changes{$prefix}{$type} = 1;
22031:                             }
22032:                         }
22033:                     } else {
22034:                         if ($inuse == 1) {
22035:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
22036:                             $changes{$prefix}{$type} = 1;
22037:                         }
22038:                     }
22039:                 }
22040:             }
22041:         }
22042:     }
22043:     if (keys(%changes)) {
22044:         foreach my $prefix (keys(%changes)) {
22045:             if (ref($changes{$prefix}) eq 'HASH') {
22046:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
22047:                     delete($changes{$prefix});
22048:                 }
22049:             } else {
22050:                 delete($changes{$prefix});
22051:             }
22052:         }
22053:     }
22054:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
22055:     if (keys(%changes) > 0) {
22056:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22057:                                                  $dom);
22058:         if ($putresult eq 'ok') {
22059:             if (ref($defaultshash{$action}) eq 'HASH') {
22060:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
22061:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
22062:                 }
22063:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
22064:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
22065:                 }
22066:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
22067:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
22068:                 }
22069:             }
22070:             my $cachetime = 24*60*60;
22071:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22072:             if (ref($lastactref) eq 'HASH') {
22073:                 $lastactref->{'domdefaults'} = 1;
22074:             }
22075:             if (keys(%changes) > 0) {
22076:                 my %titles = &ssl_titles();
22077:                 $resulttext = &mt('Changes made:').'<ul>';
22078:                 foreach my $prefix (@prefixes) {
22079:                     if (ref($changes{$prefix}) eq 'HASH') {
22080:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
22081:                         foreach my $type (@{$types{$prefix}}) {
22082:                             if (defined($changes{$prefix}{$type})) {
22083:                                 my ($newvalue,$notinuse);
22084:                                 if (ref($defaultshash{$action}) eq 'HASH') {
22085:                                     if (ref($defaultshash{$action}{$prefix})) {
22086:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22087:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
22088:                                         } else {
22089:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
22090:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
22091:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
22092:                                                 }
22093:                                             } else {
22094:                                                 $notinuse = 1;
22095:                                             }
22096:                                         }
22097:                                     }
22098:                                     if ($notinuse) {
22099:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
22100:                                     } elsif ($newvalue eq '') {
22101:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
22102:                                     } else {
22103:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
22104:                                     }
22105:                                 }
22106:                             }
22107:                         }
22108:                         $resulttext .= '</ul>';
22109:                     }
22110:                 }
22111:             } else {
22112:                 $resulttext = $nochgmsg;
22113:             }
22114:         } else {
22115:             $resulttext = '<span class="LC_error">'.
22116:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22117:         }
22118:     } else {
22119:         $resulttext = $nochgmsg;
22120:     }
22121:     return $resulttext;
22122: }
22123: 
22124: sub modify_trust {
22125:     my ($dom,$lastactref,%domconfig) = @_;
22126:     my (%by_ip,%by_location,@intdoms,@instdoms);
22127:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22128:     my @locations = sort(keys(%by_location));
22129:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
22130:     my @types = ('exc','inc');
22131:     my (%defaultshash,%changes);
22132:     foreach my $prefix (@prefixes) {
22133:         $defaultshash{'trust'}{$prefix} = {};
22134:     }
22135:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22136:     my $resulttext;
22137:     foreach my $prefix (@prefixes) {
22138:         foreach my $type (@types) {
22139:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22140:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22141:             my @okvals;
22142:             foreach my $val (@vals) {
22143:                 if ($val =~ /:/) {
22144:                     my @items = split(/:/,$val);
22145:                     foreach my $item (@items) {
22146:                         if (ref($by_location{$item}) eq 'ARRAY') {
22147:                             push(@okvals,$item);
22148:                         }
22149:                     }
22150:                 } else {
22151:                     if (ref($by_location{$val}) eq 'ARRAY') {
22152:                         push(@okvals,$val);
22153:                     }
22154:                 }
22155:             }
22156:             @okvals = sort(@okvals);
22157:             if (ref($domconfig{'trust'}) eq 'HASH') {
22158:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
22159:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22160:                         if ($inuse == 0) {
22161:                             $changes{$prefix}{$type} = 1;
22162:                         } else {
22163:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22164:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
22165:                             if (@changed > 0) {
22166:                                 $changes{$prefix}{$type} = 1;
22167:                             }
22168:                         }
22169:                     } else {
22170:                         if ($inuse == 1) {
22171:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22172:                             $changes{$prefix}{$type} = 1;
22173:                         }
22174:                     }
22175:                 } else {
22176:                     if ($inuse == 1) {
22177:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22178:                         $changes{$prefix}{$type} = 1;
22179:                     }
22180:                 }
22181:             } else {
22182:                 if ($inuse == 1) {
22183:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22184:                     $changes{$prefix}{$type} = 1;
22185:                 }
22186:             }
22187:         }
22188:     }
22189:     my $nochgmsg = &mt('No changes made to trust settings.');
22190:     if (keys(%changes) > 0) {
22191:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22192:                                                  $dom);
22193:         if ($putresult eq 'ok') {
22194:             if (ref($defaultshash{'trust'}) eq 'HASH') {
22195:                 foreach my $prefix (@prefixes) {
22196:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
22197:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
22198:                     }
22199:                 }
22200:             }
22201:             my $cachetime = 24*60*60;
22202:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22203:             &Apache::lonnet::do_cache_new('trust',$dom,$defaultshash{'trust'},3600);
22204:             if (ref($lastactref) eq 'HASH') {
22205:                 $lastactref->{'domdefaults'} = 1;
22206:                 $lastactref->{'trust'} = 1;
22207:             }
22208:             if (keys(%changes) > 0) {
22209:                 my %lt = &trust_titles();
22210:                 $resulttext = &mt('Changes made:').'<ul>';
22211:                 foreach my $prefix (@prefixes) {
22212:                     if (ref($changes{$prefix}) eq 'HASH') {
22213:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22214:                         foreach my $type (@types) {
22215:                             if (defined($changes{$prefix}{$type})) {
22216:                                 my ($newvalue,$notinuse);
22217:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
22218:                                     if (ref($defaultshash{'trust'}{$prefix})) {
22219:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22220:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
22221:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
22222:                                             }
22223:                                         } else {
22224:                                             $notinuse = 1;
22225:                                         }
22226:                                     }
22227:                                 }
22228:                                 if ($notinuse) {
22229:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22230:                                 } elsif ($newvalue eq '') {
22231:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22232:                                 } else {
22233:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22234:                                 }
22235:                             }
22236:                         }
22237:                         $resulttext .= '</ul>';
22238:                     }
22239:                 }
22240:                 $resulttext .= '</ul>';
22241:             } else {
22242:                 $resulttext = $nochgmsg;
22243:             }
22244:         } else {
22245:             $resulttext = '<span class="LC_error">'.
22246:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22247:         }
22248:     } else {
22249:         $resulttext = $nochgmsg;
22250:     }
22251:     return $resulttext;
22252: }
22253: 
22254: sub modify_loadbalancing {
22255:     my ($dom,%domconfig) = @_;
22256:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
22257:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
22258:     my ($othertitle,$usertypes,$types) =
22259:         &Apache::loncommon::sorted_inst_types($dom);
22260:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22261:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
22262:     my @sparestypes = ('primary','default');
22263:     my %typetitles = &sparestype_titles();
22264:     my $resulttext;
22265:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
22266:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22267:         %existing = %{$domconfig{'loadbalancing'}};
22268:     }
22269:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
22270:                               \%currtargets,\%currrules,\%currcookies);
22271:     my ($saveloadbalancing,%defaultshash,%changes);
22272:     my ($alltypes,$othertypes,$titles) =
22273:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
22274:     my %ruletitles = &offloadtype_text();
22275:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
22276:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
22277:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
22278:         if ($balancer eq '') {
22279:             next;
22280:         }
22281:         if (!exists($servers{$balancer})) {
22282:             if (exists($currbalancer{$balancer})) {
22283:                 push(@{$changes{'delete'}},$balancer);
22284:             }
22285:             next;
22286:         }
22287:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
22288:             push(@{$changes{'delete'}},$balancer);
22289:             next;
22290:         }
22291:         if (!exists($currbalancer{$balancer})) {
22292:             push(@{$changes{'add'}},$balancer);
22293:         }
22294:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
22295:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
22296:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
22297:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22298:             $saveloadbalancing = 1;
22299:         }
22300:         foreach my $sparetype (@sparestypes) {
22301:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
22302:             my @offloadto;
22303:             foreach my $target (@targets) {
22304:                 if (($servers{$target}) && ($target ne $balancer)) {
22305:                     if ($sparetype eq 'default') {
22306:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
22307:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
22308:                         }
22309:                     }
22310:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
22311:                         push(@offloadto,$target);
22312:                     }
22313:                 }
22314:             }
22315:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
22316:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
22317:                     push(@offloadto,$balancer);
22318:                 }
22319:             }
22320:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
22321:         }
22322:         if ($env{'form.loadbalancing_cookie_'.$i}) {
22323:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
22324:             if (exists($currbalancer{$balancer})) {
22325:                 unless ($currcookies{$balancer}) {
22326:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
22327:                 }
22328:             }
22329:         } elsif (exists($currbalancer{$balancer})) {
22330:             if ($currcookies{$balancer}) {
22331:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
22332:             }
22333:         }
22334:         if (ref($currtargets{$balancer}) eq 'HASH') {
22335:             foreach my $sparetype (@sparestypes) {
22336:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
22337:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
22338:                     if (@targetdiffs > 0) {
22339:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22340:                     }
22341:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22342:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22343:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22344:                     }
22345:                 }
22346:             }
22347:         } else {
22348:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
22349:                 foreach my $sparetype (@sparestypes) {
22350:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22351:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22352:                             $changes{'curr'}{$balancer}{'targets'} = 1;
22353:                         }
22354:                     }
22355:                 }
22356:             }
22357:         }
22358:         my $ishomedom;
22359:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
22360:             $ishomedom = 1;
22361:         }
22362:         if (ref($alltypes) eq 'ARRAY') {
22363:             foreach my $type (@{$alltypes}) {
22364:                 my $rule;
22365:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
22366:                          (!$ishomedom)) {
22367:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
22368:                 }
22369:                 if ($rule eq 'specific') {
22370:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
22371:                     if (exists($servers{$specifiedhost})) {
22372:                         $rule = $specifiedhost;
22373:                     }
22374:                 }
22375:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
22376:                 if (ref($currrules{$balancer}) eq 'HASH') {
22377:                     if ($rule ne $currrules{$balancer}{$type}) {
22378:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22379:                     }
22380:                 } elsif ($rule ne '') {
22381:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22382:                 }
22383:             }
22384:         }
22385:     }
22386:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
22387:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
22388:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
22389:             $defaultshash{'loadbalancing'} = {};
22390:         }
22391:         my $putresult = &Apache::lonnet::put_dom('configuration',
22392:                                                  \%defaultshash,$dom);
22393:         if ($putresult eq 'ok') {
22394:             if (keys(%changes) > 0) {
22395:                 my %toupdate;
22396:                 if (ref($changes{'delete'}) eq 'ARRAY') {
22397:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
22398:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
22399:                         $toupdate{$balancer} = 1;
22400:                     }
22401:                 }
22402:                 if (ref($changes{'add'}) eq 'ARRAY') {
22403:                     foreach my $balancer (sort(@{$changes{'add'}})) {
22404:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
22405:                         $toupdate{$balancer} = 1;
22406:                     }
22407:                 }
22408:                 if (ref($changes{'curr'}) eq 'HASH') {
22409:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
22410:                         $toupdate{$balancer} = 1;
22411:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
22412:                             if ($changes{'curr'}{$balancer}{'targets'}) {
22413:                                 my %offloadstr;
22414:                                 foreach my $sparetype (@sparestypes) {
22415:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22416:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22417:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
22418:                                         }
22419:                                     }
22420:                                 }
22421:                                 if (keys(%offloadstr) == 0) {
22422:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
22423:                                 } else {
22424:                                     my $showoffload;
22425:                                     foreach my $sparetype (@sparestypes) {
22426:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
22427:                                         if (defined($offloadstr{$sparetype})) {
22428:                                             $showoffload .= $offloadstr{$sparetype};
22429:                                         } else {
22430:                                             $showoffload .= &mt('None');
22431:                                         }
22432:                                         $showoffload .= ('&nbsp;'x3);
22433:                                     }
22434:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
22435:                                 }
22436:                             }
22437:                         }
22438:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
22439:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
22440:                                 foreach my $type (@{$alltypes}) {
22441:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
22442:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
22443:                                         my $balancetext;
22444:                                         if ($rule eq '') {
22445:                                             $balancetext =  $ruletitles{'default'};
22446:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
22447:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
22448:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
22449:                                                 foreach my $sparetype (@sparestypes) {
22450:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22451:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
22452:                                                     }
22453:                                                 }
22454:                                                 foreach my $item (@{$alltypes}) {
22455:                                                     next if ($item =~  /^_LC_ipchange/);
22456:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
22457:                                                     if ($hasrule eq 'homeserver') {
22458:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
22459:                                                     } else {
22460:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
22461:                                                             if ($servers{$hasrule}) {
22462:                                                                 $toupdate{$hasrule} = 1;
22463:                                                             }
22464:                                                         }
22465:                                                     }
22466:                                                 }
22467:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
22468:                                                     $balancetext =  $ruletitles{$rule};
22469:                                                 } else {
22470:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
22471:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
22472:                                                     if ($receiver) {
22473:                                                         $toupdate{$receiver};
22474:                                                     }
22475:                                                 }
22476:                                             } else {
22477:                                                 $balancetext =  $ruletitles{$rule};
22478:                                             }
22479:                                         } else {
22480:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
22481:                                         }
22482:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
22483:                                     }
22484:                                 }
22485:                             }
22486:                         }
22487:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
22488:                             if ($currcookies{$balancer}) {
22489:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
22490:                                                           $balancer).'</li>';
22491:                             } else {
22492:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
22493:                                                           $balancer).'</li>';
22494:                             }
22495:                         }
22496:                     }
22497:                 }
22498:                 if (keys(%toupdate)) {
22499:                     my %thismachine;
22500:                     my $updatedhere;
22501:                     my $cachetime = 60*60*24;
22502:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
22503:                     foreach my $lonhost (keys(%toupdate)) {
22504:                         if ($thismachine{$lonhost}) {
22505:                             unless ($updatedhere) {
22506:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
22507:                                                               $defaultshash{'loadbalancing'},
22508:                                                               $cachetime);
22509:                                 $updatedhere = 1;
22510:                             }
22511:                         } else {
22512:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
22513:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
22514:                         }
22515:                     }
22516:                 }
22517:                 if ($resulttext ne '') {
22518:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
22519:                 } else {
22520:                     $resulttext = $nochgmsg;
22521:                 }
22522:             } else {
22523:                 $resulttext = $nochgmsg;
22524:             }
22525:         } else {
22526:             $resulttext = '<span class="LC_error">'.
22527:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22528:         }
22529:     } else {
22530:         $resulttext = $nochgmsg;
22531:     }
22532:     return $resulttext;
22533: }
22534: 
22535: sub recurse_check {
22536:     my ($chkcats,$categories,$depth,$name) = @_;
22537:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
22538:         my $chg = 0;
22539:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
22540:             my $category = $chkcats->[$depth]{$name}[$j];
22541:             my $item;
22542:             if ($category eq '') {
22543:                 $chg ++;
22544:             } else {
22545:                 my $deeper = $depth + 1;
22546:                 $item = &escape($category).':'.&escape($name).':'.$depth;
22547:                 if ($chg) {
22548:                     $categories->{$item} -= $chg;
22549:                 }
22550:                 &recurse_check($chkcats,$categories,$deeper,$category);
22551:                 $deeper --;
22552:             }
22553:         }
22554:     }
22555:     return;
22556: }
22557: 
22558: sub recurse_cat_deletes {
22559:     my ($item,$coursecategories,$deletions) = @_;
22560:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
22561:     my $subdepth = $depth + 1;
22562:     if (ref($coursecategories) eq 'HASH') {
22563:         foreach my $subitem (keys(%{$coursecategories})) {
22564:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
22565:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
22566:                 delete($coursecategories->{$subitem});
22567:                 $deletions->{$subitem} = 1;
22568:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
22569:             }
22570:         }
22571:     }
22572:     return;
22573: }
22574: 
22575: sub active_dc_picker {
22576:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
22577:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
22578:     my @domcoord = keys(%domcoords);
22579:     if (keys(%currhash)) {
22580:         foreach my $dc (keys(%currhash)) {
22581:             unless (exists($domcoords{$dc})) {
22582:                 push(@domcoord,$dc);
22583:             }
22584:         }
22585:     }
22586:     @domcoord = sort(@domcoord);
22587:     my $numdcs = scalar(@domcoord);
22588:     my $rows = 0;
22589:     my $table;
22590:     if ($numdcs > 1) {
22591:         $table = '<table>';
22592:         for (my $i=0; $i<@domcoord; $i++) {
22593:             my $rem = $i%($numinrow);
22594:             if ($rem == 0) {
22595:                 if ($i > 0) {
22596:                     $table .= '</tr>';
22597:                 }
22598:                 $table .= '<tr>';
22599:                 $rows ++;
22600:             }
22601:             my $check = '';
22602:             if ($inputtype eq 'radio') {
22603:                 if (keys(%currhash) == 0) {
22604:                     if (!$i) {
22605:                         $check = ' checked="checked"';
22606:                     }
22607:                 } elsif (exists($currhash{$domcoord[$i]})) {
22608:                     $check = ' checked="checked"';
22609:                 }
22610:             } else {
22611:                 if (exists($currhash{$domcoord[$i]})) {
22612:                     $check = ' checked="checked"';
22613:                 }
22614:             }
22615:             if ($i == @domcoord - 1) {
22616:                 my $colsleft = $numinrow - $rem;
22617:                 if ($colsleft > 1) {
22618:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
22619:                 } else {
22620:                     $table .= '<td class="LC_left_item">';
22621:                 }
22622:             } else {
22623:                 $table .= '<td class="LC_left_item">';
22624:             }
22625:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
22626:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
22627:             $table .= '<span class="LC_nobreak"><label>'.
22628:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
22629:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
22630:             if ($user ne $dcname.':'.$dcdom) {
22631:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
22632:             }
22633:             $table .= '</label></span></td>';
22634:         }
22635:         $table .= '</tr></table>';
22636:     } elsif ($numdcs == 1) {
22637:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
22638:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
22639:         if ($inputtype eq 'radio') {
22640:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
22641:             if ($user ne $dcname.':'.$dcdom) {
22642:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
22643:             }
22644:         } else {
22645:             my $check;
22646:             if (exists($currhash{$domcoord[0]})) {
22647:                 $check = ' checked="checked"';
22648:             }
22649:             $table = '<span class="LC_nobreak"><label>'.
22650:                      '<input type="checkbox" name="'.$name.'" '.
22651:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
22652:             if ($user ne $dcname.':'.$dcdom) {
22653:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
22654:             }
22655:             $table .= '</label></span>';
22656:             $rows ++;
22657:         }
22658:     }
22659:     return ($numdcs,$table,$rows);
22660: }
22661: 
22662: sub usersession_titles {
22663:     return &Apache::lonlocal::texthash(
22664:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
22665:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
22666:                spares => 'Servers offloaded to, when busy',
22667:                version => 'LON-CAPA version requirement',
22668:                excludedomain => 'Allow all, but exclude specific domains',
22669:                includedomain => 'Deny all, but include specific domains',
22670:                primary => 'Primary (checked first)',
22671:                default => 'Default',
22672:            );
22673: }
22674: 
22675: sub id_for_thisdom {
22676:     my (%servers) = @_;
22677:     my %altids;
22678:     foreach my $server (keys(%servers)) {
22679:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
22680:         if ($serverhome ne $server) {
22681:             $altids{$serverhome} = $server;
22682:         }
22683:     }
22684:     return %altids;
22685: }
22686: 
22687: sub count_servers {
22688:     my ($currbalancer,%servers) = @_;
22689:     my (@spares,$numspares);
22690:     foreach my $lonhost (sort(keys(%servers))) {
22691:         next if ($currbalancer eq $lonhost);
22692:         push(@spares,$lonhost);
22693:     }
22694:     if ($currbalancer) {
22695:         $numspares = scalar(@spares);
22696:     } else {
22697:         $numspares = scalar(@spares) - 1;
22698:     }
22699:     return ($numspares,@spares);
22700: }
22701: 
22702: sub lonbalance_targets_js {
22703:     my ($dom,$types,$servers,$settings) = @_;
22704:     my $select = &mt('Select');
22705:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
22706:     if (ref($servers) eq 'HASH') {
22707:         $alltargets = join("','",sort(keys(%{$servers})));
22708:         my @homedoms;
22709:         foreach my $server (sort(keys(%{$servers}))) {
22710:             if (&Apache::lonnet::host_domain($server) eq $dom) {
22711:                 push(@homedoms,'1');
22712:             } else {
22713:                 push(@homedoms,'0');
22714:             }
22715:         }
22716:         $allishome = join("','",@homedoms);
22717:     }
22718:     if (ref($types) eq 'ARRAY') {
22719:         if (@{$types} > 0) {
22720:             @alltypes = @{$types};
22721:         }
22722:     }
22723:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
22724:     $allinsttypes = join("','",@alltypes);
22725:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
22726:     if (ref($settings) eq 'HASH') {
22727:         %existing = %{$settings};
22728:     }
22729:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
22730:                               \%currtargets,\%currrules,\%currcookies);
22731:     my $balancers = join("','",sort(keys(%currbalancer)));
22732:     return <<"END";
22733: 
22734: <script type="text/javascript">
22735: // <![CDATA[
22736: 
22737: currBalancers = new Array('$balancers');
22738: 
22739: function toggleTargets(balnum) {
22740:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
22741:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
22742:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
22743:     var prevbalancer = prevhostitem.value;
22744:     var baltotal = document.getElementById('loadbalancing_total').value;
22745:     prevhostitem.value = balancer;
22746:     if (prevbalancer != '') {
22747:         var prevIdx = currBalancers.indexOf(prevbalancer);
22748:         if (prevIdx != -1) {
22749:             currBalancers.splice(prevIdx,1);
22750:         }
22751:     }
22752:     if (balancer == '') {
22753:         hideSpares(balnum);
22754:     } else {
22755:         var currIdx = currBalancers.indexOf(balancer);
22756:         if (currIdx == -1) {
22757:             currBalancers.push(balancer);
22758:         }
22759:         var homedoms = new Array('$allishome');
22760:         var ishomedom = homedoms[lonhostitem.selectedIndex];
22761:         showSpares(balancer,ishomedom,balnum);
22762:     }
22763:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
22764:     return;
22765: }
22766: 
22767: function showSpares(balancer,ishomedom,balnum) {
22768:     var alltargets = new Array('$alltargets');
22769:     var insttypes = new Array('$allinsttypes');
22770:     var offloadtypes = new Array('primary','default');
22771: 
22772:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
22773:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
22774:  
22775:     for (var i=0; i<offloadtypes.length; i++) {
22776:         var count = 0;
22777:         for (var j=0; j<alltargets.length; j++) {
22778:             if (alltargets[j] != balancer) {
22779:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
22780:                 item.value = alltargets[j];
22781:                 item.style.textAlign='left';
22782:                 item.style.textFace='normal';
22783:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
22784:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
22785:                     item.disabled = '';
22786:                 } else {
22787:                     item.disabled = 'disabled';
22788:                     item.checked = false;
22789:                 }
22790:                 count ++;
22791:             }
22792:         }
22793:     }
22794:     for (var k=0; k<insttypes.length; k++) {
22795:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
22796:             if (ishomedom == 1) {
22797:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
22798:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
22799:             } else {
22800:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
22801:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
22802:             }
22803:         } else {
22804:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
22805:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
22806:         }
22807:         if ((insttypes[k] != '_LC_external') && 
22808:             ((insttypes[k] != '_LC_internetdom') ||
22809:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
22810:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
22811:             item.options.length = 0;
22812:             item.options[0] = new Option("","",true,true);
22813:             var idx = 0;
22814:             for (var m=0; m<alltargets.length; m++) {
22815:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
22816:                     idx ++;
22817:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
22818:                 }
22819:             }
22820:         }
22821:     }
22822:     return;
22823: }
22824: 
22825: function hideSpares(balnum) {
22826:     var alltargets = new Array('$alltargets');
22827:     var insttypes = new Array('$allinsttypes');
22828:     var offloadtypes = new Array('primary','default');
22829: 
22830:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
22831:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
22832: 
22833:     var total = alltargets.length - 1;
22834:     for (var i=0; i<offloadtypes; i++) {
22835:         for (var j=0; j<total; j++) {
22836:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
22837:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
22838:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
22839:         }
22840:     }
22841:     for (var k=0; k<insttypes.length; k++) {
22842:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
22843:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
22844:         if (insttypes[k] != '_LC_external') {
22845:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
22846:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
22847:         }
22848:     }
22849:     return;
22850: }
22851: 
22852: function checkOffloads(item,balnum,type) {
22853:     var alltargets = new Array('$alltargets');
22854:     var offloadtypes = new Array('primary','default');
22855:     if (item.checked) {
22856:         var total = alltargets.length - 1;
22857:         var other;
22858:         if (type == offloadtypes[0]) {
22859:             other = offloadtypes[1];
22860:         } else {
22861:             other = offloadtypes[0];
22862:         }
22863:         for (var i=0; i<total; i++) {
22864:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
22865:             if (server == item.value) {
22866:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
22867:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
22868:                 }
22869:             }
22870:         }
22871:     }
22872:     return;
22873: }
22874: 
22875: function singleServerToggle(balnum,type) {
22876:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
22877:     if (offloadtoSelIdx == 0) {
22878:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
22879:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
22880: 
22881:     } else {
22882:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
22883:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
22884:     }
22885:     return;
22886: }
22887: 
22888: function balanceruleChange(formname,balnum,type) {
22889:     if (type == '_LC_external') {
22890:         return;
22891:     }
22892:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
22893:     for (var i=0; i<typesRules.length; i++) {
22894:         if (formname.elements[typesRules[i]].checked) {
22895:             if (formname.elements[typesRules[i]].value != 'specific') {
22896:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
22897:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
22898:             } else {
22899:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
22900:             }
22901:         }
22902:     }
22903:     return;
22904: }
22905: 
22906: function balancerDeleteChange(balnum) {
22907:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
22908:     var baltotal = document.getElementById('loadbalancing_total').value;
22909:     var addtarget;
22910:     var removetarget;
22911:     var action = 'delete';
22912:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
22913:         var lonhost = hostitem.value;
22914:         var currIdx = currBalancers.indexOf(lonhost);
22915:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
22916:             if (currIdx != -1) {
22917:                 currBalancers.splice(currIdx,1);
22918:             }
22919:             addtarget = lonhost;
22920:         } else {
22921:             if (currIdx == -1) {
22922:                 currBalancers.push(lonhost);
22923:             }
22924:             removetarget = lonhost;
22925:             action = 'undelete';
22926:         }
22927:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
22928:     }
22929:     return;
22930: }
22931: 
22932: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
22933:     if (baltotal > 1) {
22934:         var offloadtypes = new Array('primary','default');
22935:         var alltargets = new Array('$alltargets');
22936:         var insttypes = new Array('$allinsttypes');
22937:         for (var i=0; i<baltotal; i++) {
22938:             if (i != balnum) {
22939:                 for (var j=0; j<offloadtypes.length; j++) {
22940:                     var total = alltargets.length - 1;
22941:                     for (var k=0; k<total; k++) {
22942:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
22943:                         var server = serveritem.value;
22944:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
22945:                             if (server == addtarget) {
22946:                                 serveritem.disabled = '';
22947:                             }
22948:                         }
22949:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
22950:                             if (server == removetarget) {
22951:                                 serveritem.disabled = 'disabled';
22952:                                 serveritem.checked = false;
22953:                             }
22954:                         }
22955:                     }
22956:                 }
22957:                 for (var j=0; j<insttypes.length; j++) {
22958:                     if (insttypes[j] != '_LC_external') {
22959:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
22960:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
22961:                             var currSel = singleserver.selectedIndex;
22962:                             var currVal = singleserver.options[currSel].value;
22963:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
22964:                                 var numoptions = singleserver.options.length;
22965:                                 var needsnew = 1;
22966:                                 for (var k=0; k<numoptions; k++) {
22967:                                     if (singleserver.options[k] == addtarget) {
22968:                                         needsnew = 0;
22969:                                         break;
22970:                                     }
22971:                                 }
22972:                                 if (needsnew == 1) {
22973:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
22974:                                 }
22975:                             }
22976:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
22977:                                 singleserver.options.length = 0;
22978:                                 if ((currVal) && (currVal != removetarget)) {
22979:                                     singleserver.options[0] = new Option("","",false,false);
22980:                                 } else {
22981:                                     singleserver.options[0] = new Option("","",true,true);
22982:                                 }
22983:                                 var idx = 0;
22984:                                 for (var m=0; m<alltargets.length; m++) {
22985:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
22986:                                         idx ++;
22987:                                         if (currVal == alltargets[m]) {
22988:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
22989:                                         } else {
22990:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
22991:                                         }
22992:                                     }
22993:                                 }
22994:                             }
22995:                         }
22996:                     }
22997:                 }
22998:             }
22999:         }
23000:     }
23001:     return;
23002: }
23003: 
23004: // ]]>
23005: </script>
23006: 
23007: END
23008: }
23009: 
23010: sub new_spares_js {
23011:     my @sparestypes = ('primary','default');
23012:     my $types = join("','",@sparestypes);
23013:     my $select = &mt('Select');
23014:     return <<"END";
23015: 
23016: <script type="text/javascript">
23017: // <![CDATA[
23018: 
23019: function updateNewSpares(formname,lonhost) {
23020:     var types = new Array('$types');
23021:     var include = new Array();
23022:     var exclude = new Array();
23023:     for (var i=0; i<types.length; i++) {
23024:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
23025:         for (var j=0; j<spareboxes.length; j++) {
23026:             if (formname.elements[spareboxes[j]].checked) {
23027:                 exclude.push(formname.elements[spareboxes[j]].value);
23028:             } else {
23029:                 include.push(formname.elements[spareboxes[j]].value);
23030:             }
23031:         }
23032:     }
23033:     for (var i=0; i<types.length; i++) {
23034:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
23035:         var selIdx = newSpare.selectedIndex;
23036:         var currnew = newSpare.options[selIdx].value;
23037:         var okSpares = new Array();
23038:         for (var j=0; j<newSpare.options.length; j++) {
23039:             var possible = newSpare.options[j].value;
23040:             if (possible != '') {
23041:                 if (exclude.indexOf(possible) == -1) {
23042:                     okSpares.push(possible);
23043:                 } else {
23044:                     if (currnew == possible) {
23045:                         selIdx = 0;
23046:                     }
23047:                 }
23048:             }
23049:         }
23050:         for (var k=0; k<include.length; k++) {
23051:             if (okSpares.indexOf(include[k]) == -1) {
23052:                 okSpares.push(include[k]);
23053:             }
23054:         }
23055:         okSpares.sort();
23056:         newSpare.options.length = 0;
23057:         if (selIdx == 0) {
23058:             newSpare.options[0] = new Option("$select","",true,true);
23059:         } else {
23060:             newSpare.options[0] = new Option("$select","",false,false);
23061:         }
23062:         for (var m=0; m<okSpares.length; m++) {
23063:             var idx = m+1;
23064:             var selThis = 0;
23065:             if (selIdx != 0) {
23066:                 if (okSpares[m] == currnew) {
23067:                     selThis = 1;
23068:                 }
23069:             }
23070:             if (selThis == 1) {
23071:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
23072:             } else {
23073:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
23074:             }
23075:         }
23076:     }
23077:     return;
23078: }
23079: 
23080: function checkNewSpares(lonhost,type) {
23081:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
23082:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
23083:     if (chosen != '') {
23084:         var othertype;
23085:         var othernewSpare;
23086:         if (type == 'primary') {
23087:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
23088:         }
23089:         if (type == 'default') {
23090:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
23091:         }
23092:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
23093:             othernewSpare.selectedIndex = 0;
23094:         }
23095:     }
23096:     return;
23097: }
23098: 
23099: // ]]>
23100: </script>
23101: 
23102: END
23103: 
23104: }
23105: 
23106: sub common_domprefs_js {
23107:     return <<"END";
23108: 
23109: <script type="text/javascript">
23110: // <![CDATA[
23111: 
23112: function getIndicesByName(formname,item) {
23113:     var group = new Array();
23114:     for (var i=0;i<formname.elements.length;i++) {
23115:         if (formname.elements[i].name == item) {
23116:             group.push(formname.elements[i].id);
23117:         }
23118:     }
23119:     return group;
23120: }
23121: 
23122: // ]]>
23123: </script>
23124: 
23125: END
23126: 
23127: }
23128: 
23129: sub recaptcha_js {
23130:     my %lt = &captcha_phrases();
23131:     return <<"END";
23132: 
23133: <script type="text/javascript">
23134: // <![CDATA[
23135: 
23136: function updateCaptcha(caller,context) {
23137:     var privitem;
23138:     var pubitem;
23139:     var privtext;
23140:     var pubtext;
23141:     var versionitem;
23142:     var versiontext;
23143:     if (document.getElementById(context+'_recaptchapub')) {
23144:         pubitem = document.getElementById(context+'_recaptchapub');
23145:     } else {
23146:         return;
23147:     }
23148:     if (document.getElementById(context+'_recaptchapriv')) {
23149:         privitem = document.getElementById(context+'_recaptchapriv');
23150:     } else {
23151:         return;
23152:     }
23153:     if (document.getElementById(context+'_recaptchapubtxt')) {
23154:         pubtext = document.getElementById(context+'_recaptchapubtxt');
23155:     } else {
23156:         return;
23157:     }
23158:     if (document.getElementById(context+'_recaptchaprivtxt')) {
23159:         privtext = document.getElementById(context+'_recaptchaprivtxt');
23160:     } else {
23161:         return;
23162:     }
23163:     if (document.getElementById(context+'_recaptchaversion')) {
23164:         versionitem = document.getElementById(context+'_recaptchaversion');
23165:     } else {
23166:         return;
23167:     }
23168:     if (document.getElementById(context+'_recaptchavertxt')) {
23169:         versiontext = document.getElementById(context+'_recaptchavertxt');
23170:     } else {
23171:         return;
23172:     }
23173:     if (caller.checked) {
23174:         if (caller.value == 'recaptcha') {
23175:             pubitem.type = 'text';
23176:             privitem.type = 'text';
23177:             pubitem.size = '40';
23178:             privitem.size = '40';
23179:             pubtext.innerHTML = "$lt{'pub'}";
23180:             privtext.innerHTML = "$lt{'priv'}";
23181:             versionitem.type = 'text';
23182:             versionitem.size = '3';
23183:             versiontext.innerHTML = "$lt{'ver'}";
23184:         } else {
23185:             pubitem.type = 'hidden';
23186:             privitem.type = 'hidden';
23187:             versionitem.type = 'hidden';
23188:             pubtext.innerHTML = '';
23189:             privtext.innerHTML = '';
23190:             versiontext.innerHTML = '';
23191:         }
23192:     }
23193:     return;
23194: }
23195: 
23196: // ]]>
23197: </script>
23198: 
23199: END
23200: 
23201: }
23202: 
23203: sub toggle_display_js {
23204:     return <<"END";
23205: 
23206: <script type="text/javascript">
23207: // <![CDATA[
23208: 
23209: function toggleDisplay(domForm,caller) {
23210:     if (document.getElementById(caller)) {
23211:         var divitem = document.getElementById(caller);
23212:         var optionsElement = domForm.coursecredits;
23213:         var checkval = 1;
23214:         var dispval = 'block';
23215:         var selfcreateRegExp = /^cancreate_emailverified/;
23216:         if (caller == 'emailoptions') {
23217:             optionsElement = domForm.cancreate_email;
23218:         }
23219:         if (caller == 'studentsubmission') {
23220:             optionsElement = domForm.postsubmit;
23221:         }
23222:         if (caller == 'cloneinstcode') {
23223:             optionsElement = domForm.canclone;
23224:             checkval = 'instcode';
23225:         }
23226:         if (selfcreateRegExp.test(caller)) {
23227:             optionsElement = domForm.elements[caller];
23228:             checkval = 'other';
23229:             dispval = 'inline'
23230:         }
23231:         if (optionsElement.length) {
23232:             var currval;
23233:             for (var i=0; i<optionsElement.length; i++) {
23234:                 if (optionsElement[i].checked) {
23235:                    currval = optionsElement[i].value;
23236:                 }
23237:             }
23238:             if (currval == checkval) {
23239:                 divitem.style.display = dispval;
23240:             } else {
23241:                 divitem.style.display = 'none';
23242:             }
23243:         }
23244:     }
23245:     return;
23246: }
23247: 
23248: // ]]>
23249: </script>
23250: 
23251: END
23252: 
23253: }
23254: 
23255: sub captcha_phrases {
23256:     return &Apache::lonlocal::texthash (
23257:                  priv => 'Private key',
23258:                  pub  => 'Public key',
23259:                  original  => 'original (CAPTCHA)',
23260:                  recaptcha => 'successor (ReCAPTCHA)',
23261:                  notused   => 'unused',
23262:                  ver => 'ReCAPTCHA version (1 or 2)',
23263:     );
23264: }
23265: 
23266: sub devalidate_remote_domconfs {
23267:     my ($dom,$cachekeys) = @_;
23268:     return unless (ref($cachekeys) eq 'HASH');
23269:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
23270:     my %thismachine;
23271:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23272:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
23273:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
23274:                       'ipaccess','trust');
23275:     my %cache_by_lonhost;
23276:     if (exists($cachekeys->{'samllanding'})) {
23277:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
23278:             my %landing = %{$cachekeys->{'samllanding'}};
23279:             my %domservers = &Apache::lonnet::get_servers($dom);
23280:             if (keys(%domservers)) {
23281:                 foreach my $server (keys(%domservers)) {
23282:                     my @cached;
23283:                     next if ($thismachine{$server});
23284:                     if ($landing{$server}) {
23285:                         push(@cached,&escape('samllanding').':'.&escape($server));
23286:                     }
23287:                     if (@cached) {
23288:                         $cache_by_lonhost{$server} = \@cached;
23289:                     }
23290:                 }
23291:             }
23292:         }
23293:     }
23294:     if (keys(%servers)) {
23295:         foreach my $server (keys(%servers)) {
23296:             next if ($thismachine{$server});
23297:             my @cached;
23298:             foreach my $name (@posscached) {
23299:                 if ($cachekeys->{$name}) {
23300:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
23301:                         if (ref($cachekeys->{$name}) eq 'HASH') {
23302:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
23303:                                 push(@cached,&escape($name).':'.&escape($key));
23304:                             }
23305:                         }
23306:                     } else {
23307:                         push(@cached,&escape($name).':'.&escape($dom));
23308:                     }
23309:                 }
23310:             }
23311:             if ((exists($cache_by_lonhost{$server})) &&
23312:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
23313:                 push(@cached,@{$cache_by_lonhost{$server}});
23314:             }
23315:             if (@cached) {
23316:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
23317:             }
23318:         }
23319:     }
23320:     return;
23321: }
23322: 
23323: 1;

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