File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.387: download - view: text, annotated - select for diffs
Mon Sep 27 03:26:24 2021 UTC (2 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Use fully qualified subroutine name.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.387 2021/09/27 03:26:24 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 LONCAPA qw(:DEFAULT :match);
  171: use LONCAPA::Enrollment;
  172: use LONCAPA::lonauthcgi();
  173: use LONCAPA::SSL;
  174: use File::Copy;
  175: use Locale::Language;
  176: use DateTime::TimeZone;
  177: use DateTime::Locale;
  178: use Time::HiRes qw( sleep );
  179: use Net::CIDR;
  180: 
  181: my $registered_cleanup;
  182: my $modified_urls;
  183: 
  184: sub handler {
  185:     my $r=shift;
  186:     if ($r->header_only) {
  187:         &Apache::loncommon::content_type($r,'text/html');
  188:         $r->send_http_header;
  189:         return OK;
  190:     }
  191: 
  192:     my $context = 'domain';
  193:     my $dom = $env{'request.role.domain'};
  194:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  195:     if (&Apache::lonnet::allowed('mau',$dom)) {
  196:         &Apache::loncommon::content_type($r,'text/html');
  197:         $r->send_http_header;
  198:     } else {
  199:         $env{'user.error.msg'}=
  200:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  201:         return HTTP_NOT_ACCEPTABLE;
  202:     }
  203: 
  204:     $registered_cleanup=0;
  205:     @{$modified_urls}=();
  206: 
  207:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  208:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  209:                                             ['phase','actions']);
  210:     my $phase = 'pickactions';
  211:     if ( exists($env{'form.phase'}) ) {
  212:         $phase = $env{'form.phase'};
  213:     }
  214:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  215:     my %domconfig =
  216:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  217:                 'quotas','autoenroll','autoupdate','autocreate',
  218:                 'directorysrch','usercreation','usermodification',
  219:                 'contacts','defaults','scantron','coursecategories',
  220:                 'serverstatuses','requestcourses','helpsettings',
  221:                 'coursedefaults','usersessions','loadbalancing',
  222:                 'requestauthor','selfenrollment','inststatus',
  223:                 'ltitools','ssl','trust','lti','privacy','passwords',
  224:                 'proctoring','wafproxy'],$dom);
  225:     my %encconfig =
  226:         &Apache::lonnet::get_dom('encconfig',['ltitools','lti','proctoring'],$dom,undef,1);
  227:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  228:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  229:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  230:                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
  231:                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
  232:                     foreach my $item ('key','secret') {
  233:                         $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
  234:                     }
  235:                 }
  236:             }
  237:         }
  238:     }
  239:     if (ref($domconfig{'lti'}) eq 'HASH') {
  240:         if (ref($encconfig{'lti'}) eq 'HASH') {
  241:             foreach my $id (keys(%{$domconfig{'lti'}})) {
  242:                 if ((ref($domconfig{'lti'}{$id}) eq 'HASH') &&
  243:                     (ref($encconfig{'lti'}{$id}) eq 'HASH')) {
  244:                     foreach my $item ('key','secret') {
  245:                         $domconfig{'lti'}{$id}{$item} = $encconfig{'lti'}{$id}{$item};
  246:                     }
  247:                 }
  248:             }
  249:         }
  250:     }
  251:     if (ref($domconfig{'proctoring'}) eq 'HASH') {
  252:         if (ref($encconfig{'proctoring'}) eq 'HASH') {
  253:             foreach my $provider (keys(%{$domconfig{'proctoring'}})) {
  254:                 if ((ref($domconfig{'proctoring'}{$provider}) eq 'HASH') &&
  255:                     (ref($encconfig{'proctoring'}{$provider}) eq 'HASH')) {
  256:                     foreach my $item ('key','secret') {
  257:                         $domconfig{'proctoring'}{$provider}{$item} = $encconfig{'proctoring'}{$provider}{$item};
  258:                     }
  259:                 }
  260:             }
  261:         }
  262:     }
  263:     my @prefs_order = ('rolecolors','login','defaults','wafproxy','passwords','quotas',
  264:                        'autoenroll','autoupdate','autocreate','directorysrch',
  265:                        'contacts','privacy','usercreation','selfcreation',
  266:                        'usermodification','scantron','requestcourses','requestauthor',
  267:                        'coursecategories','serverstatuses','helpsettings','coursedefaults',
  268:                        'ltitools','proctoring','selfenrollment','usersessions','ssl',
  269:                        'trust','lti');
  270:     my %existing;
  271:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  272:         %existing = %{$domconfig{'loadbalancing'}};
  273:     }
  274:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  275:         push(@prefs_order,'loadbalancing');
  276:     }
  277:     my %prefs = (
  278:         'rolecolors' =>
  279:                    { text => 'Default color schemes',
  280:                      help => 'Domain_Configuration_Color_Schemes',
  281:                      header => [{col1 => 'Student Settings',
  282:                                  col2 => '',},
  283:                                 {col1 => 'Coordinator Settings',
  284:                                  col2 => '',},
  285:                                 {col1 => 'Author Settings',
  286:                                  col2 => '',},
  287:                                 {col1 => 'Administrator Settings',
  288:                                  col2 => '',}],
  289:                       print => \&print_rolecolors,
  290:                       modify => \&modify_rolecolors,
  291:                     },
  292:         'login' =>
  293:                     { text => 'Log-in page options',
  294:                       help => 'Domain_Configuration_Login_Page',
  295:                       header => [{col1 => 'Log-in Page Items',
  296:                                   col2 => '',},
  297:                                  {col1 => 'Log-in Help',
  298:                                   col2 => 'Value'},
  299:                                  {col1 => 'Custom HTML in document head',
  300:                                   col2 => 'Value'},
  301:                                  {col1 => 'SSO',
  302:                                   col2 => 'Dual login: SSO and non-SSO options'},
  303:                                 ],
  304:                       print => \&print_login,
  305:                       modify => \&modify_login,
  306:                     },
  307:         'defaults' => 
  308:                     { text => 'Default authentication/language/timezone/portal/types',
  309:                       help => 'Domain_Configuration_LangTZAuth',
  310:                       header => [{col1 => 'Setting',
  311:                                   col2 => 'Value'},
  312:                                  {col1 => 'Institutional user types',
  313:                                   col2 => 'Name displayed'}],
  314:                       print => \&print_defaults,
  315:                       modify => \&modify_defaults,
  316:                     },
  317:         'wafproxy' =>
  318:                     { text => 'Web Application Firewall/Reverse Proxy',
  319:                       help => 'Domain_Configuration_WAF_Proxy',
  320:                       header => [{col1 => 'Domain(s)',
  321:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  322:                                  },
  323:                                  {col1 => 'Domain(s)',
  324:                                   col2 => 'WAF Configuration',}],
  325:                       print => \&print_wafproxy,
  326:                       modify => \&modify_wafproxy,
  327:                     },
  328:         'passwords' =>
  329:                     { text => 'Passwords (Internal authentication)',
  330:                       help => 'Domain_Configuration_Passwords',
  331:                       header => [{col1 => 'Resetting Forgotten Password',
  332:                                   col2 => 'Settings'},
  333:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  334:                                   col2 => 'Settings'},
  335:                                  {col1 => 'Rules for LON-CAPA Passwords',
  336:                                   col2 => 'Settings'},
  337:                                  {col1 => 'Course Owner Changing Student Passwords',
  338:                                   col2 => 'Settings'}],
  339:                       print => \&print_passwords,
  340:                       modify => \&modify_passwords,
  341:                     },
  342:         'quotas' => 
  343:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  344:                       help => 'Domain_Configuration_Quotas',
  345:                       header => [{col1 => 'User affiliation',
  346:                                   col2 => 'Available tools',
  347:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  348:                       print => \&print_quotas,
  349:                       modify => \&modify_quotas,
  350:                     },
  351:         'autoenroll' =>
  352:                    { text => 'Auto-enrollment settings',
  353:                      help => 'Domain_Configuration_Auto_Enrollment',
  354:                      header => [{col1 => 'Configuration setting',
  355:                                  col2 => 'Value(s)'}],
  356:                      print => \&print_autoenroll,
  357:                      modify => \&modify_autoenroll,
  358:                    },
  359:         'autoupdate' => 
  360:                    { text => 'Auto-update settings',
  361:                      help => 'Domain_Configuration_Auto_Updates',
  362:                      header => [{col1 => 'Setting',
  363:                                  col2 => 'Value',},
  364:                                 {col1 => 'Setting',
  365:                                  col2 => 'Affiliation'},
  366:                                 {col1 => 'User population',
  367:                                  col2 => 'Updatable user data'}],
  368:                      print => \&print_autoupdate,
  369:                      modify => \&modify_autoupdate,
  370:                   },
  371:         'autocreate' => 
  372:                   { text => 'Auto-course creation settings',
  373:                      help => 'Domain_Configuration_Auto_Creation',
  374:                      header => [{col1 => 'Configuration Setting',
  375:                                  col2 => 'Value',}],
  376:                      print => \&print_autocreate,
  377:                      modify => \&modify_autocreate,
  378:                   },
  379:         'directorysrch' => 
  380:                   { text => 'Directory searches',
  381:                     help => 'Domain_Configuration_InstDirectory_Search',
  382:                     header => [{col1 => 'Institutional Directory Setting',
  383:                                 col2 => 'Value',},
  384:                                {col1 => 'LON-CAPA Directory Setting',
  385:                                 col2 => 'Value',}],
  386:                     print => \&print_directorysrch,
  387:                     modify => \&modify_directorysrch,
  388:                   },
  389:         'contacts' =>
  390:                   { text => 'E-mail addresses and helpform',
  391:                     help => 'Domain_Configuration_Contact_Info',
  392:                     header => [{col1 => 'Default e-mail addresses',
  393:                                 col2 => 'Value',},
  394:                                {col1 => 'Recipient(s) for notifications',
  395:                                 col2 => 'Value',},
  396:                                {col1 => 'Nightly status check e-mail',
  397:                                 col2 => 'Settings',},
  398:                                {col1 => 'Ask helpdesk form settings',
  399:                                 col2 => 'Value',},],
  400:                     print => \&print_contacts,
  401:                     modify => \&modify_contacts,
  402:                   },
  403:         'usercreation' => 
  404:                   { text => 'User creation',
  405:                     help => 'Domain_Configuration_User_Creation',
  406:                     header => [{col1 => 'Format rule type',
  407:                                 col2 => 'Format rules in force'},
  408:                                {col1 => 'User account creation',
  409:                                 col2 => 'Usernames which may be created',},
  410:                                {col1 => 'Context',
  411:                                 col2 => 'Assignable authentication types'}],
  412:                     print => \&print_usercreation,
  413:                     modify => \&modify_usercreation,
  414:                   },
  415:         'selfcreation' => 
  416:                   { text => 'Users self-creating accounts',
  417:                     help => 'Domain_Configuration_Self_Creation', 
  418:                     header => [{col1 => 'Self-creation with institutional username',
  419:                                 col2 => 'Enabled?'},
  420:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  421:                                 col2 => 'Information user can enter'},
  422:                                {col1 => 'Self-creation with e-mail verification',
  423:                                 col2 => 'Settings'}],
  424:                     print => \&print_selfcreation,
  425:                     modify => \&modify_selfcreation,
  426:                   },
  427:         'usermodification' =>
  428:                   { text => 'User modification',
  429:                     help => 'Domain_Configuration_User_Modification',
  430:                     header => [{col1 => 'Target user has role',
  431:                                 col2 => 'User information updatable in author context'},
  432:                                {col1 => 'Target user has role',
  433:                                 col2 => 'User information updatable in course context'}],
  434:                     print => \&print_usermodification,
  435:                     modify => \&modify_usermodification,
  436:                   },
  437:         'scantron' =>
  438:                   { text => 'Bubblesheet format',
  439:                     help => 'Domain_Configuration_Scantron_Format',
  440:                     header => [ {col1 => 'Bubblesheet format file',
  441:                                  col2 => ''},
  442:                                 {col1 => 'Bubblesheet data upload formats',
  443:                                  col2 => 'Settings'}],
  444:                     print => \&print_scantron,
  445:                     modify => \&modify_scantron,
  446:                   },
  447:         'requestcourses' => 
  448:                  {text => 'Request creation of courses',
  449:                   help => 'Domain_Configuration_Request_Courses',
  450:                   header => [{col1 => 'User affiliation',
  451:                               col2 => 'Availability/Processing of requests',},
  452:                              {col1 => 'Setting',
  453:                               col2 => 'Value'},
  454:                              {col1 => 'Available textbooks',
  455:                               col2 => ''},
  456:                              {col1 => 'Available templates',
  457:                               col2 => ''},
  458:                              {col1 => 'Validation (not official courses)',
  459:                               col2 => 'Value'},],
  460:                   print => \&print_quotas,
  461:                   modify => \&modify_quotas,
  462:                  },
  463:         'requestauthor' =>
  464:                  {text => 'Request Authoring Space',
  465:                   help => 'Domain_Configuration_Request_Author',
  466:                   header => [{col1 => 'User affiliation',
  467:                               col2 => 'Availability/Processing of requests',},
  468:                              {col1 => 'Setting',
  469:                               col2 => 'Value'}],
  470:                   print => \&print_quotas,
  471:                   modify => \&modify_quotas,
  472:                  },
  473:         'coursecategories' =>
  474:                   { text => 'Cataloging of courses/communities',
  475:                     help => 'Domain_Configuration_Cataloging_Courses',
  476:                     header => [{col1 => 'Catalog type/availability',
  477:                                 col2 => '',},
  478:                                {col1 => 'Category settings for standard catalog',
  479:                                 col2 => '',},
  480:                                {col1 => 'Categories',
  481:                                 col2 => '',
  482:                                }],
  483:                     print => \&print_coursecategories,
  484:                     modify => \&modify_coursecategories,
  485:                   },
  486:         'serverstatuses' =>
  487:                  {text   => 'Access to server status pages',
  488:                   help   => 'Domain_Configuration_Server_Status',
  489:                   header => [{col1 => 'Status Page',
  490:                               col2 => 'Other named users',
  491:                               col3 => 'Specific IPs',
  492:                             }],
  493:                   print => \&print_serverstatuses,
  494:                   modify => \&modify_serverstatuses,
  495:                  },
  496:         'helpsettings' =>
  497:                  {text   => 'Support settings',
  498:                   help   => 'Domain_Configuration_Help_Settings',
  499:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  500:                               col2 => 'Value'},
  501:                              {col1 => 'Helpdesk Roles',
  502:                               col2 => 'Settings'},],
  503:                   print  => \&print_helpsettings,
  504:                   modify => \&modify_helpsettings,
  505:                  },
  506:         'coursedefaults' => 
  507:                  {text => 'Course/Community defaults',
  508:                   help => 'Domain_Configuration_Course_Defaults',
  509:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  510:                               col2 => 'Value',},
  511:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  512:                               col2 => 'Value',},],
  513:                   print => \&print_coursedefaults,
  514:                   modify => \&modify_coursedefaults,
  515:                  },
  516:         'selfenrollment' => 
  517:                  {text   => 'Self-enrollment in Course/Community',
  518:                   help   => 'Domain_Configuration_Selfenrollment',
  519:                   header => [{col1 => 'Configuration Rights',
  520:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  521:                              {col1 => 'Defaults',
  522:                               col2 => 'Value'},
  523:                              {col1 => 'Self-enrollment validation (optional)',
  524:                               col2 => 'Value'},],
  525:                   print => \&print_selfenrollment,
  526:                   modify => \&modify_selfenrollment,
  527:                  },
  528:         'privacy' => 
  529:                  {text   => 'Availability of User Information',
  530:                   help   => 'Domain_Configuration_User_Privacy',
  531:                   header => [{col1 => 'Role assigned in different domain',
  532:                               col2 => 'Approval options'},
  533:                              {col1 => 'Role assigned in different domain to user of type',
  534:                               col2 => 'User information available in that domain'},
  535:                              {col1 => "Role assigned in user's domain",
  536:                               col2 => 'Information viewable by privileged user'},
  537:                              {col1 => "Role assigned in user's domain",
  538:                               col2 => 'Information viewable by unprivileged user'}],
  539:                   print => \&print_privacy,
  540:                   modify => \&modify_privacy,
  541:                  },
  542:         'usersessions' =>
  543:                  {text  => 'User session hosting/offloading',
  544:                   help  => 'Domain_Configuration_User_Sessions',
  545:                   header => [{col1 => 'Domain server',
  546:                               col2 => 'Servers to offload sessions to when busy'},
  547:                              {col1 => 'Hosting of users from other domains',
  548:                               col2 => 'Rules'},
  549:                              {col1 => "Hosting domain's own users elsewhere",
  550:                               col2 => 'Rules'}],
  551:                   print => \&print_usersessions,
  552:                   modify => \&modify_usersessions,
  553:                  },
  554:         'loadbalancing' =>
  555:                  {text  => 'Dedicated Load Balancer(s)',
  556:                   help  => 'Domain_Configuration_Load_Balancing',
  557:                   header => [{col1 => 'Balancers',
  558:                               col2 => 'Default destinations',
  559:                               col3 => 'User affiliation',
  560:                               col4 => 'Overrides'},
  561:                             ],
  562:                   print => \&print_loadbalancing,
  563:                   modify => \&modify_loadbalancing,
  564:                  },
  565:         'ltitools' => 
  566:                  {text => 'External Tools (LTI)',
  567:                   help => 'Domain_Configuration_LTI_Tools',
  568:                   header => [{col1 => 'Setting',
  569:                               col2 => 'Value',}],
  570:                   print => \&print_ltitools,
  571:                   modify => \&modify_ltitools,
  572:                  },
  573:         'proctoring' =>
  574:                  {text => 'Remote Proctoring Integration',
  575:                   help => 'Domain_Configuration_Proctoring',
  576:                   header => [{col1 => 'Name',
  577:                               col2 => 'Configuration'}],
  578:                   print => \&print_proctoring,
  579:                   modify => \&modify_proctoring,
  580:                  },
  581:         'ssl' =>
  582:                  {text  => 'LON-CAPA Network (SSL)',
  583:                   help  => 'Domain_Configuration_Network_SSL',
  584:                   header => [{col1 => 'Server',
  585:                               col2 => 'Certificate Status'},
  586:                              {col1 => 'Connections to other servers',
  587:                               col2 => 'Rules'},
  588:                              {col1 => 'Connections from other servers',
  589:                               col2 => 'Rules'},
  590:                              {col1 => "Replicating domain's published content",
  591:                               col2 => 'Rules'}],
  592:                   print => \&print_ssl,
  593:                   modify => \&modify_ssl,
  594:                  },
  595:         'trust' =>
  596:                  {text   => 'Trust Settings',
  597:                   help   => 'Domain_Configuration_Trust',
  598:                   header => [{col1 => "Access to this domain's content by others",
  599:                               col2 => 'Rules'},
  600:                              {col1 => "Access to other domain's content by this domain",
  601:                               col2 => 'Rules'},
  602:                              {col1 => "Enrollment in this domain's courses by others",
  603:                               col2 => 'Rules',},
  604:                              {col1 => "Co-author roles in this domain for others",
  605:                               col2 => 'Rules',},
  606:                              {col1 => "Co-author roles for this domain's users elsewhere",
  607:                               col2 => 'Rules',},
  608:                              {col1 => "Domain roles in this domain assignable to others",
  609:                               col2 => 'Rules'},
  610:                              {col1 => "Course catalog for this domain displayed elsewhere",
  611:                               col2 => 'Rules'},
  612:                              {col1 => "Requests for creation of courses in this domain by others",
  613:                               col2 => 'Rules'},
  614:                              {col1 => "Users in other domains can send messages to this domain",
  615:                               col2 => 'Rules'},],
  616:                   print => \&print_trust,
  617:                   modify => \&modify_trust,
  618:                  },
  619:           'lti' =>
  620:                  {text => 'LTI Provider',
  621:                   help => 'Domain_Configuration_LTI_Provider',
  622:                   header => [{col1 => 'Setting',
  623:                               col2 => 'Value',}],
  624:                   print => \&print_lti,
  625:                   modify => \&modify_lti,
  626:                  },
  627:     );
  628:     if (keys(%servers) > 1) {
  629:         $prefs{'login'}  = { text   => 'Log-in page options',
  630:                              help   => 'Domain_Configuration_Login_Page',
  631:                             header => [{col1 => 'Log-in Service',
  632:                                         col2 => 'Server Setting',},
  633:                                        {col1 => 'Log-in Page Items',
  634:                                         col2 => ''},
  635:                                        {col1 => 'Log-in Help',
  636:                                         col2 => 'Value'},
  637:                                        {col1 => 'Custom HTML in document head',
  638:                                         col2 => 'Value'},
  639:                                        {col1 => 'SSO',
  640:                                         col2 => 'Dual login: SSO and non-SSO options'},
  641:                                       ],
  642:                             print => \&print_login,
  643:                             modify => \&modify_login,
  644:                            };
  645:     }
  646: 
  647:     my @roles = ('student','coordinator','author','admin');
  648:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  649:     &Apache::lonhtmlcommon::add_breadcrumb
  650:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  651:       text=>"Settings to display/modify"});
  652:     my $confname = $dom.'-domainconfig';
  653: 
  654:     if ($phase eq 'process') {
  655:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  656:                                                               \%prefs,\%domconfig,$confname,\@roles);
  657:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  658:             $r->rflush();
  659:             &devalidate_remote_domconfs($dom,$result);
  660:         }
  661:     } elsif ($phase eq 'display') {
  662:         my $js = &recaptcha_js().
  663:                  &toggle_display_js();
  664:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  665:             my ($othertitle,$usertypes,$types) =
  666:                 &Apache::loncommon::sorted_inst_types($dom);
  667:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  668:                                           $domconfig{'loadbalancing'}).
  669:                    &new_spares_js().
  670:                    &common_domprefs_js().
  671:                    &Apache::loncommon::javascript_array_indexof();
  672:         }
  673:         if (grep(/^requestcourses$/,@actions)) {
  674:             my $javascript_validations;
  675:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  676:             $js .= <<END;
  677: <script type="text/javascript">
  678: $javascript_validations
  679: </script>
  680: $coursebrowserjs
  681: END
  682:         }
  683:         if (grep(/^selfcreation$/,@actions)) {
  684:             $js .= &selfcreate_javascript();
  685:         }
  686:         if (grep(/^contacts$/,@actions)) {
  687:             $js .= &contacts_javascript();
  688:         }
  689:         if (grep(/^scantron$/,@actions)) {
  690:             $js .= &scantron_javascript();
  691:         }
  692:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  693:     } else {
  694: # check if domconfig user exists for the domain.
  695:         my $servadm = $r->dir_config('lonAdmEMail');
  696:         my ($configuserok,$author_ok,$switchserver) =
  697:             &config_check($dom,$confname,$servadm);
  698:         unless ($configuserok eq 'ok') {
  699:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  700:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  701:                           $confname).
  702:                       '<br />'
  703:             );
  704:             if ($switchserver) {
  705:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  706:                           '<br />'.
  707:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  708:                           '<br />'.
  709:                           &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).
  710:                           '<br />'.
  711:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  712:                 );
  713:             } else {
  714:                 $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.').
  715:                           '<br />'.
  716:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  717:                 );
  718:             }
  719:             $r->print(&Apache::loncommon::end_page());
  720:             return OK;
  721:         }
  722:         if (keys(%domconfig) == 0) {
  723:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  724:             my @ids=&Apache::lonnet::current_machine_ids();
  725:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  726:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  727:                 my @loginimages = ('img','logo','domlogo','login');
  728:                 my $custom_img_count = 0;
  729:                 foreach my $img (@loginimages) {
  730:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  731:                         $custom_img_count ++;
  732:                     }
  733:                 }
  734:                 foreach my $role (@roles) {
  735:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  736:                         $custom_img_count ++;
  737:                     }
  738:                 }
  739:                 if ($custom_img_count > 0) {
  740:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  741:                     my $switch_server = &check_switchserver($dom,$confname);
  742:                     $r->print(
  743:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  744:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  745:     &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 />'.
  746:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  747:                     if ($switch_server) {
  748:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  749:                     }
  750:                     $r->print(&Apache::loncommon::end_page());
  751:                     return OK;
  752:                 }
  753:             }
  754:         }
  755:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  756:     }
  757:     return OK;
  758: }
  759: 
  760: sub process_changes {
  761:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  762:     my %domconfig;
  763:     if (ref($values) eq 'HASH') {
  764:         %domconfig = %{$values};
  765:     }
  766:     my $output;
  767:     if ($action eq 'login') {
  768:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  769:     } elsif ($action eq 'rolecolors') {
  770:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  771:                                      $lastactref,%domconfig);
  772:     } elsif ($action eq 'quotas') {
  773:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  774:     } elsif ($action eq 'autoenroll') {
  775:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  776:     } elsif ($action eq 'autoupdate') {
  777:         $output = &modify_autoupdate($dom,%domconfig);
  778:     } elsif ($action eq 'autocreate') {
  779:         $output = &modify_autocreate($dom,%domconfig);
  780:     } elsif ($action eq 'directorysrch') {
  781:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  782:     } elsif ($action eq 'usercreation') {
  783:         $output = &modify_usercreation($dom,%domconfig);
  784:     } elsif ($action eq 'selfcreation') {
  785:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  786:     } elsif ($action eq 'usermodification') {
  787:         $output = &modify_usermodification($dom,%domconfig);
  788:     } elsif ($action eq 'contacts') {
  789:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  790:     } elsif ($action eq 'defaults') {
  791:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  792:     } elsif ($action eq 'scantron') {
  793:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  794:     } elsif ($action eq 'coursecategories') {
  795:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  796:     } elsif ($action eq 'serverstatuses') {
  797:         $output = &modify_serverstatuses($dom,%domconfig);
  798:     } elsif ($action eq 'requestcourses') {
  799:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  800:     } elsif ($action eq 'requestauthor') {
  801:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  802:     } elsif ($action eq 'helpsettings') {
  803:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  804:     } elsif ($action eq 'coursedefaults') {
  805:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  806:     } elsif ($action eq 'selfenrollment') {
  807:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  808:     } elsif ($action eq 'usersessions') {
  809:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  810:     } elsif ($action eq 'loadbalancing') {
  811:         $output = &modify_loadbalancing($dom,%domconfig);
  812:     } elsif ($action eq 'ltitools') {
  813:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  814:     } elsif ($action eq 'proctoring') {
  815:         $output = &modify_proctoring($r,$dom,$action,$lastactref,%domconfig);
  816:     } elsif ($action eq 'ssl') {
  817:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  818:     } elsif ($action eq 'trust') {
  819:         $output = &modify_trust($dom,$lastactref,%domconfig);
  820:     } elsif ($action eq 'lti') {
  821:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  822:     } elsif ($action eq 'privacy') {
  823:         $output = &modify_privacy($dom,%domconfig);
  824:     } elsif ($action eq 'passwords') {
  825:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  826:     } elsif ($action eq 'wafproxy') {
  827:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  828:     }
  829:     return $output;
  830: }
  831: 
  832: sub print_config_box {
  833:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  834:     my $rowtotal = 0;
  835:     my $output;
  836:     if ($action eq 'coursecategories') {
  837:         $output = &coursecategories_javascript($settings);
  838:     } elsif ($action eq 'defaults') {
  839:         $output = &defaults_javascript($settings); 
  840:     } elsif ($action eq 'passwords') {
  841:         $output = &passwords_javascript();
  842:     } elsif ($action eq 'helpsettings') {
  843:         my (%privs,%levelscurrent);
  844:         my %full=();
  845:         my %levels=(
  846:                      course => {},
  847:                      domain => {},
  848:                      system => {},
  849:                    );
  850:         my $context = 'domain';
  851:         my $crstype = 'Course';
  852:         my $formname = 'display';
  853:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  854:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  855:         $output =
  856:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  857:                                                       \@templateroles);
  858:     } elsif ($action eq 'ltitools') {
  859:         $output .= &ltitools_javascript($settings);
  860:     } elsif ($action eq 'lti') {
  861:         $output .= &lti_javascript($settings);
  862:     } elsif ($action eq 'proctoring') {
  863:         $output .= &proctoring_javascript($settings);
  864:     } elsif ($action eq 'wafproxy') {
  865:         $output .= &wafproxy_javascript($dom);
  866:     } elsif ($action eq 'autoupdate') {
  867:         $output .= &autoupdate_javascript();
  868:     } elsif ($action eq 'login') {
  869:         $output .= &saml_javascript();
  870:     }
  871:     $output .=
  872:          '<table class="LC_nested_outer">
  873:           <tr>
  874:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  875:            &mt($item->{text}).'&nbsp;'.
  876:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  877:           '</tr>';
  878:     $rowtotal ++;
  879:     my $numheaders = 1;
  880:     if (ref($item->{'header'}) eq 'ARRAY') {
  881:         $numheaders = scalar(@{$item->{'header'}});
  882:     }
  883:     if ($numheaders > 1) {
  884:         my $colspan = '';
  885:         my $rightcolspan = '';
  886:         my $leftnobr = '';
  887:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  888:             ($action eq 'directorysrch') ||
  889:             (($action eq 'login') && ($numheaders < 5))) {
  890:             $colspan = ' colspan="2"';
  891:         }
  892:         if ($action eq 'usersessions') {
  893:             $rightcolspan = ' colspan="3"'; 
  894:         }
  895:         if ($action eq 'passwords') {
  896:             $leftnobr = ' LC_nobreak';
  897:         }
  898:         $output .= '
  899:           <tr>
  900:            <td>
  901:             <table class="LC_nested">
  902:              <tr class="LC_info_row">
  903:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  904:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  905:              </tr>';
  906:         $rowtotal ++;
  907:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  908:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  909:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  910:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  911:             ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy')) {
  912:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  913:         } elsif ($action eq 'passwords') {
  914:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  915:         } elsif ($action eq 'coursecategories') {
  916:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  917:         } elsif ($action eq 'scantron') {
  918:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  919:         } elsif ($action eq 'login') {
  920:             if ($numheaders == 5) {
  921:                 $colspan = ' colspan="2"';
  922:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  923:             } else {
  924:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  925:             }
  926:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  927:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  928:         } elsif ($action eq 'rolecolors') {
  929:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  930:         }
  931:         $output .= '
  932:            </table>
  933:           </td>
  934:          </tr>
  935:          <tr>
  936:            <td>
  937:             <table class="LC_nested">
  938:              <tr class="LC_info_row">
  939:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  940:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  941:              </tr>';
  942:             $rowtotal ++;
  943:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  944:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  945:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  946:             ($action eq 'trust') || ($action eq 'contacts') ||
  947:             ($action eq 'privacy') || ($action eq 'passwords')) {
  948:             if ($action eq 'coursecategories') {
  949:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  950:                 $colspan = ' colspan="2"';
  951:             } elsif ($action eq 'trust') {
  952:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  953:             } elsif ($action eq 'passwords') {
  954:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  955:             } else {
  956:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  957:             }
  958:             if ($action eq 'trust') {
  959:                 $output .= '
  960:             </table>
  961:           </td>
  962:          </tr>';
  963:                 my @trusthdrs = qw(2 3 4 5 6 7);
  964:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
  965:                 for (my $i=0; $i<@trusthdrs; $i++) {
  966:                     $output .= '
  967:          <tr>
  968:            <td>
  969:             <table class="LC_nested">
  970:              <tr class="LC_info_row">
  971:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
  972:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
  973:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
  974:             </table>
  975:           </td>
  976:          </tr>';
  977:                 }
  978:                 $output .= '
  979:          <tr>
  980:            <td>
  981:             <table class="LC_nested">
  982:              <tr class="LC_info_row">
  983:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
  984:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
  985:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  986:             } else {
  987:                 $output .= '
  988:            </table>
  989:           </td>
  990:          </tr>
  991:          <tr>
  992:            <td>
  993:             <table class="LC_nested">
  994:              <tr class="LC_info_row">
  995:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  996:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  997:              </tr>'."\n";
  998:                 if ($action eq 'coursecategories') {
  999:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
 1000:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'passwords')) {
 1001:                     if ($action eq 'passwords') {
 1002:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
 1003:                     } else {
 1004:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
 1005:                     }
 1006:                     $output .= '
 1007:              </tr>
 1008:             </table>
 1009:            </td>
 1010:           </tr>
 1011:           <tr>
 1012:            <td>
 1013:             <table class="LC_nested">
 1014:              <tr class="LC_info_row">
 1015:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1016:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
 1017:                     if ($action eq 'passwords') {
 1018:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
 1019:                     } else {
 1020:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1021:                     }
 1022:                     $output .= '
 1023:             </table>
 1024:           </td>
 1025:          </tr>
 1026:          <tr>';
 1027:                 } else {
 1028:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1029:                 }
 1030:             }
 1031:             $rowtotal ++;
 1032:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
 1033:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
 1034:                  ($action eq 'helpsettings') || ($action eq 'wafproxy')) {
 1035:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1036:         } elsif ($action eq 'scantron') {
 1037:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
 1038:         } elsif ($action eq 'ssl') {
 1039:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
 1040:             </table>
 1041:           </td>
 1042:          </tr>
 1043:          <tr>
 1044:            <td>
 1045:             <table class="LC_nested">
 1046:              <tr class="LC_info_row">
 1047:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1048:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1049:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
 1050:             </table>
 1051:           </td>
 1052:          </tr>
 1053:          <tr>
 1054:            <td>
 1055:             <table class="LC_nested">
 1056:              <tr class="LC_info_row">
 1057:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1058:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1059:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1060:         } elsif ($action eq 'login') {
 1061:             if ($numheaders == 5) {
 1062:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1063:            </table>
 1064:           </td>
 1065:          </tr>
 1066:          <tr>
 1067:            <td>
 1068:             <table class="LC_nested">
 1069:              <tr class="LC_info_row">
 1070:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1071:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1072:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1073:                 $rowtotal ++;
 1074:             } else {
 1075:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1076:             }
 1077:             $output .= '
 1078:            </table>
 1079:           </td>
 1080:          </tr>
 1081:          <tr>
 1082:            <td>
 1083:             <table class="LC_nested">
 1084:              <tr class="LC_info_row">';
 1085:             if ($numheaders == 5) {
 1086:                 $output .= '
 1087:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1088:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1089:              </tr>';
 1090:             } else {
 1091:                 $output .= '
 1092:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1093:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1094:              </tr>';
 1095:             }
 1096:             $rowtotal ++;
 1097:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
 1098:            </table>
 1099:           </td>
 1100:          </tr>
 1101:          <tr>
 1102:            <td>
 1103:             <table class="LC_nested">
 1104:              <tr class="LC_info_row">';
 1105:             if ($numheaders == 5) {
 1106:                 $output .= '
 1107:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1108:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1109:              </tr>';
 1110:             } else {
 1111:                 $output .= '
 1112:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1113:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1114:              </tr>';
 1115:             }
 1116:             $rowtotal ++;
 1117:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1118:         } elsif ($action eq 'requestcourses') {
 1119:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1120:             $rowtotal ++;
 1121:             $output .= &print_studentcode($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'}->[2]->{'col1'}).'</td>
 1130:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1131:                        &textbookcourses_javascript($settings).
 1132:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1133:             </table>
 1134:            </td>
 1135:           </tr>
 1136:          <tr>
 1137:            <td>
 1138:             <table class="LC_nested">
 1139:              <tr class="LC_info_row">
 1140:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1141:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1142:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1143:             </table>
 1144:            </td>
 1145:           </tr>
 1146:           <tr>
 1147:            <td>
 1148:             <table class="LC_nested">
 1149:              <tr class="LC_info_row">
 1150:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1151:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1152:              </tr>'.
 1153:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1154:         } elsif ($action eq 'requestauthor') {
 1155:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1156:             $rowtotal ++;
 1157:         } elsif ($action eq 'rolecolors') {
 1158:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1159:            </table>
 1160:           </td>
 1161:          </tr>
 1162:          <tr>
 1163:            <td>
 1164:             <table class="LC_nested">
 1165:              <tr class="LC_info_row">
 1166:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1167:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1168:               <td class="LC_right_item" style="vertical-align: top">'.
 1169:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1170:              </tr>'.
 1171:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1172:            </table>
 1173:           </td>
 1174:          </tr>
 1175:          <tr>
 1176:            <td>
 1177:             <table class="LC_nested">
 1178:              <tr class="LC_info_row">
 1179:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1180:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1181:              </tr>'.
 1182:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1183:             $rowtotal += 2;
 1184:         }
 1185:     } else {
 1186:         $output .= '
 1187:           <tr>
 1188:            <td>
 1189:             <table class="LC_nested">
 1190:              <tr class="LC_info_row">';
 1191:         if ($action eq 'login') {
 1192:             $output .= '  
 1193:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1194:         } elsif ($action eq 'serverstatuses') {
 1195:             $output .= '
 1196:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1197:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1198: 
 1199:         } else {
 1200:             $output .= '
 1201:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1202:         }
 1203:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1204:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1205:                        &mt($item->{'header'}->[0]->{'col2'});
 1206:             if ($action eq 'serverstatuses') {
 1207:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1208:             } 
 1209:         } else {
 1210:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1211:                        &mt($item->{'header'}->[0]->{'col2'});
 1212:         }
 1213:         $output .= '</td>';
 1214:         if ($item->{'header'}->[0]->{'col3'}) {
 1215:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1216:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1217:                             &mt($item->{'header'}->[0]->{'col3'});
 1218:             } else {
 1219:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1220:                            &mt($item->{'header'}->[0]->{'col3'});
 1221:             }
 1222:             if ($action eq 'serverstatuses') {
 1223:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1224:             }
 1225:             $output .= '</td>';
 1226:         }
 1227:         if ($item->{'header'}->[0]->{'col4'}) {
 1228:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1229:                        &mt($item->{'header'}->[0]->{'col4'});
 1230:         }
 1231:         $output .= '</tr>';
 1232:         $rowtotal ++;
 1233:         if ($action eq 'quotas') {
 1234:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1235:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1236:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1237:                  ($action eq 'ltitools') || ($action eq 'lti') ||
 1238:                  ($action eq 'proctoring')) {
 1239:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1240:         }
 1241:     }
 1242:     $output .= '
 1243:    </table>
 1244:   </td>
 1245:  </tr>
 1246: </table><br />';
 1247:     return ($output,$rowtotal);
 1248: }
 1249: 
 1250: sub print_login {
 1251:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1252:     my ($css_class,$datatable,$switchserver,%lt);
 1253:     my %choices = &login_choices();
 1254:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1255:         %lt = &login_file_options();
 1256:         $switchserver = &check_switchserver($dom,$confname);
 1257:     }
 1258:     if ($caller eq 'service') {
 1259:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1260:         my $choice = $choices{'disallowlogin'};
 1261:         $css_class = ' class="LC_odd_row"';
 1262:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1263:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1264:                       '<th>'.$choices{'server'}.'</th>'.
 1265:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1266:                       '<th>'.$choices{'custompath'}.'</th>'.
 1267:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1268:         my %disallowed;
 1269:         if (ref($settings) eq 'HASH') {
 1270:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1271:                %disallowed = %{$settings->{'loginvia'}};
 1272:             }
 1273:         }
 1274:         foreach my $lonhost (sort(keys(%servers))) {
 1275:             my $direct = 'selected="selected"';
 1276:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1277:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1278:                     $direct = '';
 1279:                 }
 1280:             }
 1281:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1282:                           '<td><select name="'.$lonhost.'_server">'.
 1283:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1284:                           '</option>';
 1285:             foreach my $hostid (sort(keys(%servers))) {
 1286:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1287:                 my $selected = '';
 1288:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1289:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1290:                         $selected = 'selected="selected"';
 1291:                     }
 1292:                 }
 1293:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1294:                               $servers{$hostid}.'</option>';
 1295:             }
 1296:             $datatable .= '</select></td>'.
 1297:                           '<td><select name="'.$lonhost.'_serverpath">';
 1298:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1299:                 my $pathname = $path;
 1300:                 if ($path eq 'custom') {
 1301:                     $pathname = &mt('Custom Path').' ->';
 1302:                 }
 1303:                 my $selected = '';
 1304:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1305:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1306:                         $selected = 'selected="selected"';
 1307:                     }
 1308:                 } elsif ($path eq '') {
 1309:                     $selected = 'selected="selected"';
 1310:                 }
 1311:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1312:             }
 1313:             $datatable .= '</select></td>';
 1314:             my ($custom,$exempt);
 1315:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1316:                 $custom = $disallowed{$lonhost}{'custompath'};
 1317:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1318:             }
 1319:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1320:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1321:                           '</tr>';
 1322:         }
 1323:         $datatable .= '</table></td></tr>';
 1324:         return $datatable;
 1325:     } elsif ($caller eq 'page') {
 1326:         my %defaultchecked = ( 
 1327:                                'coursecatalog' => 'on',
 1328:                                'helpdesk'      => 'on',
 1329:                                'adminmail'     => 'off',
 1330:                                'newuser'       => 'off',
 1331:                              );
 1332:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1333:         my (%checkedon,%checkedoff);
 1334:         foreach my $item (@toggles) {
 1335:             if ($defaultchecked{$item} eq 'on') { 
 1336:                 $checkedon{$item} = ' checked="checked" ';
 1337:                 $checkedoff{$item} = ' ';
 1338:             } elsif ($defaultchecked{$item} eq 'off') {
 1339:                 $checkedoff{$item} = ' checked="checked" ';
 1340:                 $checkedon{$item} = ' ';
 1341:             }
 1342:         }
 1343:         my @images = ('img','logo','domlogo','login');
 1344:         my @logintext = ('textcol','bgcol');
 1345:         my @bgs = ('pgbg','mainbg','sidebg');
 1346:         my @links = ('link','alink','vlink');
 1347:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1348:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1349:         my (%is_custom,%designs);
 1350:         my %defaults = (
 1351:                        font => $defaultdesign{'login.font'},
 1352:                        );
 1353:         foreach my $item (@images) {
 1354:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1355:             $defaults{'showlogo'}{$item} = 1;
 1356:         }
 1357:         foreach my $item (@bgs) {
 1358:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1359:         }
 1360:         foreach my $item (@logintext) {
 1361:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1362:         }
 1363:         foreach my $item (@links) {
 1364:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1365:         }
 1366:         if (ref($settings) eq 'HASH') {
 1367:             foreach my $item (@toggles) {
 1368:                 if ($settings->{$item} eq '1') {
 1369:                     $checkedon{$item} =  ' checked="checked" ';
 1370:                     $checkedoff{$item} = ' ';
 1371:                 } elsif ($settings->{$item} eq '0') {
 1372:                     $checkedoff{$item} =  ' checked="checked" ';
 1373:                     $checkedon{$item} = ' ';
 1374:                 }
 1375:             }
 1376:             foreach my $item (@images) {
 1377:                 if (defined($settings->{$item})) {
 1378:                     $designs{$item} = $settings->{$item};
 1379:                     $is_custom{$item} = 1;
 1380:                 }
 1381:                 if (defined($settings->{'showlogo'}{$item})) {
 1382:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1383:                 }
 1384:             }
 1385:             foreach my $item (@logintext) {
 1386:                 if ($settings->{$item} ne '') {
 1387:                     $designs{'logintext'}{$item} = $settings->{$item};
 1388:                     $is_custom{$item} = 1;
 1389:                 }
 1390:             }
 1391:             if ($settings->{'font'} ne '') {
 1392:                 $designs{'font'} = $settings->{'font'};
 1393:                 $is_custom{'font'} = 1;
 1394:             }
 1395:             foreach my $item (@bgs) {
 1396:                 if ($settings->{$item} ne '') {
 1397:                     $designs{'bgs'}{$item} = $settings->{$item};
 1398:                     $is_custom{$item} = 1;
 1399:                 }
 1400:             }
 1401:             foreach my $item (@links) {
 1402:                 if ($settings->{$item} ne '') {
 1403:                     $designs{'links'}{$item} = $settings->{$item};
 1404:                     $is_custom{$item} = 1;
 1405:                 }
 1406:             }
 1407:         } else {
 1408:             if ($designhash{$dom.'.login.font'} ne '') {
 1409:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1410:                 $is_custom{'font'} = 1;
 1411:             }
 1412:             foreach my $item (@images) {
 1413:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1414:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1415:                     $is_custom{$item} = 1;
 1416:                 }
 1417:             }
 1418:             foreach my $item (@bgs) {
 1419:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1420:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1421:                     $is_custom{$item} = 1;
 1422:                 }
 1423:             }
 1424:             foreach my $item (@links) {
 1425:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1426:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1427:                     $is_custom{$item} = 1;
 1428:                 }
 1429:             }
 1430:         }
 1431:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1432:                                                       logo => 'Institution Logo',
 1433:                                                       domlogo => 'Domain Logo',
 1434:                                                       login => 'Login box');
 1435:         my $itemcount = 1;
 1436:         foreach my $item (@toggles) {
 1437:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1438:             $datatable .=  
 1439:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1440:                 '</td><td>'.
 1441:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1442:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1443:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1444:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1445:                 '</tr>';
 1446:             $itemcount ++;
 1447:         }
 1448:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1449:         $datatable .= '</tr></table></td></tr>';
 1450:     } elsif ($caller eq 'help') {
 1451:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1452:         my $itemcount = 1;
 1453:         $defaulturl = '/adm/loginproblems.html';
 1454:         $defaulttype = 'default';
 1455:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1456:         my @currlangs;
 1457:         if (ref($settings) eq 'HASH') {
 1458:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1459:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1460:                     next if ($settings->{'helpurl'}{$key} eq '');
 1461:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1462:                     $type{$key} = 'custom';
 1463:                     unless ($key eq 'nolang') {
 1464:                         push(@currlangs,$key);
 1465:                     }
 1466:                 }
 1467:             } elsif ($settings->{'helpurl'} ne '') {
 1468:                 $type{'nolang'} = 'custom';
 1469:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1470:             }
 1471:         }
 1472:         foreach my $lang ('nolang',sort(@currlangs)) {
 1473:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1474:             $datatable .= '<tr'.$css_class.'>';
 1475:             if ($url{$lang} eq '') {
 1476:                 $url{$lang} = $defaulturl;
 1477:             }
 1478:             if ($type{$lang} eq '') {
 1479:                 $type{$lang} = $defaulttype;
 1480:             }
 1481:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1482:             if ($lang eq 'nolang') {
 1483:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1484:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1485:             } else {
 1486:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1487:                                   $langchoices{$lang},
 1488:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1489:             }
 1490:             $datatable .= '</span></td>'."\n".
 1491:                           '<td class="LC_left_item">';
 1492:             if ($type{$lang} eq 'custom') {
 1493:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1494:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1495:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1496:             } else {
 1497:                 $datatable .= $lt{'upl'};
 1498:             }
 1499:             $datatable .='<br />';
 1500:             if ($switchserver) {
 1501:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1502:             } else {
 1503:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1504:             }
 1505:             $datatable .= '</td></tr>';
 1506:             $itemcount ++;
 1507:         }
 1508:         my @addlangs;
 1509:         foreach my $lang (sort(keys(%langchoices))) {
 1510:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1511:             push(@addlangs,$lang);
 1512:         }
 1513:         if (@addlangs > 0) {
 1514:             my %toadd;
 1515:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1516:             $toadd{''} = &mt('Select');
 1517:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1518:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1519:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1520:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1521:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1522:             if ($switchserver) {
 1523:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1524:             } else {
 1525:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1526:             }
 1527:             $datatable .= '</td></tr>';
 1528:             $itemcount ++;
 1529:         }
 1530:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1531:     } elsif ($caller eq 'headtag') {
 1532:         my %domservers = &Apache::lonnet::get_servers($dom);
 1533:         my $choice = $choices{'headtag'};
 1534:         $css_class = ' class="LC_odd_row"';
 1535:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1536:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1537:                       '<th>'.$choices{'current'}.'</th>'.
 1538:                       '<th>'.$choices{'action'}.'</th>'.
 1539:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1540:         my (%currurls,%currexempt);
 1541:         if (ref($settings) eq 'HASH') {
 1542:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1543:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1544:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1545:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1546:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1547:                     }
 1548:                 }
 1549:             }
 1550:         }
 1551:         foreach my $lonhost (sort(keys(%domservers))) {
 1552:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1553:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1554:             if ($currurls{$lonhost}) {
 1555:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1556:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1557:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1558:                               '">'.$lt{'curr'}.'</a></td>'.
 1559:                               '<td><span class="LC_nobreak"><label>'.
 1560:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1561:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1562:             } else {
 1563:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1564:             }
 1565:             $datatable .='<br />';
 1566:             if ($switchserver) {
 1567:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1568:             } else {
 1569:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1570:             }
 1571:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1572:         }
 1573:         $datatable .= '</table></td></tr>';
 1574:     } elsif ($caller eq 'saml') {
 1575:         my %domservers = &Apache::lonnet::get_servers($dom);
 1576:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1577:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1578:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1579:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1580:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
 1581:         foreach my $lonhost (keys(%domservers)) {
 1582:             $samlurl{$lonhost} = '/adm/sso';
 1583:             $styleon{$lonhost} = 'display:none';
 1584:             $styleoff{$lonhost} = '';
 1585:         }
 1586:         if (ref($settings->{'saml'}) eq 'HASH') {
 1587:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1588:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1589:                     $saml{$lonhost} = 1;
 1590:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1591:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1592:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1593:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1594:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1595:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1596:                     $styleon{$lonhost} = '';
 1597:                     $styleoff{$lonhost} = 'display:none';
 1598:                 } else {
 1599:                     $styleon{$lonhost} = 'display:none';
 1600:                     $styleoff{$lonhost} = '';
 1601:                 }
 1602:             }
 1603:         }
 1604:         my $itemcount = 1;
 1605:         foreach my $lonhost (sort(keys(%domservers))) {
 1606:             my $samlon = ' ';
 1607:             my $samloff = ' checked="checked" ';
 1608:             if ($saml{$lonhost}) {
 1609:                 $samlon = $samloff;
 1610:                 $samloff = ' ';
 1611:             }
 1612:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1613:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1614:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1615:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1616:                           &mt('No').'</label>'.('&nbsp;'x2).
 1617:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1618:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1619:                           &mt('Yes').'</label></span></td>'.
 1620:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1621:                           '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
 1622:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1623:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1624:                           '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
 1625:                           '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
 1626:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
 1627:                           $samltext{$lonhost}.'" /></td><td>';
 1628:             if ($samlimg{$lonhost}) {
 1629:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1630:                               '<span class="LC_nobreak"><label>'.
 1631:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1632:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1633:             } else {
 1634:                 $datatable .= $lt{'upl'};
 1635:             }
 1636:             $datatable .='<br />';
 1637:             if ($switchserver) {
 1638:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1639:             } else {
 1640:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1641:             }
 1642:             $datatable .= '</td>'.
 1643:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
 1644:                           'value="'.$samlalt{$lonhost}.'" /></td>'.
 1645:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
 1646:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1647:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
 1648:                           $samltitle{$lonhost}.'</textarea></td>'.
 1649:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
 1650:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1651:                           '</table></td>'.
 1652:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1653:            $itemcount ++;
 1654:         }
 1655:         $datatable .= '</table></td></tr>';
 1656:     }
 1657:     return $datatable;
 1658: }
 1659: 
 1660: sub login_choices {
 1661:     my %choices =
 1662:         &Apache::lonlocal::texthash (
 1663:             coursecatalog => 'Display Course/Community Catalog link?',
 1664:             adminmail     => "Display Administrator's E-mail Address?",
 1665:             helpdesk      => 'Display "Contact Helpdesk" link',
 1666:             disallowlogin => "Login page requests redirected",
 1667:             hostid        => "Server",
 1668:             server        => "Redirect to:",
 1669:             serverpath    => "Path",
 1670:             custompath    => "Custom", 
 1671:             exempt        => "Exempt IP(s)",
 1672:             directlogin   => "No redirect",
 1673:             newuser       => "Link to create a user account",
 1674:             img           => "Header",
 1675:             logo          => "Main Logo",
 1676:             domlogo       => "Domain Logo",
 1677:             login         => "Log-in Header", 
 1678:             textcol       => "Text color",
 1679:             bgcol         => "Box color",
 1680:             bgs           => "Background colors",
 1681:             links         => "Link colors",
 1682:             font          => "Font color",
 1683:             pgbg          => "Header",
 1684:             mainbg        => "Page",
 1685:             sidebg        => "Login box",
 1686:             link          => "Link",
 1687:             alink         => "Active link",
 1688:             vlink         => "Visited link",
 1689:             headtag       => "Custom markup",
 1690:             action        => "Action",
 1691:             current       => "Current",
 1692:             samllanding   => "Dual login?",
 1693:             samloptions   => "Options",
 1694:         );
 1695:     return %choices;
 1696: }
 1697: 
 1698: sub login_file_options {
 1699:       return &Apache::lonlocal::texthash(
 1700:                                            del     => 'Delete?',
 1701:                                            rep     => 'Replace:',
 1702:                                            upl     => 'Upload:',
 1703:                                            curr    => 'View contents',
 1704:                                            default => 'Default',
 1705:                                            custom  => 'Custom',
 1706:                                            none    => 'None',
 1707:       );
 1708: }
 1709: 
 1710: sub print_rolecolors {
 1711:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1712:     my %choices = &color_font_choices();
 1713:     my @bgs = ('pgbg','tabbg','sidebg');
 1714:     my @links = ('link','alink','vlink');
 1715:     my @images = ('img');
 1716:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1717:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1718:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1719:     my (%is_custom,%designs);
 1720:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1721:     if (ref($settings) eq 'HASH') {
 1722:         if (ref($settings->{$role}) eq 'HASH') {
 1723:             if ($settings->{$role}->{'img'} ne '') {
 1724:                 $designs{'img'} = $settings->{$role}->{'img'};
 1725:                 $is_custom{'img'} = 1;
 1726:             }
 1727:             if ($settings->{$role}->{'font'} ne '') {
 1728:                 $designs{'font'} = $settings->{$role}->{'font'};
 1729:                 $is_custom{'font'} = 1;
 1730:             }
 1731:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1732:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1733:                 $is_custom{'fontmenu'} = 1;
 1734:             }
 1735:             foreach my $item (@bgs) {
 1736:                 if ($settings->{$role}->{$item} ne '') {
 1737:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1738:                     $is_custom{$item} = 1;
 1739:                 }
 1740:             }
 1741:             foreach my $item (@links) {
 1742:                 if ($settings->{$role}->{$item} ne '') {
 1743:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1744:                     $is_custom{$item} = 1;
 1745:                 }
 1746:             }
 1747:         }
 1748:     } else {
 1749:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1750:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1751:             $is_custom{'img'} = 1;
 1752:         }
 1753:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1754:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1755:             $is_custom{'fontmenu'} = 1; 
 1756:         }
 1757:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1758:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1759:             $is_custom{'font'} = 1;
 1760:         }
 1761:         foreach my $item (@bgs) {
 1762:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1763:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1764:                 $is_custom{$item} = 1;
 1765:             
 1766:             }
 1767:         }
 1768:         foreach my $item (@links) {
 1769:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1770:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1771:                 $is_custom{$item} = 1;
 1772:             }
 1773:         }
 1774:     }
 1775:     my $itemcount = 1;
 1776:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1777:     $datatable .= '</tr></table></td></tr>';
 1778:     return $datatable;
 1779: }
 1780: 
 1781: sub role_defaults {
 1782:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1783:     my %defaults;
 1784:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1785:         return %defaults;
 1786:     }
 1787:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1788:     if ($role eq 'login') {
 1789:         %defaults = (
 1790:                        font => $defaultdesign{$role.'.font'},
 1791:                     );
 1792:         if (ref($logintext) eq 'ARRAY') {
 1793:             foreach my $item (@{$logintext}) {
 1794:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1795:             }
 1796:         }
 1797:         foreach my $item (@{$images}) {
 1798:             $defaults{'showlogo'}{$item} = 1;
 1799:         }
 1800:     } else {
 1801:         %defaults = (
 1802:                        img => $defaultdesign{$role.'.img'},
 1803:                        font => $defaultdesign{$role.'.font'},
 1804:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1805:                     );
 1806:     }
 1807:     foreach my $item (@{$bgs}) {
 1808:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1809:     }
 1810:     foreach my $item (@{$links}) {
 1811:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1812:     }
 1813:     foreach my $item (@{$images}) {
 1814:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1815:     }
 1816:     return %defaults;
 1817: }
 1818: 
 1819: sub display_color_options {
 1820:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1821:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1822:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1823:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1824:     my $datatable = '<tr'.$css_class.'>'.
 1825:         '<td>'.$choices->{'font'}.'</td>';
 1826:     if (!$is_custom->{'font'}) {
 1827:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1828:     } else {
 1829:         $datatable .= '<td>&nbsp;</td>';
 1830:     }
 1831:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1832: 
 1833:     $datatable .= '<td><span class="LC_nobreak">'.
 1834:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1835:                   ' value="'.$current_color.'" />&nbsp;'.
 1836:                   '&nbsp;</span></td></tr>';
 1837:     unless ($role eq 'login') { 
 1838:         $datatable .= '<tr'.$css_class.'>'.
 1839:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1840:         if (!$is_custom->{'fontmenu'}) {
 1841:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1842:         } else {
 1843:             $datatable .= '<td>&nbsp;</td>';
 1844:         }
 1845: 	$current_color = $designs->{'fontmenu'} ?
 1846: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1847:         $datatable .= '<td><span class="LC_nobreak">'.
 1848:                       '<input class="colorchooser" type="text" size="10" name="'
 1849: 		      .$role.'_fontmenu"'.
 1850:                       ' value="'.$current_color.'" />&nbsp;'.
 1851:                       '&nbsp;</span></td></tr>';
 1852:     }
 1853:     my $switchserver = &check_switchserver($dom,$confname);
 1854:     foreach my $img (@{$images}) {
 1855: 	$itemcount ++;
 1856:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1857:         $datatable .= '<tr'.$css_class.'>'.
 1858:                       '<td>'.$choices->{$img};
 1859:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1860:         if ($role eq 'login') {
 1861:             if ($img eq 'login') {
 1862:                 $login_hdr_pick =
 1863:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1864:                 $logincolors =
 1865:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1866:                                        $designs,$defaults);
 1867:             } elsif ($img ne 'domlogo') {
 1868:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1869:             }
 1870:         }
 1871:         $datatable .= '</td>';
 1872:         if ($designs->{$img} ne '') {
 1873:             $imgfile = $designs->{$img};
 1874: 	    $img_import = ($imgfile =~ m{^/adm/});
 1875:         } else {
 1876:             $imgfile = $defaults->{$img};
 1877:         }
 1878:         if ($imgfile) {
 1879:             my ($showfile,$fullsize);
 1880:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1881:                 my $urldir = $1;
 1882:                 my $filename = $2;
 1883:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1884:                 if (@info) {
 1885:                     my $thumbfile = 'tn-'.$filename;
 1886:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1887:                     if (@thumb) {
 1888:                         $showfile = $urldir.'/'.$thumbfile;
 1889:                     } else {
 1890:                         $showfile = $imgfile;
 1891:                     }
 1892:                 } else {
 1893:                     $showfile = '';
 1894:                 }
 1895:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1896:                 $showfile = $imgfile;
 1897:                 my $imgdir = $1;
 1898:                 my $filename = $2;
 1899:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1900:                     $showfile = "/$imgdir/tn-".$filename;
 1901:                 } else {
 1902:                     my $input = $londocroot.$imgfile;
 1903:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1904:                     if (!-e $output) {
 1905:                         my ($width,$height) = &thumb_dimensions();
 1906:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1907:                         if ($fullwidth ne '' && $fullheight ne '') {
 1908:                             if ($fullwidth > $width && $fullheight > $height) { 
 1909:                                 my $size = $width.'x'.$height;
 1910:                                 my @args = ('convert','-sample',$size,$input,$output);
 1911:                                 system({$args[0]} @args);
 1912:                                 $showfile = "/$imgdir/tn-".$filename;
 1913:                             }
 1914:                         }
 1915:                     }
 1916:                 }
 1917:             }
 1918:             if ($showfile) {
 1919:                 if ($showfile =~ m{^/(adm|res)/}) {
 1920:                     if ($showfile =~ m{^/res/}) {
 1921:                         my $local_showfile =
 1922:                             &Apache::lonnet::filelocation('',$showfile);
 1923:                         &Apache::lonnet::repcopy($local_showfile);
 1924:                     }
 1925:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1926:                 }
 1927:                 if ($imgfile) {
 1928:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1929:                         if ($imgfile =~ m{^/res/}) {
 1930:                             my $local_imgfile =
 1931:                                 &Apache::lonnet::filelocation('',$imgfile);
 1932:                             &Apache::lonnet::repcopy($local_imgfile);
 1933:                         }
 1934:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1935:                     } else {
 1936:                         $fullsize = $imgfile;
 1937:                     }
 1938:                 }
 1939:                 $datatable .= '<td>';
 1940:                 if ($img eq 'login') {
 1941:                     $datatable .= $login_hdr_pick;
 1942:                 } 
 1943:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1944:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1945:             } else {
 1946:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1947:                               &mt('Upload:').'<br />';
 1948:             }
 1949:         } else {
 1950:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1951:                           &mt('Upload:').'<br />';
 1952:         }
 1953:         if ($switchserver) {
 1954:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1955:         } else {
 1956:             if ($img ne 'login') { # suppress file selection for Log-in header
 1957:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1958:             }
 1959:         }
 1960:         $datatable .= '</td></tr>';
 1961:     }
 1962:     $itemcount ++;
 1963:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1964:     $datatable .= '<tr'.$css_class.'>'.
 1965:                   '<td>'.$choices->{'bgs'}.'</td>';
 1966:     my $bgs_def;
 1967:     foreach my $item (@{$bgs}) {
 1968:         if (!$is_custom->{$item}) {
 1969:             $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>';
 1970:         }
 1971:     }
 1972:     if ($bgs_def) {
 1973:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1974:     } else {
 1975:         $datatable .= '<td>&nbsp;</td>';
 1976:     }
 1977:     $datatable .= '<td class="LC_right_item">'.
 1978:                   '<table border="0"><tr>';
 1979: 
 1980:     foreach my $item (@{$bgs}) {
 1981:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 1982: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 1983:         if ($designs->{'bgs'}{$item}) {
 1984:             $datatable .= '&nbsp;';
 1985:         }
 1986:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1987:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1988:     }
 1989:     $datatable .= '</tr></table></td></tr>';
 1990:     $itemcount ++;
 1991:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1992:     $datatable .= '<tr'.$css_class.'>'.
 1993:                   '<td>'.$choices->{'links'}.'</td>';
 1994:     my $links_def;
 1995:     foreach my $item (@{$links}) {
 1996:         if (!$is_custom->{$item}) {
 1997:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 1998:         }
 1999:     }
 2000:     if ($links_def) {
 2001:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2002:     } else {
 2003:         $datatable .= '<td>&nbsp;</td>';
 2004:     }
 2005:     $datatable .= '<td class="LC_right_item">'.
 2006:                   '<table border="0"><tr>';
 2007:     foreach my $item (@{$links}) {
 2008: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2009:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 2010:         if ($designs->{'links'}{$item}) {
 2011:             $datatable.='&nbsp;';
 2012:         }
 2013:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2014:                       '" /></td>';
 2015:     }
 2016:     $$rowtotal += $itemcount;
 2017:     return $datatable;
 2018: }
 2019: 
 2020: sub logo_display_options {
 2021:     my ($img,$defaults,$designs) = @_;
 2022:     my $checkedon;
 2023:     if (ref($defaults) eq 'HASH') {
 2024:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2025:             if ($defaults->{'showlogo'}{$img}) {
 2026:                 $checkedon = 'checked="checked" ';     
 2027:             }
 2028:         } 
 2029:     }
 2030:     if (ref($designs) eq 'HASH') {
 2031:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2032:             if (defined($designs->{'showlogo'}{$img})) {
 2033:                 if ($designs->{'showlogo'}{$img} == 0) {
 2034:                     $checkedon = '';
 2035:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2036:                     $checkedon = 'checked="checked" ';
 2037:                 }
 2038:             }
 2039:         }
 2040:     }
 2041:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2042:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2043:            &mt('show').'</label>'."\n";
 2044: }
 2045: 
 2046: sub login_header_options  {
 2047:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2048:     my $output = '';
 2049:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2050:         $output .= &mt('Text default(s):').'<br />';
 2051:         if (!$is_custom->{'textcol'}) {
 2052:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2053:                        '&nbsp;&nbsp;&nbsp;';
 2054:         }
 2055:         if (!$is_custom->{'bgcol'}) {
 2056:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2057:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2058:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2059:         }
 2060:         $output .= '<br />';
 2061:     }
 2062:     $output .='<br />';
 2063:     return $output;
 2064: }
 2065: 
 2066: sub login_text_colors {
 2067:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2068:     my $color_menu = '<table border="0"><tr>';
 2069:     foreach my $item (@{$logintext}) {
 2070:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 2071:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2072:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2073:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2074:     }
 2075:     $color_menu .= '</tr></table><br />';
 2076:     return $color_menu;
 2077: }
 2078: 
 2079: sub image_changes {
 2080:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2081:     my $output;
 2082:     if ($img eq 'login') {
 2083:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2084:     } elsif (!$is_custom) {
 2085:         if ($img ne 'domlogo') {
 2086:             $output = &mt('Default image:').'<br />';
 2087:         } else {
 2088:             $output = &mt('Default in use:').'<br />';
 2089:         }
 2090:     }
 2091:     if ($img ne 'login') {
 2092:         if ($img_import) {
 2093:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2094:         }
 2095:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2096:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2097:         if ($is_custom) {
 2098:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2099:                        '<input type="checkbox" name="'.
 2100:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2101:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2102:         } else {
 2103:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 2104:         }
 2105:     }
 2106:     return $output;
 2107: }
 2108: 
 2109: sub print_quotas {
 2110:     my ($dom,$settings,$rowtotal,$action) = @_;
 2111:     my $context;
 2112:     if ($action eq 'quotas') {
 2113:         $context = 'tools';
 2114:     } else {
 2115:         $context = $action;
 2116:     }
 2117:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2118:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2119:     my $typecount = 0;
 2120:     my ($css_class,%titles);
 2121:     if ($context eq 'requestcourses') {
 2122:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 2123:         @options =('norequest','approval','validate','autolimit');
 2124:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2125:         %titles = &courserequest_titles();
 2126:     } elsif ($context eq 'requestauthor') {
 2127:         @usertools = ('author');
 2128:         @options = ('norequest','approval','automatic');
 2129:         %titles = &authorrequest_titles();
 2130:     } else {
 2131:         @usertools = ('aboutme','blog','webdav','portfolio');
 2132:         %titles = &tool_titles();
 2133:     }
 2134:     if (ref($types) eq 'ARRAY') {
 2135:         foreach my $type (@{$types}) {
 2136:             my ($currdefquota,$currauthorquota);
 2137:             unless (($context eq 'requestcourses') ||
 2138:                     ($context eq 'requestauthor')) {
 2139:                 if (ref($settings) eq 'HASH') {
 2140:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2141:                         $currdefquota = $settings->{defaultquota}->{$type};
 2142:                     } else {
 2143:                         $currdefquota = $settings->{$type};
 2144:                     }
 2145:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2146:                         $currauthorquota = $settings->{authorquota}->{$type};
 2147:                     }
 2148:                 }
 2149:             }
 2150:             if (defined($usertypes->{$type})) {
 2151:                 $typecount ++;
 2152:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2153:                 $datatable .= '<tr'.$css_class.'>'.
 2154:                               '<td>'.$usertypes->{$type}.'</td>'.
 2155:                               '<td class="LC_left_item">';
 2156:                 if ($context eq 'requestcourses') {
 2157:                     $datatable .= '<table><tr>';
 2158:                 }
 2159:                 my %cell;  
 2160:                 foreach my $item (@usertools) {
 2161:                     if ($context eq 'requestcourses') {
 2162:                         my ($curroption,$currlimit);
 2163:                         if (ref($settings) eq 'HASH') {
 2164:                             if (ref($settings->{$item}) eq 'HASH') {
 2165:                                 $curroption = $settings->{$item}->{$type};
 2166:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2167:                                     $currlimit = $1; 
 2168:                                 }
 2169:                             }
 2170:                         }
 2171:                         if (!$curroption) {
 2172:                             $curroption = 'norequest';
 2173:                         }
 2174:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2175:                         foreach my $option (@options) {
 2176:                             my $val = $option;
 2177:                             if ($option eq 'norequest') {
 2178:                                 $val = 0;  
 2179:                             }
 2180:                             if ($option eq 'validate') {
 2181:                                 my $canvalidate = 0;
 2182:                                 if (ref($validations{$item}) eq 'HASH') { 
 2183:                                     if ($validations{$item}{$type}) {
 2184:                                         $canvalidate = 1;
 2185:                                     }
 2186:                                 }
 2187:                                 next if (!$canvalidate);
 2188:                             }
 2189:                             my $checked = '';
 2190:                             if ($option eq $curroption) {
 2191:                                 $checked = ' checked="checked"';
 2192:                             } elsif ($option eq 'autolimit') {
 2193:                                 if ($curroption =~ /^autolimit/) {
 2194:                                     $checked = ' checked="checked"';
 2195:                                 }                       
 2196:                             } 
 2197:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2198:                                   '<input type="radio" name="crsreq_'.$item.
 2199:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2200:                                   $titles{$option}.'</label>';
 2201:                             if ($option eq 'autolimit') {
 2202:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2203:                                                 $item.'_limit_'.$type.'" size="1" '.
 2204:                                                 'value="'.$currlimit.'" />';
 2205:                             }
 2206:                             $cell{$item} .= '</span> ';
 2207:                             if ($option eq 'autolimit') {
 2208:                                 $cell{$item} .= $titles{'unlimited'};
 2209:                             }
 2210:                         }
 2211:                     } elsif ($context eq 'requestauthor') {
 2212:                         my $curroption;
 2213:                         if (ref($settings) eq 'HASH') {
 2214:                             $curroption = $settings->{$type};
 2215:                         }
 2216:                         if (!$curroption) {
 2217:                             $curroption = 'norequest';
 2218:                         }
 2219:                         foreach my $option (@options) {
 2220:                             my $val = $option;
 2221:                             if ($option eq 'norequest') {
 2222:                                 $val = 0;
 2223:                             }
 2224:                             my $checked = '';
 2225:                             if ($option eq $curroption) {
 2226:                                 $checked = ' checked="checked"';
 2227:                             }
 2228:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2229:                                   '<input type="radio" name="authorreq_'.$type.
 2230:                                   '" value="'.$val.'"'.$checked.' />'.
 2231:                                   $titles{$option}.'</label></span>&nbsp; ';
 2232:                         }
 2233:                     } else {
 2234:                         my $checked = 'checked="checked" ';
 2235:                         if (ref($settings) eq 'HASH') {
 2236:                             if (ref($settings->{$item}) eq 'HASH') {
 2237:                                 if ($settings->{$item}->{$type} == 0) {
 2238:                                     $checked = '';
 2239:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2240:                                     $checked =  'checked="checked" ';
 2241:                                 }
 2242:                             }
 2243:                         }
 2244:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2245:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2246:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2247:                                       '</label></span>&nbsp; ';
 2248:                     }
 2249:                 }
 2250:                 if ($context eq 'requestcourses') {
 2251:                     $datatable .= '</tr><tr>';
 2252:                     foreach my $item (@usertools) {
 2253:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2254:                     }
 2255:                     $datatable .= '</tr></table>';
 2256:                 }
 2257:                 $datatable .= '</td>';
 2258:                 unless (($context eq 'requestcourses') ||
 2259:                         ($context eq 'requestauthor')) {
 2260:                     $datatable .= 
 2261:                               '<td class="LC_right_item">'.
 2262:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2263:                               '<input type="text" name="quota_'.$type.
 2264:                               '" value="'.$currdefquota.
 2265:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2266:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2267:                               '<input type="text" name="authorquota_'.$type.
 2268:                               '" value="'.$currauthorquota.
 2269:                               '" size="5" /></span></td>';
 2270:                 }
 2271:                 $datatable .= '</tr>';
 2272:             }
 2273:         }
 2274:     }
 2275:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2276:         $defaultquota = '20';
 2277:         $authorquota = '500';
 2278:         if (ref($settings) eq 'HASH') {
 2279:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2280:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2281:             } elsif (defined($settings->{'default'})) {
 2282:                 $defaultquota = $settings->{'default'};
 2283:             }
 2284:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2285:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2286:             }
 2287:         }
 2288:     }
 2289:     $typecount ++;
 2290:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2291:     $datatable .= '<tr'.$css_class.'>'.
 2292:                   '<td>'.$othertitle.'</td>'.
 2293:                   '<td class="LC_left_item">';
 2294:     if ($context eq 'requestcourses') {
 2295:         $datatable .= '<table><tr>';
 2296:     }
 2297:     my %defcell;
 2298:     foreach my $item (@usertools) {
 2299:         if ($context eq 'requestcourses') {
 2300:             my ($curroption,$currlimit);
 2301:             if (ref($settings) eq 'HASH') {
 2302:                 if (ref($settings->{$item}) eq 'HASH') {
 2303:                     $curroption = $settings->{$item}->{'default'};
 2304:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2305:                         $currlimit = $1;
 2306:                     }
 2307:                 }
 2308:             }
 2309:             if (!$curroption) {
 2310:                 $curroption = 'norequest';
 2311:             }
 2312:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2313:             foreach my $option (@options) {
 2314:                 my $val = $option;
 2315:                 if ($option eq 'norequest') {
 2316:                     $val = 0;
 2317:                 }
 2318:                 if ($option eq 'validate') {
 2319:                     my $canvalidate = 0;
 2320:                     if (ref($validations{$item}) eq 'HASH') {
 2321:                         if ($validations{$item}{'default'}) {
 2322:                             $canvalidate = 1;
 2323:                         }
 2324:                     }
 2325:                     next if (!$canvalidate);
 2326:                 }
 2327:                 my $checked = '';
 2328:                 if ($option eq $curroption) {
 2329:                     $checked = ' checked="checked"';
 2330:                 } elsif ($option eq 'autolimit') {
 2331:                     if ($curroption =~ /^autolimit/) {
 2332:                         $checked = ' checked="checked"';
 2333:                     }
 2334:                 }
 2335:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2336:                                   '<input type="radio" name="crsreq_'.$item.
 2337:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2338:                                   $titles{$option}.'</label>';
 2339:                 if ($option eq 'autolimit') {
 2340:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2341:                                        $item.'_limit_default" size="1" '.
 2342:                                        'value="'.$currlimit.'" />';
 2343:                 }
 2344:                 $defcell{$item} .= '</span> ';
 2345:                 if ($option eq 'autolimit') {
 2346:                     $defcell{$item} .= $titles{'unlimited'};
 2347:                 }
 2348:             }
 2349:         } elsif ($context eq 'requestauthor') {
 2350:             my $curroption;
 2351:             if (ref($settings) eq 'HASH') {
 2352:                 $curroption = $settings->{'default'};
 2353:             }
 2354:             if (!$curroption) {
 2355:                 $curroption = 'norequest';
 2356:             }
 2357:             foreach my $option (@options) {
 2358:                 my $val = $option;
 2359:                 if ($option eq 'norequest') {
 2360:                     $val = 0;
 2361:                 }
 2362:                 my $checked = '';
 2363:                 if ($option eq $curroption) {
 2364:                     $checked = ' checked="checked"';
 2365:                 }
 2366:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2367:                               '<input type="radio" name="authorreq_default"'.
 2368:                               ' value="'.$val.'"'.$checked.' />'.
 2369:                               $titles{$option}.'</label></span>&nbsp; ';
 2370:             }
 2371:         } else {
 2372:             my $checked = 'checked="checked" ';
 2373:             if (ref($settings) eq 'HASH') {
 2374:                 if (ref($settings->{$item}) eq 'HASH') {
 2375:                     if ($settings->{$item}->{'default'} == 0) {
 2376:                         $checked = '';
 2377:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2378:                         $checked = 'checked="checked" ';
 2379:                     }
 2380:                 }
 2381:             }
 2382:             $datatable .= '<span class="LC_nobreak"><label>'.
 2383:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2384:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2385:                           '</label></span>&nbsp; ';
 2386:         }
 2387:     }
 2388:     if ($context eq 'requestcourses') {
 2389:         $datatable .= '</tr><tr>';
 2390:         foreach my $item (@usertools) {
 2391:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2392:         }
 2393:         $datatable .= '</tr></table>';
 2394:     }
 2395:     $datatable .= '</td>';
 2396:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2397:         $datatable .= '<td class="LC_right_item">'.
 2398:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2399:                       '<input type="text" name="defaultquota" value="'.
 2400:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2401:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2402:                       '<input type="text" name="authorquota" value="'.
 2403:                       $authorquota.'" size="5" /></span></td>';
 2404:     }
 2405:     $datatable .= '</tr>';
 2406:     $typecount ++;
 2407:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2408:     $datatable .= '<tr'.$css_class.'>'.
 2409:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2410:     if ($context eq 'requestcourses') {
 2411:         $datatable .= &mt('(overrides affiliation, if set)').
 2412:                       '</td>'.
 2413:                       '<td class="LC_left_item">'.
 2414:                       '<table><tr>';
 2415:     } else {
 2416:         $datatable .= &mt('(overrides affiliation, if checked)').
 2417:                       '</td>'.
 2418:                       '<td class="LC_left_item" colspan="2">'.
 2419:                       '<br />';
 2420:     }
 2421:     my %advcell;
 2422:     foreach my $item (@usertools) {
 2423:         if ($context eq 'requestcourses') {
 2424:             my ($curroption,$currlimit);
 2425:             if (ref($settings) eq 'HASH') {
 2426:                 if (ref($settings->{$item}) eq 'HASH') {
 2427:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2428:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2429:                         $currlimit = $1;
 2430:                     }
 2431:                 }
 2432:             }
 2433:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2434:             my $checked = '';
 2435:             if ($curroption eq '') {
 2436:                 $checked = ' checked="checked"';
 2437:             }
 2438:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2439:                                '<input type="radio" name="crsreq_'.$item.
 2440:                                '__LC_adv" value=""'.$checked.' />'.
 2441:                                &mt('No override set').'</label></span>&nbsp; ';
 2442:             foreach my $option (@options) {
 2443:                 my $val = $option;
 2444:                 if ($option eq 'norequest') {
 2445:                     $val = 0;
 2446:                 }
 2447:                 if ($option eq 'validate') {
 2448:                     my $canvalidate = 0;
 2449:                     if (ref($validations{$item}) eq 'HASH') {
 2450:                         if ($validations{$item}{'_LC_adv'}) {
 2451:                             $canvalidate = 1;
 2452:                         }
 2453:                     }
 2454:                     next if (!$canvalidate);
 2455:                 }
 2456:                 my $checked = '';
 2457:                 if ($val eq $curroption) {
 2458:                     $checked = ' checked="checked"';
 2459:                 } elsif ($option eq 'autolimit') {
 2460:                     if ($curroption =~ /^autolimit/) {
 2461:                         $checked = ' checked="checked"';
 2462:                     }
 2463:                 }
 2464:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2465:                                   '<input type="radio" name="crsreq_'.$item.
 2466:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2467:                                   $titles{$option}.'</label>';
 2468:                 if ($option eq 'autolimit') {
 2469:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2470:                                        $item.'_limit__LC_adv" size="1" '.
 2471:                                        'value="'.$currlimit.'" />';
 2472:                 }
 2473:                 $advcell{$item} .= '</span> ';
 2474:                 if ($option eq 'autolimit') {
 2475:                     $advcell{$item} .= $titles{'unlimited'};
 2476:                 }
 2477:             }
 2478:         } elsif ($context eq 'requestauthor') {
 2479:             my $curroption;
 2480:             if (ref($settings) eq 'HASH') {
 2481:                 $curroption = $settings->{'_LC_adv'};
 2482:             }
 2483:             my $checked = '';
 2484:             if ($curroption eq '') {
 2485:                 $checked = ' checked="checked"';
 2486:             }
 2487:             $datatable .= '<span class="LC_nobreak"><label>'.
 2488:                           '<input type="radio" name="authorreq__LC_adv"'.
 2489:                           ' value=""'.$checked.' />'.
 2490:                           &mt('No override set').'</label></span>&nbsp; ';
 2491:             foreach my $option (@options) {
 2492:                 my $val = $option;
 2493:                 if ($option eq 'norequest') {
 2494:                     $val = 0;
 2495:                 }
 2496:                 my $checked = '';
 2497:                 if ($val eq $curroption) {
 2498:                     $checked = ' checked="checked"';
 2499:                 }
 2500:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2501:                               '<input type="radio" name="authorreq__LC_adv"'.
 2502:                               ' value="'.$val.'"'.$checked.' />'.
 2503:                               $titles{$option}.'</label></span>&nbsp; ';
 2504:             }
 2505:         } else {
 2506:             my $checked = 'checked="checked" ';
 2507:             if (ref($settings) eq 'HASH') {
 2508:                 if (ref($settings->{$item}) eq 'HASH') {
 2509:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2510:                         $checked = '';
 2511:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2512:                         $checked = 'checked="checked" ';
 2513:                     }
 2514:                 }
 2515:             }
 2516:             $datatable .= '<span class="LC_nobreak"><label>'.
 2517:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2518:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2519:                           '</label></span>&nbsp; ';
 2520:         }
 2521:     }
 2522:     if ($context eq 'requestcourses') {
 2523:         $datatable .= '</tr><tr>';
 2524:         foreach my $item (@usertools) {
 2525:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2526:         }
 2527:         $datatable .= '</tr></table>';
 2528:     }
 2529:     $datatable .= '</td></tr>';
 2530:     $$rowtotal += $typecount;
 2531:     return $datatable;
 2532: }
 2533: 
 2534: sub print_requestmail {
 2535:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2536:     my ($now,$datatable,%currapp);
 2537:     $now = time;
 2538:     if (ref($settings) eq 'HASH') {
 2539:         if (ref($settings->{'notify'}) eq 'HASH') {
 2540:             if ($settings->{'notify'}{'approval'} ne '') {
 2541:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2542:             }
 2543:         }
 2544:     }
 2545:     my $numinrow = 2;
 2546:     my $css_class;
 2547:     if ($$rowtotal%2) {
 2548:         $css_class = 'LC_odd_row';
 2549:     }
 2550:     if ($customcss) {
 2551:         $css_class .= " $customcss";
 2552:     }
 2553:     $css_class =~ s/^\s+//;
 2554:     if ($css_class) {
 2555:         $css_class = ' class="'.$css_class.'"';
 2556:     }
 2557:     if ($rowstyle) {
 2558:         $css_class .= ' style="'.$rowstyle.'"';
 2559:     }
 2560:     my $text;
 2561:     if ($action eq 'requestcourses') {
 2562:         $text = &mt('Receive notification of course requests requiring approval');
 2563:     } elsif ($action eq 'requestauthor') {
 2564:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2565:     } else {
 2566:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2567:     }
 2568:     $datatable = '<tr'.$css_class.'>'.
 2569:                  ' <td>'.$text.'</td>'.
 2570:                  ' <td class="LC_left_item">';
 2571:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2572:                                                  $action.'notifyapproval',%currapp);
 2573:     if ($numdc > 0) {
 2574:         $datatable .= $table;
 2575:     } else {
 2576:         $datatable .= &mt('There are no active Domain Coordinators');
 2577:     }
 2578:     $datatable .='</td></tr>';
 2579:     return $datatable;
 2580: }
 2581: 
 2582: sub print_studentcode {
 2583:     my ($settings,$rowtotal) = @_;
 2584:     my $rownum = 0; 
 2585:     my ($output,%current);
 2586:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2587:     if (ref($settings) eq 'HASH') {
 2588:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2589:             foreach my $type (@crstypes) {
 2590:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2591:             }
 2592:         }
 2593:     }
 2594:     $output .= '<tr>'.
 2595:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2596:                '<td class="LC_left_item">';
 2597:     foreach my $type (@crstypes) {
 2598:         my $check = ' ';
 2599:         if ($current{$type}) {
 2600:             $check = ' checked="checked" ';
 2601:         }
 2602:         $output .= '<span class="LC_nobreak"><label>'.
 2603:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2604:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2605:     }
 2606:     $output .= '</td></tr>';
 2607:     $$rowtotal ++;
 2608:     return $output;
 2609: }
 2610: 
 2611: sub print_textbookcourses {
 2612:     my ($dom,$type,$settings,$rowtotal) = @_;
 2613:     my $rownum = 0;
 2614:     my $css_class;
 2615:     my $itemcount = 1;
 2616:     my $maxnum = 0;
 2617:     my $bookshash;
 2618:     if (ref($settings) eq 'HASH') {
 2619:         $bookshash = $settings->{$type};
 2620:     }
 2621:     my %ordered;
 2622:     if (ref($bookshash) eq 'HASH') {
 2623:         foreach my $item (keys(%{$bookshash})) {
 2624:             if (ref($bookshash->{$item}) eq 'HASH') {
 2625:                 my $num = $bookshash->{$item}{'order'};
 2626:                 $ordered{$num} = $item;
 2627:             }
 2628:         }
 2629:     }
 2630:     my $confname = $dom.'-domainconfig';
 2631:     my $switchserver = &check_switchserver($dom,$confname);
 2632:     my $maxnum = scalar(keys(%ordered));
 2633:     my $datatable;
 2634:     if (keys(%ordered)) {
 2635:         my @items = sort { $a <=> $b } keys(%ordered);
 2636:         for (my $i=0; $i<@items; $i++) {
 2637:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2638:             my $key = $ordered{$items[$i]};
 2639:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2640:             my $coursetitle = $coursehash{'description'};
 2641:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2642:             if (ref($bookshash->{$key}) eq 'HASH') {
 2643:                 $subject = $bookshash->{$key}->{'subject'};
 2644:                 $title = $bookshash->{$key}->{'title'};
 2645:                 if ($type eq 'textbooks') {
 2646:                     $publisher = $bookshash->{$key}->{'publisher'};
 2647:                     $author = $bookshash->{$key}->{'author'};
 2648:                     $image = $bookshash->{$key}->{'image'};
 2649:                     if ($image ne '') {
 2650:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2651:                         my $imagethumb = "$path/tn-".$imagefile;
 2652:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2653:                     }
 2654:                 }
 2655:             }
 2656:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2657:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2658:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2659:             for (my $k=0; $k<=$maxnum; $k++) {
 2660:                 my $vpos = $k+1;
 2661:                 my $selstr;
 2662:                 if ($k == $i) {
 2663:                     $selstr = ' selected="selected" ';
 2664:                 }
 2665:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2666:             }
 2667:             $datatable .= '</select>'.('&nbsp;'x2).
 2668:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2669:                 &mt('Delete?').'</label></span></td>'.
 2670:                 '<td colspan="2">'.
 2671:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2672:                 ('&nbsp;'x2).
 2673:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2674:             if ($type eq 'textbooks') {
 2675:                 $datatable .= ('&nbsp;'x2).
 2676:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2677:                               ('&nbsp;'x2).
 2678:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2679:                               ('&nbsp;'x2).
 2680:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2681:                 if ($image) {
 2682:                     $datatable .= $imgsrc.
 2683:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2684:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2685:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2686:                 }
 2687:                 if ($switchserver) {
 2688:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2689:                 } else {
 2690:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2691:                 }
 2692:             }
 2693:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2694:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2695:                           $coursetitle.'</span></td></tr>'."\n";
 2696:             $itemcount ++;
 2697:         }
 2698:     }
 2699:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2700:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2701:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2702:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2703:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2704:     for (my $k=0; $k<$maxnum+1; $k++) {
 2705:         my $vpos = $k+1;
 2706:         my $selstr;
 2707:         if ($k == $maxnum) {
 2708:             $selstr = ' selected="selected" ';
 2709:         }
 2710:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2711:     }
 2712:     $datatable .= '</select>&nbsp;'."\n".
 2713:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2714:                   '<td colspan="2">'.
 2715:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2716:                   ('&nbsp;'x2).
 2717:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2718:                   ('&nbsp;'x2);
 2719:     if ($type eq 'textbooks') {
 2720:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2721:                       ('&nbsp;'x2).
 2722:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2723:                       ('&nbsp;'x2).
 2724:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2725:         if ($switchserver) {
 2726:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2727:         } else {
 2728:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2729:         }
 2730:         $datatable .= '</span>'."\n";
 2731:     }
 2732:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2733:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2734:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2735:                   &Apache::loncommon::selectcourse_link
 2736:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2737:                   '</span></td>'."\n".
 2738:                   '</tr>'."\n";
 2739:     $itemcount ++;
 2740:     return $datatable;
 2741: }
 2742: 
 2743: sub textbookcourses_javascript {
 2744:     my ($settings) = @_;
 2745:     return unless(ref($settings) eq 'HASH');
 2746:     my (%ordered,%total,%jstext);
 2747:     foreach my $type ('textbooks','templates') {
 2748:         $total{$type} = 0;
 2749:         if (ref($settings->{$type}) eq 'HASH') {
 2750:             foreach my $item (keys(%{$settings->{$type}})) {
 2751:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2752:                     my $num = $settings->{$type}->{$item}{'order'};
 2753:                     $ordered{$type}{$num} = $item;
 2754:                 }
 2755:             }
 2756:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2757:         }
 2758:         my @jsarray = ();
 2759:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2760:             push(@jsarray,$ordered{$type}{$item});
 2761:         }
 2762:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2763:     }
 2764:     return <<"ENDSCRIPT";
 2765: <script type="text/javascript">
 2766: // <![CDATA[
 2767: function reorderBooks(form,item,caller) {
 2768:     var changedVal;
 2769: $jstext{'textbooks'};
 2770: $jstext{'templates'};
 2771:     var newpos;
 2772:     var maxh;
 2773:     if (caller == 'textbooks') {  
 2774:         newpos = 'textbooks_addbook_pos';
 2775:         maxh = 1 + $total{'textbooks'};
 2776:     } else {
 2777:         newpos = 'templates_addbook_pos';
 2778:         maxh = 1 + $total{'templates'};
 2779:     }
 2780:     var current = new Array;
 2781:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2782:     if (item == newpos) {
 2783:         changedVal = newitemVal;
 2784:     } else {
 2785:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2786:         current[newitemVal] = newpos;
 2787:     }
 2788:     if (caller == 'textbooks') {
 2789:         for (var i=0; i<textbooks.length; i++) {
 2790:             var elementName = 'textbooks_'+textbooks[i];
 2791:             if (elementName != item) {
 2792:                 if (form.elements[elementName]) {
 2793:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2794:                     current[currVal] = elementName;
 2795:                 }
 2796:             }
 2797:         }
 2798:     }
 2799:     if (caller == 'templates') {
 2800:         for (var i=0; i<templates.length; i++) {
 2801:             var elementName = 'templates_'+templates[i];
 2802:             if (elementName != item) {
 2803:                 if (form.elements[elementName]) {
 2804:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2805:                     current[currVal] = elementName;
 2806:                 }
 2807:             }
 2808:         }
 2809:     }
 2810:     var oldVal;
 2811:     for (var j=0; j<maxh; j++) {
 2812:         if (current[j] == undefined) {
 2813:             oldVal = j;
 2814:         }
 2815:     }
 2816:     if (oldVal < changedVal) {
 2817:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2818:            var elementName = current[k];
 2819:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2820:         }
 2821:     } else {
 2822:         for (var k=changedVal; k<oldVal; k++) {
 2823:             var elementName = current[k];
 2824:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2825:         }
 2826:     }
 2827:     return;
 2828: }
 2829: 
 2830: // ]]>
 2831: </script>
 2832: 
 2833: ENDSCRIPT
 2834: }
 2835: 
 2836: sub ltitools_javascript {
 2837:     my ($settings) = @_;
 2838:     my $togglejs = &ltitools_toggle_js();
 2839:     unless (ref($settings) eq 'HASH') {
 2840:         return $togglejs;
 2841:     }
 2842:     my (%ordered,$total,%jstext);
 2843:     $total = 0;
 2844:     foreach my $item (keys(%{$settings})) {
 2845:         if (ref($settings->{$item}) eq 'HASH') {
 2846:             my $num = $settings->{$item}{'order'};
 2847:             $ordered{$num} = $item;
 2848:         }
 2849:     }
 2850:     $total = scalar(keys(%{$settings}));
 2851:     my @jsarray = ();
 2852:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2853:         push(@jsarray,$ordered{$item});
 2854:     }
 2855:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 2856:     return <<"ENDSCRIPT";
 2857: <script type="text/javascript">
 2858: // <![CDATA[
 2859: function reorderLTITools(form,item) {
 2860:     var changedVal;
 2861: $jstext
 2862:     var newpos = 'ltitools_add_pos';
 2863:     var maxh = 1 + $total;
 2864:     var current = new Array;
 2865:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2866:     if (item == newpos) {
 2867:         changedVal = newitemVal;
 2868:     } else {
 2869:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2870:         current[newitemVal] = newpos;
 2871:     }
 2872:     for (var i=0; i<ltitools.length; i++) {
 2873:         var elementName = 'ltitools_'+ltitools[i];
 2874:         if (elementName != item) {
 2875:             if (form.elements[elementName]) {
 2876:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2877:                 current[currVal] = elementName;
 2878:             }
 2879:         }
 2880:     }
 2881:     var oldVal;
 2882:     for (var j=0; j<maxh; j++) {
 2883:         if (current[j] == undefined) {
 2884:             oldVal = j;
 2885:         }
 2886:     }
 2887:     if (oldVal < changedVal) {
 2888:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2889:            var elementName = current[k];
 2890:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2891:         }
 2892:     } else {
 2893:         for (var k=changedVal; k<oldVal; k++) {
 2894:             var elementName = current[k];
 2895:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2896:         }
 2897:     }
 2898:     return;
 2899: }
 2900: 
 2901: // ]]>
 2902: </script>
 2903: 
 2904: $togglejs
 2905: 
 2906: ENDSCRIPT
 2907: }
 2908: 
 2909: sub ltitools_toggle_js {
 2910:     return <<"ENDSCRIPT";
 2911: <script type="text/javascript">
 2912: // <![CDATA[
 2913: 
 2914: function toggleLTITools(form,setting,item) {
 2915:     var radioname = '';
 2916:     var divid = '';
 2917:     if ((setting == 'passback') || (setting == 'roster')) {
 2918:         radioname = 'ltitools_'+setting+'_'+item;
 2919:         divid = 'ltitools_'+setting+'time_'+item;
 2920:         var num = form.elements[radioname].length;
 2921:         if (num) {
 2922:             var setvis = '';
 2923:             for (var i=0; i<num; i++) {
 2924:                 if (form.elements[radioname][i].checked) {
 2925:                     if (form.elements[radioname][i].value == '1') {
 2926:                         if (document.getElementById(divid)) {
 2927:                             document.getElementById(divid).style.display = 'inline-block';
 2928:                         }
 2929:                         setvis = 1;
 2930:                     }
 2931:                     break;
 2932:                 }
 2933:             }
 2934:         }
 2935:         if (!setvis) {
 2936:             if (document.getElementById(divid)) {
 2937:                 document.getElementById(divid).style.display = 'none';
 2938:             }
 2939:         }
 2940:     }
 2941:     if (setting == 'user') {
 2942:         divid = 'ltitools_'+setting+'_div_'+item;
 2943:         var checkid = 'ltitools_'+setting+'_field_'+item;
 2944:         if (document.getElementById(divid)) {
 2945:             if (document.getElementById(checkid)) {
 2946:                 if (document.getElementById(checkid).checked) {
 2947:                     document.getElementById(divid).style.display = 'inline-block';
 2948:                 } else {
 2949:                     document.getElementById(divid).style.display = 'none';
 2950:                 }
 2951:             }
 2952:         }
 2953:     }
 2954:     return;
 2955: }
 2956: // ]]>
 2957: </script>
 2958: 
 2959: ENDSCRIPT
 2960: }
 2961: 
 2962: sub wafproxy_javascript {
 2963:     my ($dom) = @_;
 2964:     return <<"ENDSCRIPT";
 2965: <script type="text/javascript">
 2966: // <![CDATA[
 2967: function updateWAF() {
 2968:     if (document.getElementById('wafproxy_remoteip')) {
 2969:         var wafremote = 0;
 2970:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 2971:             wafremote = 1;
 2972:         }
 2973:         var fields = new Array('header','trust');
 2974:         for (var i=0; i<fields.length; i++) {
 2975:             if (document.getElementById('wafproxy_'+fields[i])) {
 2976:                 if (wafremote == 1) {
 2977:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 2978:                 }
 2979:                 else {
 2980:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 2981:                 }
 2982:             }
 2983:         }
 2984:         if (document.getElementById('wafproxyranges_$dom')) {
 2985:             if (wafremote == 1) {
 2986:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 2987:             } else {
 2988:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 2989:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 2990:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 2991:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 2992:                         }
 2993:                     }
 2994:                 }
 2995:             }
 2996:         }
 2997:     }
 2998:     return;
 2999: }
 3000: 
 3001: function checkWAF() {
 3002:     if (document.getElementById('wafproxy_remoteip')) {
 3003:         var wafvpn = 0;
 3004:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3005:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3006:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3007:                     wafvpn = 1;
 3008:                 }
 3009:                 break;
 3010:             }
 3011:         }
 3012:         var vpn = new Array('vpnint','vpnext');
 3013:         for (var i=0; i<vpn.length; i++) {
 3014:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3015:                 if (wafvpn == 1) {
 3016:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3017:                 }
 3018:                 else {
 3019:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3020:                 }
 3021:             }
 3022:         }
 3023:         if (document.getElementById('wafproxyranges_$dom')) {
 3024:             if (wafvpn == 1) {
 3025:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3026:             }
 3027:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3028:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3029:             }
 3030:         }
 3031:     }
 3032:     return;
 3033: }
 3034: 
 3035: function toggleWAF() {
 3036:     if (document.getElementById('wafproxy_table')) {
 3037:         var wafproxy = 0;
 3038:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3039:              if (document.display.wafproxy_${dom}[i].checked) {
 3040:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3041:                      wafproxy = 1;
 3042:                      break;
 3043:                 }
 3044:             }
 3045:         }
 3046:         if (wafproxy == 1) {
 3047:             document.getElementById('wafproxy_table').style.display='inline';
 3048:         }
 3049:         else {
 3050:            document.getElementById('wafproxy_table').style.display='none';
 3051:         }
 3052:         if (document.getElementById('wafproxyrow_${dom}')) {
 3053:             if (wafproxy == 1) {
 3054:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3055:             }
 3056:             else {
 3057:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3058:             }
 3059:         }
 3060:         if (document.getElementById('nowafproxyrow_$dom')) {
 3061:             if (wafproxy == 1) {
 3062:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3063:             }
 3064:             else {
 3065:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3066:             }
 3067:         }
 3068:     }
 3069:     return;
 3070: }
 3071: // ]]>
 3072: </script>
 3073: 
 3074: ENDSCRIPT
 3075: }
 3076: 
 3077: sub proctoring_javascript {
 3078:     my ($settings) = @_;
 3079:     my (%ordered,$total,%jstext);
 3080:     $total = 0;
 3081:     if (ref($settings) eq 'HASH') {
 3082:         foreach my $item (keys(%{$settings})) {
 3083:             if (ref($settings->{$item}) eq 'HASH') {
 3084:                 my $num = $settings->{$item}{'order'};
 3085:                 $ordered{$num} = $item;
 3086:             }
 3087:         }
 3088:         $total = scalar(keys(%{$settings}));
 3089:     } else {
 3090:         %ordered = (
 3091:                        0 => 'proctorio',
 3092:                        1 => 'examity',
 3093:                    );
 3094:         $total = 2; 
 3095:     }
 3096:     my @jsarray = ();
 3097:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3098:         push(@jsarray,$ordered{$item});
 3099:     }
 3100:     my $jstext = '    var proctors = Array('."'".join("','",@jsarray)."'".');'."\n";
 3101:     return <<"ENDSCRIPT";
 3102: <script type="text/javascript">
 3103: // <![CDATA[
 3104: function reorderProctoring(form,item) {
 3105:     var changedVal;
 3106: $jstext
 3107:     var maxh = $total;
 3108:     var current = new Array;
 3109:     var changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3110:     for (var i=0; i<proctors.length; i++) {
 3111:         var elementName = 'proctoring_pos_'+proctors[i];
 3112:         if (elementName != item) {
 3113:             if (form.elements[elementName]) {
 3114:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3115:                 current[currVal] = elementName;
 3116:             }
 3117:         }
 3118:     }
 3119:     var oldVal;
 3120:     for (var j=0; j<maxh; j++) {
 3121:         if (current[j] == undefined) {
 3122:             oldVal = j;
 3123:         }
 3124:     }
 3125:     if (oldVal < changedVal) {
 3126:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3127:            var elementName = current[k];
 3128:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3129:         }
 3130:     } else {
 3131:         for (var k=changedVal; k<oldVal; k++) {
 3132:             var elementName = current[k];
 3133:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3134:         }
 3135:     }
 3136:     return;
 3137: }
 3138: 
 3139: function toggleProctoring(form,item) {
 3140:     var fieldsets = document.getElementsByClassName('proctoring_'+item);
 3141:     if (fieldsets.length) {
 3142:         var radioname = 'proctoring_available_'+item;
 3143:         var num = form.elements[radioname].length;
 3144:         if (num) {
 3145:             var setvis = '';
 3146:             for (var i=0; i<num; i++) {
 3147:                 if (form.elements[radioname][i].checked) {
 3148:                     if (form.elements[radioname][i].value == '1') {
 3149:                        setvis = 1;
 3150:                        break;
 3151:                     }
 3152:                 }
 3153:             }
 3154:             for (var j=0; j<fieldsets.length; j++) {
 3155:                 if (setvis) {
 3156:                     fieldsets[j].style.display = 'block';
 3157:                 } else {
 3158:                     fieldsets[j].style.display = 'none';
 3159:                 }
 3160:             }
 3161:         }
 3162:     }
 3163:     return;
 3164: }
 3165: 
 3166: // ]]>
 3167: </script>
 3168: 
 3169: ENDSCRIPT
 3170: }
 3171: 
 3172: 
 3173: sub lti_javascript {
 3174:     my ($settings) = @_;
 3175:     my $togglejs = &lti_toggle_js();
 3176:     unless (ref($settings) eq 'HASH') {
 3177:         return $togglejs;
 3178:     }
 3179:     my (%ordered,$total,%jstext);
 3180:     $total = 0;
 3181:     foreach my $item (keys(%{$settings})) {
 3182:         if (ref($settings->{$item}) eq 'HASH') {
 3183:             my $num = $settings->{$item}{'order'};
 3184:             $ordered{$num} = $item;
 3185:         }
 3186:     }
 3187:     $total = scalar(keys(%{$settings}));
 3188:     my @jsarray = ();
 3189:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3190:         push(@jsarray,$ordered{$item});
 3191:     }
 3192:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3193:     return <<"ENDSCRIPT";
 3194: <script type="text/javascript">
 3195: // <![CDATA[
 3196: function reorderLTI(form,item) {
 3197:     var changedVal;
 3198: $jstext
 3199:     var newpos = 'lti_pos_add';
 3200:     var maxh = 1 + $total;
 3201:     var current = new Array;
 3202:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3203:     if (item == newpos) {
 3204:         changedVal = newitemVal;
 3205:     } else {
 3206:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3207:         current[newitemVal] = newpos;
 3208:     }
 3209:     for (var i=0; i<lti.length; i++) {
 3210:         var elementName = 'lti_pos_'+lti[i];
 3211:         if (elementName != item) {
 3212:             if (form.elements[elementName]) {
 3213:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3214:                 current[currVal] = elementName;
 3215:             }
 3216:         }
 3217:     }
 3218:     var oldVal;
 3219:     for (var j=0; j<maxh; j++) {
 3220:         if (current[j] == undefined) {
 3221:             oldVal = j;
 3222:         }
 3223:     }
 3224:     if (oldVal < changedVal) {
 3225:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3226:            var elementName = current[k];
 3227:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3228:         }
 3229:     } else {
 3230:         for (var k=changedVal; k<oldVal; k++) {
 3231:             var elementName = current[k];
 3232:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3233:         }
 3234:     }
 3235:     return;
 3236: }
 3237: // ]]>
 3238: </script>
 3239: 
 3240: $togglejs
 3241: 
 3242: ENDSCRIPT
 3243: }
 3244: 
 3245: sub lti_toggle_js {
 3246:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3247:                             localauth => 'Local auth argument',
 3248:                             krb       => 'Kerberos domain',
 3249:                          );
 3250:     return <<"ENDSCRIPT";
 3251: <script type="text/javascript">
 3252: // <![CDATA[
 3253: 
 3254: function toggleLTI(form,setting,item) {
 3255:     if (setting == 'requser') {
 3256:         var fieldsets = document.getElementsByClassName('ltioption_'+item);
 3257:         if (fieldsets.length) {
 3258:             var radioname = 'lti_'+setting+'_'+item;
 3259:             var num = form.elements[radioname].length;
 3260:             if (num) {
 3261:                 var setvis = '';
 3262:                 for (var i=0; i<num; i++) {
 3263:                     if (form.elements[radioname][i].checked) {
 3264:                         if (form.elements[radioname][i].value == '1') {
 3265:                            setvis = 1;
 3266:                            break;
 3267:                         }
 3268:                     }
 3269:                 }
 3270:                 for (var j=0; j<fieldsets.length; j++) {
 3271:                     if (setvis) {
 3272:                         fieldsets[j].style.display = 'block';
 3273:                     } else {
 3274:                         fieldsets[j].style.display = 'none';
 3275:                     }
 3276:                 }
 3277:             }
 3278:         }
 3279:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3280:         var radioname = '';
 3281:         var divid = '';
 3282:         if (setting == 'user') {
 3283:             radioname = 'lti_mapuser_'+item;
 3284:             divid = 'lti_userfield_'+item;
 3285:         } else if (setting == 'crs') {
 3286:             radioname = 'lti_mapcrs_'+item;
 3287:             divid = 'lti_crsfield_'+item;
 3288:         } else if (setting == 'callback') {
 3289:             radioname = 'lti_callback_'+item;
 3290:             divid = 'lti_callbackfield_'+item;
 3291:         } else {
 3292:             radioname = 'lti_passback_'+item;
 3293:             divid =  'lti_passback_'+item;
 3294:         }
 3295:         var num = form.elements[radioname].length;
 3296:         if (num) {
 3297:             var setvis = '';
 3298:             for (var i=0; i<num; i++) {
 3299:                if (form.elements[radioname][i].checked) {
 3300:                    if ((setting == 'passback') || (setting == 'callback')) {
 3301:                        if (form.elements[radioname][i].value == '1') {
 3302:                            if (document.getElementById(divid)) {
 3303:                                document.getElementById(divid).style.display = 'inline-block';
 3304:                            }
 3305:                            setvis = 1;
 3306:                            break;
 3307:                        }
 3308:                    } else {
 3309:                        if (form.elements[radioname][i].value == 'other') {
 3310:                            if (document.getElementById(divid)) {
 3311:                                document.getElementById(divid).style.display = 'inline-block';
 3312:                            }
 3313:                            setvis = 1;
 3314:                            break;
 3315:                        }
 3316:                    }
 3317:                } 
 3318:             }
 3319:             if (!setvis) {
 3320:                 if (document.getElementById(divid)) {
 3321:                     document.getElementById(divid).style.display = 'none';
 3322:                 }
 3323:             }
 3324:         }
 3325:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3326:         var numsec = form.elements['lti_crssec_'+item].length;
 3327:         if (numsec) {
 3328:             var setvis = '';
 3329:             for (var i=0; i<numsec; i++) {
 3330:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3331:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3332:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3333:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3334:                             setvis = 1;
 3335:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3336:                             if (numsrcsec) {
 3337:                                 var setsrcvis = '';
 3338:                                 for (var j=0; j<numsrcsec; j++) {
 3339:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3340:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3341:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3342:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3343:                                                 setsrcvis = 1;
 3344:                                             }
 3345:                                         }
 3346:                                     }
 3347:                                 }
 3348:                                 if (!setsrcvis) {
 3349:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3350:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3351:                                     }
 3352:                                 }
 3353:                             }
 3354:                         }
 3355:                     }
 3356:                 }
 3357:             }
 3358:             if (!setvis) {
 3359:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3360:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3361:                 }
 3362:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3363:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3364:                 }
 3365:             }
 3366:         }
 3367:     } else if (setting == 'lcauth') {
 3368:         var numauth = form.elements['lti_lcauth_'+item].length;
 3369:         if (numauth) {
 3370:             for (var i=0; i<numauth; i++) {
 3371:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3372:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3373:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3374:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3375:                         } else {
 3376:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3377:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3378:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3379:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3380:                                 } else {
 3381:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3382:                                 }
 3383:                             }
 3384:                         }
 3385:                     }
 3386:                 }
 3387:             }
 3388:         }
 3389:     } else if (setting == 'lcmenu') {
 3390:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3391:         var divid = 'lti_menufield_'+item;
 3392:         var setvis = '';
 3393:         for (var i=0; i<menus.length; i++) {
 3394:             var radioname = menus[i];  
 3395:             var num = form.elements[radioname].length;
 3396:             if (num) {
 3397:                 for (var j=0; j<num; j++) {
 3398:                     if (form.elements[radioname][j].checked) {
 3399:                         if (form.elements[radioname][j].value == '1') {
 3400:                             if (document.getElementById(divid)) {
 3401:                                 document.getElementById(divid).style.display = 'inline-block';
 3402:                             }
 3403:                             setvis = 1;
 3404:                             break;
 3405:                         }
 3406:                     }
 3407:                 }
 3408:             }
 3409:             if (setvis == 1) {
 3410:                 break;
 3411:             }
 3412:         }
 3413:         if (!setvis) {
 3414:             if (document.getElementById(divid)) {
 3415:                 document.getElementById(divid).style.display = 'none';
 3416:             }
 3417:         }
 3418:     }
 3419:     return;
 3420: }
 3421: // ]]>
 3422: </script>
 3423: 
 3424: ENDSCRIPT
 3425: }
 3426: 
 3427: sub autoupdate_javascript {
 3428:     return <<"ENDSCRIPT";
 3429: <script type="text/javascript">
 3430: // <![CDATA[
 3431: function toggleLastActiveDays(form) {
 3432:     var radioname = 'lastactive';
 3433:     var divid = 'lastactive_div';
 3434:     var num = form.elements[radioname].length;
 3435:     if (num) {
 3436:         var setvis = '';
 3437:         for (var i=0; i<num; i++) {
 3438:             if (form.elements[radioname][i].checked) {
 3439:                 if (form.elements[radioname][i].value == '1') {
 3440:                     if (document.getElementById(divid)) {
 3441:                         document.getElementById(divid).style.display = 'inline-block';
 3442:                     }
 3443:                     setvis = 1;
 3444:                 }
 3445:                 break;
 3446:             }
 3447:         }
 3448:         if (!setvis) {
 3449:             if (document.getElementById(divid)) {
 3450:                 document.getElementById(divid).style.display = 'none';
 3451:             }
 3452:         }
 3453:     }
 3454:     return;
 3455: }
 3456: // ]]>
 3457: </script>
 3458: 
 3459: ENDSCRIPT
 3460: }
 3461: 
 3462: sub saml_javascript {
 3463:     return <<"ENDSCRIPT";
 3464: <script type="text/javascript">
 3465: // <![CDATA[
 3466: function toggleSamlOptions(form,hostid) { 
 3467:     var radioname = 'saml_'+hostid;
 3468:     var tablecellon = 'samloptionson_'+hostid;
 3469:     var tablecelloff = 'samloptionsoff_'+hostid;
 3470:     var num = form.elements[radioname].length;
 3471:     if (num) {
 3472:         var setvis = ''; 
 3473:         for (var i=0; i<num; i++) {
 3474:             if (form.elements[radioname][i].checked) {
 3475:                 if (form.elements[radioname][i].value == '1') { 
 3476:                     if (document.getElementById(tablecellon)) {
 3477:                         document.getElementById(tablecellon).style.display='';
 3478:                     }
 3479:                     if (document.getElementById(tablecelloff)) {
 3480:                         document.getElementById(tablecelloff).style.display='none';
 3481:                     }
 3482:                     setvis = 1;
 3483:                 }
 3484:                 break;
 3485:             }
 3486:         }
 3487:         if (!setvis) {
 3488:             if (document.getElementById(tablecellon)) {
 3489:                 document.getElementById(tablecellon).style.display='none';
 3490:             }
 3491:             if (document.getElementById(tablecelloff)) {
 3492:                 document.getElementById(tablecelloff).style.display='';
 3493:             }
 3494:         }
 3495:     }
 3496:     return;
 3497: }
 3498: // ]]>
 3499: </script>
 3500: 
 3501: ENDSCRIPT
 3502: }
 3503: 
 3504: sub print_autoenroll {
 3505:     my ($dom,$settings,$rowtotal) = @_;
 3506:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3507:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,$failsafe);
 3508:     if (ref($settings) eq 'HASH') {
 3509:         if (exists($settings->{'run'})) {
 3510:             if ($settings->{'run'} eq '0') {
 3511:                 $runoff = ' checked="checked" ';
 3512:                 $runon = ' ';
 3513:             } else {
 3514:                 $runon = ' checked="checked" ';
 3515:                 $runoff = ' ';
 3516:             }
 3517:         } else {
 3518:             if ($autorun) {
 3519:                 $runon = ' checked="checked" ';
 3520:                 $runoff = ' ';
 3521:             } else {
 3522:                 $runoff = ' checked="checked" ';
 3523:                 $runon = ' ';
 3524:             }
 3525:         }
 3526:         if (exists($settings->{'co-owners'})) {
 3527:             if ($settings->{'co-owners'} eq '0') {
 3528:                 $coownersoff = ' checked="checked" ';
 3529:                 $coownerson = ' ';
 3530:             } else {
 3531:                 $coownerson = ' checked="checked" ';
 3532:                 $coownersoff = ' ';
 3533:             }
 3534:         } else {
 3535:             $coownersoff = ' checked="checked" ';
 3536:             $coownerson = ' ';
 3537:         }
 3538:         if (exists($settings->{'sender_domain'})) {
 3539:             $defdom = $settings->{'sender_domain'};
 3540:         }
 3541:         if (exists($settings->{'autofailsafe'})) {
 3542:             $failsafe = $settings->{'autofailsafe'};
 3543:         }
 3544:     } else {
 3545:         if ($autorun) {
 3546:             $runon = ' checked="checked" ';
 3547:             $runoff = ' ';
 3548:         } else {
 3549:             $runoff = ' checked="checked" ';
 3550:             $runon = ' ';
 3551:         }
 3552:     }
 3553:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3554:     my $notif_sender;
 3555:     if (ref($settings) eq 'HASH') {
 3556:         $notif_sender = $settings->{'sender_uname'};
 3557:     }
 3558:     my $datatable='<tr class="LC_odd_row">'.
 3559:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3560:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3561:                   '<input type="radio" name="autoenroll_run"'.
 3562:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3563:                   '<label><input type="radio" name="autoenroll_run"'.
 3564:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3565:                   '</tr><tr>'.
 3566:                   '<td>'.&mt('Notification messages - sender').
 3567:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3568:                   &mt('username').':&nbsp;'.
 3569:                   '<input type="text" name="sender_uname" value="'.
 3570:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3571:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3572:                   '<tr class="LC_odd_row">'.
 3573:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3574:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3575:                   '<input type="radio" name="autoassign_coowners"'.
 3576:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3577:                   '<label><input type="radio" name="autoassign_coowners"'.
 3578:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3579:                   '</tr><tr>'.
 3580:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3581:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 3582:                   '<input type="text" name="autoenroll_failsafe"'.
 3583:                   ' value="'.$failsafe.'" size="4" /></span></td></tr>';
 3584:     $$rowtotal += 4;
 3585:     return $datatable;
 3586: }
 3587: 
 3588: sub print_autoupdate {
 3589:     my ($position,$dom,$settings,$rowtotal) = @_;
 3590:     my ($enable,$datatable);
 3591:     if ($position eq 'top') {
 3592:         my %choices = &Apache::lonlocal::texthash (
 3593:                           run        => 'Auto-update active?',
 3594:                           classlists => 'Update information in classlists?',
 3595:                           unexpired  => 'Skip updates for users without active or future roles?',
 3596:                           lastactive => 'Skip updates for inactive users?',
 3597:         );
 3598:         my $itemcount = 0;
 3599:         my $updateon = ' ';
 3600:         my $updateoff = ' checked="checked" ';
 3601:         if (ref($settings) eq 'HASH') {
 3602:             if ($settings->{'run'} eq '1') {
 3603:                 $updateon = $updateoff;
 3604:                 $updateoff = ' ';
 3605:             }
 3606:         }
 3607:         $enable = '<tr class="LC_odd_row">'.
 3608:                   '<td>'.$choices{'run'}.'</td>'.
 3609:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3610:                   '<input type="radio" name="autoupdate_run"'.
 3611:                   $updateoff.' value="0" />'.&mt('No').'</label>&nbsp;'.
 3612:                   '<label><input type="radio" name="autoupdate_run"'.
 3613:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 3614:                   '</tr>';
 3615:         my @toggles = ('classlists','unexpired');
 3616:         my %defaultchecked = ('classlists' => 'off',
 3617:                               'unexpired'  => 'off'
 3618:                               );
 3619:         $$rowtotal ++;
 3620:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3621:                                                      \%choices,$itemcount,'','','left','no');
 3622:         $datatable = $enable.$datatable;
 3623:         $$rowtotal += $itemcount;
 3624:         my $lastactiveon = ' ';
 3625:         my $lastactiveoff = ' checked="checked" ';
 3626:         my $lastactivestyle = 'none';
 3627:         my $lastactivedays;
 3628:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 3629:         if (ref($settings) eq 'HASH') {
 3630:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 3631:                 $lastactiveon = $lastactiveoff;
 3632:                 $lastactiveoff = ' ';
 3633:                 $lastactivestyle = 'inline-block';
 3634:                 $lastactivedays = $settings->{'lastactive'};
 3635:             }
 3636:         }
 3637:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3638:         $datatable .= '<tr'.$css_class.'>'.
 3639:                       '<td>'.$choices{'lastactive'}.'</td>'.
 3640:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 3641:                       '<input type="radio" name="lastactive"'.
 3642:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3643:                       '&nbsp;<label>'.
 3644:                       '<input type="radio" name="lastactive"'.
 3645:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 3646:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 3647:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 3648:                           '<input type="text" size="5" name="lastactivedays" value="'.
 3649:                           $lastactivedays.'" />').
 3650:                       '</span></td>'.
 3651:                       '</tr>';
 3652:         $$rowtotal ++;
 3653:     } elsif ($position eq 'middle') {
 3654:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3655:         my $numinrow = 3;
 3656:         my $locknamesettings;
 3657:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3658:                                      $dom,$numinrow,$othertitle,
 3659:                                     'lockablenames',$rowtotal);
 3660:         $$rowtotal ++;
 3661:     } else {
 3662:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3663:         my @fields = ('lastname','firstname','middlename','generation',
 3664:                       'permanentemail','id');
 3665:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3666:         my $numrows = 0;
 3667:         if (ref($types) eq 'ARRAY') {
 3668:             if (@{$types} > 0) {
 3669:                 $datatable = 
 3670:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3671:                                          \@fields,$types,\$numrows);
 3672:                     $$rowtotal += @{$types}; 
 3673:             }
 3674:         }
 3675:         $datatable .= 
 3676:             &usertype_update_row($settings,{'default' => $othertitle},
 3677:                                  \%fieldtitles,\@fields,['default'],
 3678:                                  \$numrows);
 3679:         $$rowtotal ++;     
 3680:     }
 3681:     return $datatable;
 3682: }
 3683: 
 3684: sub print_autocreate {
 3685:     my ($dom,$settings,$rowtotal) = @_;
 3686:     my (%createon,%createoff,%currhash);
 3687:     my @types = ('xml','req');
 3688:     if (ref($settings) eq 'HASH') {
 3689:         foreach my $item (@types) {
 3690:             $createoff{$item} = ' checked="checked" ';
 3691:             $createon{$item} = ' ';
 3692:             if (exists($settings->{$item})) {
 3693:                 if ($settings->{$item}) {
 3694:                     $createon{$item} = ' checked="checked" ';
 3695:                     $createoff{$item} = ' ';
 3696:                 }
 3697:             }
 3698:         }
 3699:         if ($settings->{'xmldc'} ne '') {
 3700:             $currhash{$settings->{'xmldc'}} = 1;
 3701:         }
 3702:     } else {
 3703:         foreach my $item (@types) {
 3704:             $createoff{$item} = ' checked="checked" ';
 3705:             $createon{$item} = ' ';
 3706:         }
 3707:     }
 3708:     $$rowtotal += 2;
 3709:     my $numinrow = 2;
 3710:     my $datatable='<tr class="LC_odd_row">'.
 3711:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3712:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3713:                   '<input type="radio" name="autocreate_xml"'.
 3714:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3715:                   '<label><input type="radio" name="autocreate_xml"'.
 3716:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3717:                   '</td></tr><tr>'.
 3718:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3719:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3720:                   '<input type="radio" name="autocreate_req"'.
 3721:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3722:                   '<label><input type="radio" name="autocreate_req"'.
 3723:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3724:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3725:                                                    'autocreate_xmldc',%currhash);
 3726:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3727:     if ($numdc > 1) {
 3728:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3729:                       '</td><td class="LC_left_item">';
 3730:     } else {
 3731:         $datatable .= &mt('Course creation processed as:').
 3732:                       '</td><td class="LC_right_item">';
 3733:     }
 3734:     $datatable .= $dctable.'</td></tr>';
 3735:     $$rowtotal += $rows;
 3736:     return $datatable;
 3737: }
 3738: 
 3739: sub print_directorysrch {
 3740:     my ($position,$dom,$settings,$rowtotal) = @_;
 3741:     my $datatable;
 3742:     if ($position eq 'top') {
 3743:         my $instsrchon = ' ';
 3744:         my $instsrchoff = ' checked="checked" ';
 3745:         my ($exacton,$containson,$beginson);
 3746:         my $instlocalon = ' ';
 3747:         my $instlocaloff = ' checked="checked" ';
 3748:         if (ref($settings) eq 'HASH') {
 3749:             if ($settings->{'available'} eq '1') {
 3750:                 $instsrchon = $instsrchoff;
 3751:                 $instsrchoff = ' ';
 3752:             }
 3753:             if ($settings->{'localonly'} eq '1') {
 3754:                 $instlocalon = $instlocaloff;
 3755:                 $instlocaloff = ' ';
 3756:             }
 3757:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3758:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3759:                     if ($type eq 'exact') {
 3760:                         $exacton = ' checked="checked" ';
 3761:                     } elsif ($type eq 'contains') {
 3762:                         $containson = ' checked="checked" ';
 3763:                     } elsif ($type eq 'begins') {
 3764:                         $beginson = ' checked="checked" ';
 3765:                     }
 3766:                 }
 3767:             } else {
 3768:                 if ($settings->{'searchtypes'} eq 'exact') {
 3769:                     $exacton = ' checked="checked" ';
 3770:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 3771:                     $containson = ' checked="checked" ';
 3772:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 3773:                     $exacton = ' checked="checked" ';
 3774:                     $containson = ' checked="checked" ';
 3775:                 }
 3776:             }
 3777:         }
 3778:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 3779:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3780: 
 3781:         my $numinrow = 4;
 3782:         my $cansrchrow = 0;
 3783:         $datatable='<tr class="LC_odd_row">'.
 3784:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 3785:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3786:                    '<input type="radio" name="dirsrch_available"'.
 3787:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3788:                    '<label><input type="radio" name="dirsrch_available"'.
 3789:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3790:                    '</tr><tr>'.
 3791:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 3792:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3793:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 3794:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3795:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 3796:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3797:                    '</tr>';
 3798:         $$rowtotal += 2;
 3799:         if (ref($usertypes) eq 'HASH') {
 3800:             if (keys(%{$usertypes}) > 0) {
 3801:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3802:                                              $numinrow,$othertitle,'cansearch',
 3803:                                              $rowtotal);
 3804:                 $cansrchrow = 1;
 3805:             }
 3806:         }
 3807:         if ($cansrchrow) {
 3808:             $$rowtotal ++;
 3809:             $datatable .= '<tr>';
 3810:         } else {
 3811:             $datatable .= '<tr class="LC_odd_row">';
 3812:         }
 3813:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 3814:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 3815:         foreach my $title (@{$titleorder}) {
 3816:             if (defined($searchtitles->{$title})) {
 3817:                 my $check = ' ';
 3818:                 if (ref($settings) eq 'HASH') {
 3819:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 3820:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 3821:                             $check = ' checked="checked" ';
 3822:                         }
 3823:                     }
 3824:                 }
 3825:                 $datatable .= '<td class="LC_left_item">'.
 3826:                               '<span class="LC_nobreak"><label>'.
 3827:                               '<input type="checkbox" name="searchby" '.
 3828:                               'value="'.$title.'"'.$check.'/>'.
 3829:                               $searchtitles->{$title}.'</label></span></td>';
 3830:             }
 3831:         }
 3832:         $datatable .= '</tr></table></td></tr>';
 3833:         $$rowtotal ++;
 3834:         if ($cansrchrow) {
 3835:             $datatable .= '<tr class="LC_odd_row">';
 3836:         } else {
 3837:             $datatable .= '<tr>';
 3838:         }
 3839:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 3840:                       '<td class="LC_left_item" colspan="2">'.
 3841:                       '<span class="LC_nobreak"><label>'.
 3842:                       '<input type="checkbox" name="searchtypes" '.
 3843:                       $exacton.' value="exact" />'.&mt('Exact match').
 3844:                       '</label>&nbsp;'.
 3845:                       '<label><input type="checkbox" name="searchtypes" '.
 3846:                       $beginson.' value="begins" />'.&mt('Begins with').
 3847:                       '</label>&nbsp;'.
 3848:                       '<label><input type="checkbox" name="searchtypes" '.
 3849:                       $containson.' value="contains" />'.&mt('Contains').
 3850:                       '</label></span></td></tr>';
 3851:         $$rowtotal ++;
 3852:     } else {
 3853:         my $domsrchon = ' checked="checked" ';
 3854:         my $domsrchoff = ' ';
 3855:         my $domlocalon = ' ';
 3856:         my $domlocaloff = ' checked="checked" ';
 3857:         if (ref($settings) eq 'HASH') {
 3858:             if ($settings->{'lclocalonly'} eq '1') {
 3859:                 $domlocalon = $domlocaloff;
 3860:                 $domlocaloff = ' ';
 3861:             }
 3862:             if ($settings->{'lcavailable'} eq '0') {
 3863:                 $domsrchoff = $domsrchon;
 3864:                 $domsrchon = ' ';
 3865:             }
 3866:         }
 3867:         $datatable='<tr class="LC_odd_row">'.
 3868:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 3869:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3870:                       '<input type="radio" name="dirsrch_domavailable"'.
 3871:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3872:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 3873:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3874:                       '</tr><tr>'.
 3875:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 3876:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3877:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 3878:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3879:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 3880:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3881:                       '</tr>';
 3882:         $$rowtotal += 2;
 3883:     }
 3884:     return $datatable;
 3885: }
 3886: 
 3887: sub print_contacts {
 3888:     my ($position,$dom,$settings,$rowtotal) = @_;
 3889:     my $datatable;
 3890:     my @contacts = ('adminemail','supportemail');
 3891:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 3892:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 3893:     if ($position eq 'top') {
 3894:         if (ref($settings) eq 'HASH') {
 3895:             foreach my $item (@contacts) {
 3896:                 if (exists($settings->{$item})) {
 3897:                     $to{$item} = $settings->{$item};
 3898:                 }
 3899:             }
 3900:         }
 3901:     } elsif ($position eq 'middle') {
 3902:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 3903:                      'updatesmail','idconflictsmail','hostipmail');
 3904:         foreach my $type (@mailings) {
 3905:             $otheremails{$type} = '';
 3906:         }
 3907:     } elsif ($position eq 'lower') {
 3908:         if (ref($settings) eq 'HASH') {
 3909:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 3910:                 %lonstatus = %{$settings->{'lonstatus'}};
 3911:             }
 3912:         }
 3913:     } else {
 3914:         @mailings = ('helpdeskmail','otherdomsmail');
 3915:         foreach my $type (@mailings) {
 3916:             $otheremails{$type} = '';
 3917:         }
 3918:         $bccemails{'helpdeskmail'} = '';
 3919:         $bccemails{'otherdomsmail'} = '';
 3920:         $includestr{'helpdeskmail'} = '';
 3921:         $includestr{'otherdomsmail'} = '';
 3922:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 3923:     }
 3924:     if (ref($settings) eq 'HASH') {
 3925:         unless (($position eq 'top') || ($position eq 'lower')) {
 3926:             foreach my $type (@mailings) {
 3927:                 if (exists($settings->{$type})) {
 3928:                     if (ref($settings->{$type}) eq 'HASH') {
 3929:                         foreach my $item (@contacts) {
 3930:                             if ($settings->{$type}{$item}) {
 3931:                                 $checked{$type}{$item} = ' checked="checked" ';
 3932:                             }
 3933:                         }
 3934:                         $otheremails{$type} = $settings->{$type}{'others'};
 3935:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3936:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 3937:                             if ($settings->{$type}{'include'} ne '') {
 3938:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3939:                                 $includestr{$type} = &unescape($includestr{$type});
 3940:                             }
 3941:                         }
 3942:                     }
 3943:                 } elsif ($type eq 'lonstatusmail') {
 3944:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3945:                 }
 3946:             }
 3947:         }
 3948:         if ($position eq 'bottom') {
 3949:             foreach my $type (@mailings) {
 3950:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 3951:                 if ($settings->{$type}{'include'} ne '') {
 3952:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3953:                     $includestr{$type} = &unescape($includestr{$type});
 3954:                 }
 3955:             }
 3956:             if (ref($settings->{'helpform'}) eq 'HASH') {
 3957:                 if (ref($fields) eq 'ARRAY') {
 3958:                     foreach my $field (@{$fields}) {
 3959:                         $currfield{$field} = $settings->{'helpform'}{$field};
 3960:                     }
 3961:                 }
 3962:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 3963:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 3964:                 } else {
 3965:                     $maxsize = '1.0';
 3966:                 }
 3967:             } else {
 3968:                 if (ref($fields) eq 'ARRAY') {
 3969:                     foreach my $field (@{$fields}) {
 3970:                         $currfield{$field} = 'yes';
 3971:                     }
 3972:                 }
 3973:                 $maxsize = '1.0';
 3974:             }
 3975:         }
 3976:     } else {
 3977:         if ($position eq 'top') {
 3978:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 3979:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 3980:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 3981:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 3982:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3983:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 3984:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 3985:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 3986:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 3987:         } elsif ($position eq 'bottom') {
 3988:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 3989:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 3990:             if (ref($fields) eq 'ARRAY') {
 3991:                 foreach my $field (@{$fields}) {
 3992:                     $currfield{$field} = 'yes';
 3993:                 }
 3994:             }
 3995:             $maxsize = '1.0';
 3996:         }
 3997:     }
 3998:     my ($titles,$short_titles) = &contact_titles();
 3999:     my $rownum = 0;
 4000:     my $css_class;
 4001:     if ($position eq 'top') {
 4002:         foreach my $item (@contacts) {
 4003:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4004:             $datatable .= '<tr'.$css_class.'>'. 
 4005:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 4006:                           '</span></td><td class="LC_right_item">'.
 4007:                           '<input type="text" name="'.$item.'" value="'.
 4008:                           $to{$item}.'" /></td></tr>';
 4009:             $rownum ++;
 4010:         }
 4011:     } elsif ($position eq 'bottom') {
 4012:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4013:         $datatable .= '<tr'.$css_class.'>'.
 4014:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 4015:                       &mt('(e-mail, subject, and description always shown)').
 4016:                       '</td><td class="LC_left_item">';
 4017:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 4018:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 4019:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 4020:             foreach my $field (@{$fields}) {
 4021:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 4022:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 4023:                     $datatable .= ' '.&mt('(logged-in users)');
 4024:                 }
 4025:                 $datatable .='</td><td>';
 4026:                 my $clickaction;
 4027:                 if ($field eq 'screenshot') {
 4028:                     $clickaction = ' onclick="screenshotSize(this);"';
 4029:                 }
 4030:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4031:                     foreach my $option (@{$possoptions->{$field}}) {
 4032:                         my $checked;
 4033:                         if ($currfield{$field} eq $option) {
 4034:                             $checked = ' checked="checked"';
 4035:                         }
 4036:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4037:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4038:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4039:                                       '</label></span>'.('&nbsp;'x2);
 4040:                     }
 4041:                 }
 4042:                 if ($field eq 'screenshot') {
 4043:                     my $display;
 4044:                     if ($currfield{$field} eq 'no') {
 4045:                         $display = ' style="display:none"';
 4046:                     }
 4047:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4048:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4049:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4050:                 }
 4051:                 $datatable .= '</td></tr>';
 4052:             }
 4053:             $datatable .= '</table>';
 4054:         }
 4055:         $datatable .= '</td></tr>'."\n";
 4056:         $rownum ++;
 4057:     }
 4058:     unless (($position eq 'top') || ($position eq 'lower')) {
 4059:         foreach my $type (@mailings) {
 4060:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4061:             $datatable .= '<tr'.$css_class.'>'.
 4062:                           '<td><span class="LC_nobreak">'.
 4063:                           $titles->{$type}.': </span></td>'.
 4064:                           '<td class="LC_left_item">';
 4065:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4066:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4067:             }
 4068:             $datatable .= '<span class="LC_nobreak">';
 4069:             foreach my $item (@contacts) {
 4070:                 $datatable .= '<label>'.
 4071:                               '<input type="checkbox" name="'.$type.'"'.
 4072:                               $checked{$type}{$item}.
 4073:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4074:                               '</label>&nbsp;';
 4075:             }
 4076:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4077:                           '<input type="text" name="'.$type.'_others" '.
 4078:                           'value="'.$otheremails{$type}.'"  />';
 4079:             my %locchecked;
 4080:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4081:                 foreach my $loc ('s','b') {
 4082:                     if ($includeloc{$type} eq $loc) {
 4083:                         $locchecked{$loc} = ' checked="checked"';
 4084:                         last;
 4085:                     }
 4086:                 }
 4087:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4088:                               '<input type="text" name="'.$type.'_bcc" '.
 4089:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4090:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4091:                               &mt('Text automatically added to e-mail:').' '.
 4092:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4093:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4094:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4095:                               ('&nbsp;'x2).
 4096:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4097:                               '</span></fieldset>';
 4098:             }
 4099:             $datatable .= '</td></tr>'."\n";
 4100:             $rownum ++;
 4101:         }
 4102:     }
 4103:     if ($position eq 'middle') {
 4104:         my %choices;
 4105:         my $corelink = &core_link_msu();
 4106:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4107:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4108:                                         $corelink);
 4109:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4110:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4111:         my %defaultchecked = ('reporterrors'  => 'on',
 4112:                               'reportupdates' => 'on',
 4113:                               'reportstatus'  => 'on');
 4114:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4115:                                                    \%choices,$rownum);
 4116:         $datatable .= $reports;
 4117:     } elsif ($position eq 'lower') {
 4118:         my (%current,%excluded,%weights);
 4119:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4120:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4121:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4122:         } else {
 4123:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4124:         }
 4125:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4126:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4127:         } else {
 4128:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4129:         }
 4130:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4131:             foreach my $type ('E','W','N','U') {
 4132:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4133:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4134:                 } else {
 4135:                     $weights{$type} = $defaults->{$type};
 4136:                 }
 4137:             }
 4138:         } else {
 4139:             foreach my $type ('E','W','N','U') {
 4140:                 $weights{$type} = $defaults->{$type};
 4141:             }
 4142:         }
 4143:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4144:             if (@{$lonstatus{'excluded'}} > 0) {
 4145:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4146:             }
 4147:         }
 4148:         foreach my $item ('errorthreshold','errorsysmail') { 
 4149:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4150:             $datatable .= '<tr'.$css_class.'>'.
 4151:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4152:                           $titles->{$item}.
 4153:                           '</span></td><td class="LC_left_item">'.
 4154:                           '<input type="text" name="'.$item.'" value="'.
 4155:                           $current{$item}.'" size="5" /></td></tr>';
 4156:             $rownum ++;
 4157:         }
 4158:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4159:         $datatable .= '<tr'.$css_class.'>'.
 4160:                       '<td class="LC_left_item">'.
 4161:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4162:                       '</span></td><td class="LC_left_item"><table><tr>';
 4163:         foreach my $type ('E','W','N','U') {
 4164:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4165:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4166:                           $weights{$type}.'" size="5" /></td>';
 4167:         }
 4168:         $datatable .= '</tr></table></tr>';
 4169:         $rownum ++;
 4170:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4171:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4172:                       $titles->{'errorexcluded'}.'</td>'.
 4173:                       '<td class="LC_left_item"><table>';
 4174:         my $numinrow = 4;
 4175:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4176:         for (my $i=0; $i<@ids; $i++) {
 4177:             my $rem = $i%($numinrow);
 4178:             if ($rem == 0) {
 4179:                 if ($i > 0) {
 4180:                     $datatable .= '</tr>';
 4181:                 }
 4182:                 $datatable .= '<tr>';
 4183:             }
 4184:             my $check;
 4185:             if ($excluded{$ids[$i]}) {
 4186:                 $check = ' checked="checked" ';
 4187:             }
 4188:             $datatable .= '<td class="LC_left_item">'.
 4189:                           '<span class="LC_nobreak"><label>'.
 4190:                           '<input type="checkbox" name="errorexcluded" '.
 4191:                           'value="'.$ids[$i].'"'.$check.' />'.
 4192:                           $ids[$i].'</label></span></td>';
 4193:         }
 4194:         my $colsleft = $numinrow - @ids%($numinrow);
 4195:         if ($colsleft > 1 ) {
 4196:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4197:                           '&nbsp;</td>';
 4198:         } elsif ($colsleft == 1) {
 4199:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4200:         }
 4201:         $datatable .= '</tr></table></td></tr>';
 4202:         $rownum ++;
 4203:     } elsif ($position eq 'bottom') {
 4204:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4205:         my (@posstypes,%usertypeshash);
 4206:         if (ref($types) eq 'ARRAY') {
 4207:             @posstypes = @{$types};
 4208:         }
 4209:         if (@posstypes) {
 4210:             if (ref($usertypes) eq 'HASH') {
 4211:                 %usertypeshash = %{$usertypes};
 4212:             }
 4213:             my @overridden;
 4214:             my $numinrow = 4;
 4215:             if (ref($settings) eq 'HASH') {
 4216:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4217:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4218:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4219:                             push(@overridden,$key);
 4220:                             foreach my $item (@contacts) {
 4221:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4222:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4223:                                 }
 4224:                             }
 4225:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4226:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4227:                             $includeloc{'override_'.$key} = '';
 4228:                             $includestr{'override_'.$key} = '';
 4229:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4230:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 4231:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4232:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4233:                             }
 4234:                         }
 4235:                     }
 4236:                 }
 4237:             }
 4238:             my $customclass = 'LC_helpdesk_override';
 4239:             my $optionsprefix = 'LC_options_helpdesk_';
 4240: 
 4241:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4242:  
 4243:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4244:                                          $numinrow,$othertitle,'overrides',
 4245:                                          \$rownum,$onclicktypes,$customclass);
 4246:             $rownum ++;
 4247:             $usertypeshash{'default'} = $othertitle;
 4248:             foreach my $status (@posstypes) {
 4249:                 my $css_class;
 4250:                 if ($rownum%2) {
 4251:                     $css_class = 'LC_odd_row ';
 4252:                 }
 4253:                 $css_class .= $customclass;
 4254:                 my $rowid = $optionsprefix.$status;
 4255:                 my $hidden = 1;
 4256:                 my $currstyle = 'display:none';
 4257:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4258:                     $currstyle = 'display:table-row';
 4259:                     $hidden = 0;
 4260:                 }
 4261:                 my $key = 'override_'.$status;
 4262:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4263:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4264:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4265:                                                   \@contacts,$short_titles);
 4266:                 unless ($hidden) {
 4267:                     $rownum ++;
 4268:                 }
 4269:             }
 4270:         }
 4271:     }
 4272:     $$rowtotal += $rownum;
 4273:     return $datatable;
 4274: }
 4275: 
 4276: sub core_link_msu {
 4277:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4278:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4279: }
 4280: 
 4281: sub overridden_helpdesk {
 4282:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4283:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4284:     my $class = 'LC_left_item';
 4285:     if ($css_class) {
 4286:         $css_class = ' class="'.$css_class.'"';
 4287:     }
 4288:     if ($rowid) {
 4289:         $rowid = ' id="'.$rowid.'"';
 4290:     }
 4291:     if ($rowstyle) {
 4292:         $rowstyle = ' style="'.$rowstyle.'"';
 4293:     }
 4294:     my ($output,$description);
 4295:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4296:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4297:               "<td>$description</td>\n".
 4298:               '<td class="'.$class.'" colspan="2">'.
 4299:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4300:               '<span class="LC_nobreak">';
 4301:     if (ref($contacts) eq 'ARRAY') {
 4302:         foreach my $item (@{$contacts}) {
 4303:             my $check;
 4304:             if (ref($checked) eq 'HASH') {
 4305:                $check = $checked->{$item};
 4306:             }
 4307:             my $title;
 4308:             if (ref($short_titles) eq 'HASH') {
 4309:                 $title = $short_titles->{$item}; 
 4310:             }
 4311:             $output .= '<label>'.
 4312:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4313:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4314:         }
 4315:     }
 4316:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4317:                '<input type="text" name="override_'.$type.'_others" '.
 4318:                'value="'.$otheremails.'"  />';
 4319:     my %locchecked;
 4320:     foreach my $loc ('s','b') {
 4321:         if ($includeloc eq $loc) {
 4322:             $locchecked{$loc} = ' checked="checked"';
 4323:             last;
 4324:         }
 4325:     }
 4326:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4327:                '<input type="text" name="override_'.$type.'_bcc" '.
 4328:                'value="'.$bccemails.'"  /></fieldset>'.
 4329:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4330:                &mt('Text automatically added to e-mail:').' '.
 4331:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4332:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4333:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4334:                ('&nbsp;'x2).
 4335:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4336:                '</span></fieldset>'.
 4337:                '</td></tr>'."\n";
 4338:     return $output;
 4339: }
 4340: 
 4341: sub contacts_javascript {
 4342:     return <<"ENDSCRIPT";
 4343: 
 4344: <script type="text/javascript">
 4345: // <![CDATA[
 4346: 
 4347: function screenshotSize(field) {
 4348:     if (document.getElementById('help_screenshotsize')) {
 4349:         if (field.value == 'no') {
 4350:             document.getElementById('help_screenshotsize').style.display="none";
 4351:         } else {
 4352:             document.getElementById('help_screenshotsize').style.display="";
 4353:         }
 4354:     }
 4355:     return;
 4356: }
 4357: 
 4358: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4359:     if (form.elements[checkbox].length != undefined) {
 4360:         var count = 0;
 4361:         if (docount) {
 4362:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4363:                 if (form.elements[checkbox][i].checked) {
 4364:                     count ++;
 4365:                 }
 4366:             }
 4367:         }
 4368:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4369:             var type = form.elements[checkbox][i].value;
 4370:             if (document.getElementById(prefix+type)) {
 4371:                 if (form.elements[checkbox][i].checked) {
 4372:                     document.getElementById(prefix+type).style.display = 'table-row';
 4373:                     if (count % 2 == 1) {
 4374:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4375:                     } else {
 4376:                         document.getElementById(prefix+type).className = target;
 4377:                     }
 4378:                     count ++;
 4379:                 } else {
 4380:                     document.getElementById(prefix+type).style.display = 'none';
 4381:                 }
 4382:             }
 4383:         }
 4384:     }
 4385:     return;
 4386: }
 4387: 
 4388: 
 4389: // ]]>
 4390: </script>
 4391: 
 4392: ENDSCRIPT
 4393: }
 4394: 
 4395: sub print_helpsettings {
 4396:     my ($position,$dom,$settings,$rowtotal) = @_;
 4397:     my $confname = $dom.'-domainconfig';
 4398:     my $formname = 'display';
 4399:     my ($datatable,$itemcount);
 4400:     if ($position eq 'top') {
 4401:         $itemcount = 1;
 4402:         my (%choices,%defaultchecked,@toggles);
 4403:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4404:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4405:                                      &mt('LON-CAPA bug tracker'),600,500));
 4406:         %defaultchecked = ('submitbugs' => 'on');
 4407:         @toggles = ('submitbugs');
 4408:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4409:                                                      \%choices,$itemcount);
 4410:         $$rowtotal ++;
 4411:     } else {
 4412:         my $css_class;
 4413:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4414:         my (%customroles,%ordered,%current);
 4415:         if (ref($settings) eq 'HASH') {
 4416:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4417:                 %current = %{$settings->{'adhoc'}};
 4418:             }
 4419:         }
 4420:         my $count = 0;
 4421:         foreach my $key (sort(keys(%existing))) {
 4422:             if ($key=~/^rolesdef\_(\w+)$/) {
 4423:                 my $rolename = $1;
 4424:                 my (%privs,$order);
 4425:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4426:                 $customroles{$rolename} = \%privs;
 4427:                 if (ref($current{$rolename}) eq 'HASH') {
 4428:                     $order = $current{$rolename}{'order'};
 4429:                 }
 4430:                 if ($order eq '') {
 4431:                     $order = $count;
 4432:                 }
 4433:                 $ordered{$order} = $rolename;
 4434:                 $count++;
 4435:             }
 4436:         }
 4437:         my $maxnum = scalar(keys(%ordered));
 4438:         my @roles_by_num = ();
 4439:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4440:             push(@roles_by_num,$item);
 4441:         }
 4442:         my $context = 'domprefs';
 4443:         my $crstype = 'Course';
 4444:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4445:         my @accesstypes = ('all','dh','da','none');
 4446:         my ($numstatustypes,@jsarray);
 4447:         if (ref($types) eq 'ARRAY') {
 4448:             if (@{$types} > 0) {
 4449:                 $numstatustypes = scalar(@{$types});
 4450:                 push(@accesstypes,'status');
 4451:                 @jsarray = ('bystatus');
 4452:             }
 4453:         }
 4454:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4455:         if (keys(%domhelpdesk)) {
 4456:             push(@accesstypes,('inc','exc'));
 4457:             push(@jsarray,('notinc','notexc'));
 4458:         }
 4459:         my $hiddenstr = join("','",@jsarray);
 4460:         my $context = 'domprefs';
 4461:         my $crstype = 'Course';
 4462:         my $prefix = 'helproles_';
 4463:         my $add_class = 'LC_hidden';
 4464:         foreach my $num (@roles_by_num) {
 4465:             my $role = $ordered{$num};
 4466:             my ($desc,$access,@statuses);
 4467:             if (ref($current{$role}) eq 'HASH') {
 4468:                 $desc = $current{$role}{'desc'};
 4469:                 $access = $current{$role}{'access'};
 4470:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4471:                     @statuses = @{$current{$role}{'insttypes'}};
 4472:                 }
 4473:             }
 4474:             if ($desc eq '') {
 4475:                 $desc = $role;
 4476:             }
 4477:             my $identifier = 'custhelp'.$num;
 4478:             my %full=();
 4479:             my %levels= (
 4480:                          course => {},
 4481:                          domain => {},
 4482:                          system => {},
 4483:                         );
 4484:             my %levelscurrent=(
 4485:                                course => {},
 4486:                                domain => {},
 4487:                                system => {},
 4488:                               );
 4489:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4490:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4491:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4492:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4493:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 4494:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4495:             for (my $k=0; $k<=$maxnum; $k++) {
 4496:                 my $vpos = $k+1;
 4497:                 my $selstr;
 4498:                 if ($k == $num) {
 4499:                     $selstr = ' selected="selected" ';
 4500:                 }
 4501:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4502:             }
 4503:             $datatable .= '</select>'.('&nbsp;'x2).
 4504:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4505:                           '</td>'.
 4506:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4507:                           &mt('Name shown to users:').
 4508:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4509:                           '</fieldset>'.
 4510:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4511:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4512:                           '<fieldset>'.
 4513:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4514:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4515:                                                                    \%levelscurrent,$identifier,
 4516:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4517:                           '</fieldset></td>';
 4518:             $itemcount ++;
 4519:         }
 4520:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4521:         my $newcust = 'custhelp'.$count;
 4522:         my (%privs,%levelscurrent);
 4523:         my %full=();
 4524:         my %levels= (
 4525:                      course => {},
 4526:                      domain => {},
 4527:                      system => {},
 4528:                     );
 4529:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4530:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4531:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4532:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 4533:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4534:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4535:         for (my $k=0; $k<$maxnum+1; $k++) {
 4536:             my $vpos = $k+1;
 4537:             my $selstr;
 4538:             if ($k == $maxnum) {
 4539:                 $selstr = ' selected="selected" ';
 4540:             }
 4541:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4542:         }
 4543:         $datatable .= '</select>&nbsp;'."\n".
 4544:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4545:                       '</label></span></td>'.
 4546:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4547:                       '<span class="LC_nobreak">'.
 4548:                       &mt('Internal name:').
 4549:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4550:                       '</span>'.('&nbsp;'x4).
 4551:                       '<span class="LC_nobreak">'.
 4552:                       &mt('Name shown to users:').
 4553:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4554:                       '</span></fieldset>'.
 4555:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4556:                                              $usertypes,$types,\%domhelpdesk).
 4557:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4558:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4559:                                                                 \@templateroles,$newcust).
 4560:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4561:                                                                \%levelscurrent,$newcust).
 4562:                       '</fieldset>'.
 4563:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4564:                       '</td></tr>';
 4565:         $count ++;
 4566:         $$rowtotal += $count;
 4567:     }
 4568:     return $datatable;
 4569: }
 4570: 
 4571: sub adhocbutton {
 4572:     my ($prefix,$num,$field,$visibility) = @_;
 4573:     my %lt = &Apache::lonlocal::texthash(
 4574:                                           show => 'Show details',
 4575:                                           hide => 'Hide details',
 4576:                                         );
 4577:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4578:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4579:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4580:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4581: }
 4582: 
 4583: sub helpsettings_javascript {
 4584:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4585:     return unless(ref($roles_by_num) eq 'ARRAY');
 4586:     my %html_js_lt = &Apache::lonlocal::texthash(
 4587:                                           show => 'Show details',
 4588:                                           hide => 'Hide details',
 4589:                                         );
 4590:     &html_escape(\%html_js_lt);
 4591:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4592:     return <<"ENDSCRIPT";
 4593: <script type="text/javascript">
 4594: // <![CDATA[
 4595: 
 4596: function reorderHelpRoles(form,item) {
 4597:     var changedVal;
 4598: $jstext
 4599:     var newpos = 'helproles_${total}_pos';
 4600:     var maxh = 1 + $total;
 4601:     var current = new Array();
 4602:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4603:     if (item == newpos) {
 4604:         changedVal = newitemVal;
 4605:     } else {
 4606:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4607:         current[newitemVal] = newpos;
 4608:     }
 4609:     for (var i=0; i<helproles.length; i++) {
 4610:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4611:         if (elementName != item) {
 4612:             if (form.elements[elementName]) {
 4613:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4614:                 current[currVal] = elementName;
 4615:             }
 4616:         }
 4617:     }
 4618:     var oldVal;
 4619:     for (var j=0; j<maxh; j++) {
 4620:         if (current[j] == undefined) {
 4621:             oldVal = j;
 4622:         }
 4623:     }
 4624:     if (oldVal < changedVal) {
 4625:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4626:            var elementName = current[k];
 4627:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4628:         }
 4629:     } else {
 4630:         for (var k=changedVal; k<oldVal; k++) {
 4631:             var elementName = current[k];
 4632:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4633:         }
 4634:     }
 4635:     return;
 4636: }
 4637: 
 4638: function helpdeskAccess(num) {
 4639:     var curraccess = null;
 4640:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4641:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4642:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4643:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4644:             }
 4645:         }
 4646:     }
 4647:     var shown = Array();
 4648:     var hidden = Array();
 4649:     if (curraccess == 'none') {
 4650:         hidden = Array('$hiddenstr');
 4651:     } else {
 4652:         if (curraccess == 'status') {
 4653:             shown = Array('bystatus');
 4654:             hidden = Array('notinc','notexc');
 4655:         } else {
 4656:             if (curraccess == 'exc') {
 4657:                 shown = Array('notexc');
 4658:                 hidden = Array('notinc','bystatus');
 4659:             }
 4660:             if (curraccess == 'inc') {
 4661:                 shown = Array('notinc');
 4662:                 hidden = Array('notexc','bystatus');
 4663:             }
 4664:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4665:                 hidden = Array('notinc','notexc','bystatus');
 4666:             }
 4667:         }
 4668:     }
 4669:     if (hidden.length > 0) {
 4670:         for (var i=0; i<hidden.length; i++) {
 4671:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4672:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4673:             }
 4674:         }
 4675:     }
 4676:     if (shown.length > 0) {
 4677:         for (var i=0; i<shown.length; i++) {
 4678:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4679:                 if (shown[i] == 'privs') {
 4680:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4681:                 } else {
 4682:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4683:                 }
 4684:             }
 4685:         }
 4686:     }
 4687:     return;
 4688: }
 4689: 
 4690: function toggleHelpdeskItem(num,field) {
 4691:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4692:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4693:             document.getElementById('helproles_'+num+'_'+field).className =
 4694:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4695:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4696:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4697:             }
 4698:         } else {
 4699:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4700:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4701:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4702:             }
 4703:         }
 4704:     }
 4705:     return;
 4706: }
 4707: 
 4708: // ]]>
 4709: </script>
 4710: 
 4711: ENDSCRIPT
 4712: }
 4713: 
 4714: sub helpdeskroles_access {
 4715:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4716:         $usertypes,$types,$domhelpdesk) = @_;
 4717:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4718:     my %lt = &Apache::lonlocal::texthash(
 4719:                     'rou'    => 'Role usage',
 4720:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4721:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4722:                     'dh'     => 'All with domain helpdesk role',
 4723:                     'da'     => 'All with domain helpdesk assistant role',
 4724:                     'none'   => 'None',
 4725:                     'status' => 'Determined based on institutional status',
 4726:                     'inc'    => 'Include all, but exclude specific personnel',
 4727:                     'exc'    => 'Exclude all, but include specific personnel',
 4728:                   );
 4729:     my %usecheck = (
 4730:                      all => ' checked="checked"',
 4731:                    );
 4732:     my %displaydiv = (
 4733:                       status => 'none',
 4734:                       inc    => 'none',
 4735:                       exc    => 'none',
 4736:                       priv   => 'block',
 4737:                      );
 4738:     my $output;
 4739:     if (ref($current) eq 'HASH') {
 4740:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4741:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4742:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4743:                 delete($usecheck{'all'});
 4744:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4745:                     my $access = $1;
 4746:                     $displaydiv{$access} = 'inline';
 4747:                 } elsif ($current->{access} eq 'none') {
 4748:                     $displaydiv{'priv'} = 'none';
 4749:                 }
 4750:             }
 4751:         }
 4752:     }
 4753:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4754:               '<p>'.$lt{'whi'}.'</p>';
 4755:     foreach my $access (@{$accesstypes}) {
 4756:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4757:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4758:                    $lt{$access}.'</label>';
 4759:         if ($access eq 'status') {
 4760:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4761:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4762:                                                                  $othertitle,$usertypes,$types).
 4763:                        '</div>';
 4764:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4765:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4766:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4767:                        '</div>';
 4768:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4769:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 4770:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4771:                        '</div>';
 4772:         }
 4773:         $output .= '</p>';
 4774:     }
 4775:     $output .= '</fieldset>';
 4776:     return $output;
 4777: }
 4778: 
 4779: sub radiobutton_prefs {
 4780:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 4781:         $additional,$align,$firstval) = @_;
 4782:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 4783:                    (ref($choices) eq 'HASH'));
 4784: 
 4785:     my (%checkedon,%checkedoff,$datatable,$css_class);
 4786: 
 4787:     foreach my $item (@{$toggles}) {
 4788:         if ($defaultchecked->{$item} eq 'on') {
 4789:             $checkedon{$item} = ' checked="checked" ';
 4790:             $checkedoff{$item} = ' ';
 4791:         } elsif ($defaultchecked->{$item} eq 'off') {
 4792:             $checkedoff{$item} = ' checked="checked" ';
 4793:             $checkedon{$item} = ' ';
 4794:         }
 4795:     }
 4796:     if (ref($settings) eq 'HASH') {
 4797:         foreach my $item (@{$toggles}) {
 4798:             if ($settings->{$item} eq '1') {
 4799:                 $checkedon{$item} =  ' checked="checked" ';
 4800:                 $checkedoff{$item} = ' ';
 4801:             } elsif ($settings->{$item} eq '0') {
 4802:                 $checkedoff{$item} =  ' checked="checked" ';
 4803:                 $checkedon{$item} = ' ';
 4804:             }
 4805:         }
 4806:     }
 4807:     if ($onclick) {
 4808:         $onclick = ' onclick="'.$onclick.'"';
 4809:     }
 4810:     foreach my $item (@{$toggles}) {
 4811:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4812:         $datatable .=
 4813:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 4814:             '<span class="LC_nobreak">'.$choices->{$item}.
 4815:             '</span></td>';
 4816:         if ($align eq 'left') {
 4817:             $datatable .= '<td class="LC_left_item">';
 4818:         } else {
 4819:             $datatable .= '<td class="LC_right_item">';
 4820:         }
 4821:         $datatable .= '<span class="LC_nobreak">';
 4822:         if ($firstval eq 'no') {
 4823:             $datatable .=
 4824:                 '<label><input type="radio" name="'.
 4825:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 4826:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4827:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 4828:         } else {
 4829:             $datatable .=
 4830:                 '<label><input type="radio" name="'.
 4831:                 $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 4832:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4833:                 $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 4834:         }
 4835:         $datatable .= '</span>'.$additional.'</td></tr>';
 4836:         $itemcount ++;
 4837:     }
 4838:     return ($datatable,$itemcount);
 4839: }
 4840: 
 4841: sub print_ltitools {
 4842:     my ($dom,$settings,$rowtotal) = @_;
 4843:     my $rownum = 0;
 4844:     my $css_class;
 4845:     my $itemcount = 1;
 4846:     my $maxnum = 0;
 4847:     my %ordered;
 4848:     if (ref($settings) eq 'HASH') {
 4849:         foreach my $item (keys(%{$settings})) {
 4850:             if (ref($settings->{$item}) eq 'HASH') {
 4851:                 my $num = $settings->{$item}{'order'};
 4852:                 $ordered{$num} = $item;
 4853:             }
 4854:         }
 4855:     }
 4856:     my $confname = $dom.'-domainconfig';
 4857:     my $switchserver = &check_switchserver($dom,$confname);
 4858:     my $maxnum = scalar(keys(%ordered));
 4859:     my $datatable;
 4860:     my %lt = &ltitools_names();
 4861:     my @courseroles = ('cc','in','ta','ep','st');
 4862:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 4863:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 4864:     if (keys(%ordered)) {
 4865:         my @items = sort { $a <=> $b } keys(%ordered);
 4866:         for (my $i=0; $i<@items; $i++) {
 4867:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4868:             my $item = $ordered{$items[$i]};
 4869:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 4870:             if (ref($settings->{$item}) eq 'HASH') {
 4871:                 $title = $settings->{$item}->{'title'};
 4872:                 $url = $settings->{$item}->{'url'};
 4873:                 $key = $settings->{$item}->{'key'};
 4874:                 $secret = $settings->{$item}->{'secret'};
 4875:                 $lifetime = $settings->{$item}->{'lifetime'};
 4876:                 my $image = $settings->{$item}->{'image'};
 4877:                 if ($image ne '') {
 4878:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 4879:                 }
 4880:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 4881:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 4882:                 } else {
 4883:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 4884:                 }
 4885:             }
 4886:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 4887:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 4888:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 4889:             for (my $k=0; $k<=$maxnum; $k++) {
 4890:                 my $vpos = $k+1;
 4891:                 my $selstr;
 4892:                 if ($k == $i) {
 4893:                     $selstr = ' selected="selected" ';
 4894:                 }
 4895:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4896:             }
 4897:             $datatable .= '</select>'.('&nbsp;'x2).
 4898:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 4899:                 &mt('Delete?').'</label></span></td>'.
 4900:                 '<td colspan="2">'.
 4901:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4902:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 4903:                 ('&nbsp;'x2).
 4904:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 4905:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 4906:                 ('&nbsp;'x2).
 4907:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 4908:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4909:                 ('&nbsp;'x2).
 4910:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 4911:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 4912:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 4913:                 '<br /><br />'.
 4914:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 4915:                 ' value="'.$url.'" /></span>'.
 4916:                 ('&nbsp;'x2).
 4917:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 4918:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 4919:                 ('&nbsp;'x2).
 4920:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 4921:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 4922:                 ('&nbsp;'x2).
 4923:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 4924:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 4925:                 '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltitools_secret_'.$i.'.type='."'text'".' } else { this.form.ltitools_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 4926:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 4927:                 '</fieldset>'.
 4928:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4929:                 '<span class="LC_nobreak">'.&mt('Display target:');
 4930:             my %currdisp;
 4931:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 4932:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 4933:                     $currdisp{'window'} = ' checked="checked"';
 4934:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 4935:                     $currdisp{'tab'} = ' checked="checked"';
 4936:                 } else {
 4937:                     $currdisp{'iframe'} = ' checked="checked"';
 4938:                 }
 4939:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 4940:                     $currdisp{'width'} = $1;
 4941:                 }
 4942:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 4943:                      $currdisp{'height'} = $1;
 4944:                 }
 4945:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 4946:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 4947:             } else {
 4948:                 $currdisp{'iframe'} = ' checked="checked"';
 4949:             }
 4950:             foreach my $disp ('iframe','tab','window') {
 4951:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 4952:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 4953:             }
 4954:             $datatable .= ('&nbsp;'x4);
 4955:             foreach my $dimen ('width','height') {
 4956:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4957:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 4958:                               ('&nbsp;'x2);
 4959:             }
 4960:             $datatable .= '</span><br />'.
 4961:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4962:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 4963:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4964:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 4965:                           '</textarea></div><div style=""></div><br />';
 4966:             my %units = (
 4967:                           'passback' => 'days',
 4968:                           'roster'   => 'seconds',
 4969:                         );
 4970:             foreach my $extra ('passback','roster') {
 4971:                 my $validsty = 'none';
 4972:                 my $currvalid;
 4973:                 my $checkedon = '';
 4974:                 my $checkedoff = ' checked="checked"';
 4975:                 if ($settings->{$item}->{$extra}) {
 4976:                     $checkedon = $checkedoff;
 4977:                     $checkedoff = '';
 4978:                     $validsty = 'inline-block';
 4979:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 4980:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 4981:                     }
 4982:                 }
 4983:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 4984:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 4985:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 4986:                               &mt('No').'</label>'.('&nbsp;'x2).
 4987:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 4988:                               &mt('Yes').'</label></span></div>'.
 4989:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 4990:                               '<span class="LC_nobreak">'.
 4991:                               &mt("at least [_1] $units{$extra} after launch",
 4992:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 4993:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 4994:             }
 4995:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 4996:             if ($imgsrc) {
 4997:                 $datatable .= $imgsrc.
 4998:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 4999:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 5000:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 5001:             } else {
 5002:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5003:             }
 5004:             if ($switchserver) {
 5005:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5006:             } else {
 5007:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 5008:             }
 5009:             $datatable .= '</span></fieldset>';
 5010:             my (%checkedfields,%rolemaps,$userincdom);
 5011:             if (ref($settings->{$item}) eq 'HASH') {
 5012:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 5013:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 5014:                 }
 5015:                 $userincdom = $settings->{$item}->{'incdom'};
 5016:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 5017:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 5018:                     $checkedfields{'roles'} = 1;
 5019:                 }
 5020:             }
 5021:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5022:                           '<span class="LC_nobreak">';
 5023:             my $userfieldstyle = 'display:none;';
 5024:             my $seluserdom = '';
 5025:             my $unseluserdom = ' selected="selected"';
 5026:             foreach my $field (@fields) {
 5027:                 my ($checked,$onclick,$id,$spacer);
 5028:                 if ($checkedfields{$field}) {
 5029:                     $checked = ' checked="checked"';
 5030:                 }
 5031:                 if ($field eq 'user') {
 5032:                     $id = ' id="ltitools_user_field_'.$i.'"';
 5033:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 5034:                     if ($checked) {
 5035:                         $userfieldstyle = 'display:inline-block';
 5036:                         if ($userincdom) {
 5037:                             $seluserdom = $unseluserdom;
 5038:                             $unseluserdom = '';
 5039:                         }
 5040:                     }
 5041:                 } else {
 5042:                     $spacer = ('&nbsp;' x2);
 5043:                 }
 5044:                 $datatable .= '<label>'.
 5045:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 5046:                               $lt{$field}.'</label>'.$spacer;
 5047:             }
 5048:             $datatable .= '</span>';
 5049:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 5050:                           '<span class="LC_nobreak"> : '.
 5051:                           '<select name="ltitools_userincdom_'.$i.'">'.
 5052:                           '<option value="">'.&mt('Select').'</option>'.
 5053:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 5054:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 5055:                           '</select></span></div>';
 5056:             $datatable .= '</fieldset>'.
 5057:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5058:             foreach my $role (@courseroles) {
 5059:                 my ($selected,$selectnone);
 5060:                 if (!$rolemaps{$role}) {
 5061:                     $selectnone = ' selected="selected"';
 5062:                 }
 5063:                 $datatable .= '<td style="text-align: center">'. 
 5064:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5065:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 5066:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5067:                 foreach my $ltirole (@ltiroles) {
 5068:                     unless ($selectnone) {
 5069:                         if ($rolemaps{$role} eq $ltirole) {
 5070:                             $selected = ' selected="selected"';
 5071:                         } else {
 5072:                             $selected = '';
 5073:                         }
 5074:                     }
 5075:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5076:                 }
 5077:                 $datatable .= '</select></td>';
 5078:             }
 5079:             $datatable .= '</tr></table></fieldset>';
 5080:             my %courseconfig;
 5081:             if (ref($settings->{$item}) eq 'HASH') {
 5082:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 5083:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 5084:                 }
 5085:             }
 5086:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5087:             foreach my $item ('label','title','target','linktext','explanation','append') {
 5088:                 my $checked;
 5089:                 if ($courseconfig{$item}) {
 5090:                     $checked = ' checked="checked"';
 5091:                 }
 5092:                 $datatable .= '<label>'.
 5093:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 5094:                        $lt{'crs'.$item}.'</label>&nbsp; '."\n";
 5095:             }
 5096:             $datatable .= '</span></fieldset>'.
 5097:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5098:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 5099:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 5100:                 my %custom = %{$settings->{$item}->{'custom'}};
 5101:                 if (keys(%custom) > 0) {
 5102:                     foreach my $key (sort(keys(%custom))) {
 5103:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 5104:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 5105:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5106:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 5107:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 5108:                     }
 5109:                 }
 5110:             }
 5111:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 5112:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 5113:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 5114:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 5115:             $datatable .= '</table></fieldset></td></tr>'."\n";
 5116:             $itemcount ++;
 5117:         }
 5118:     }
 5119:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5120:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 5121:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5122:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 5123:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 5124:     for (my $k=0; $k<$maxnum+1; $k++) {
 5125:         my $vpos = $k+1;
 5126:         my $selstr;
 5127:         if ($k == $maxnum) {
 5128:             $selstr = ' selected="selected" ';
 5129:         }
 5130:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5131:     }
 5132:     $datatable .= '</select>&nbsp;'."\n".
 5133:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5134:                   '<td colspan="2">'.
 5135:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5136:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 5137:                   ('&nbsp;'x2).
 5138:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 5139:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5140:                   ('&nbsp;'x2).
 5141:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 5142:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5143:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 5144:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5145:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5146:                   '<br />'.
 5147:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 5148:                   ('&nbsp;'x2).
 5149:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 5150:                   ('&nbsp;'x2).
 5151:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 5152:                   ('&nbsp;'x2).
 5153:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 5154:                   '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltitools_add_secret.type='."'text'".' } else { this.form.ltitools_add_secret.type='."'password'".' }" />'.&mt('Visible input').'</label></span> '."\n".
 5155:                   '</fieldset>'.
 5156:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5157:                   '<span class="LC_nobreak">'.&mt('Display target:');
 5158:     my %defaultdisp;
 5159:     $defaultdisp{'iframe'} = ' checked="checked"';
 5160:     foreach my $disp ('iframe','tab','window') {
 5161:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 5162:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 5163:     }
 5164:     $datatable .= ('&nbsp;'x4);
 5165:     foreach my $dimen ('width','height') {
 5166:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5167:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 5168:                       ('&nbsp;'x2);
 5169:     }
 5170:     $datatable .= '</span><br />'.
 5171:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5172:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 5173:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5174:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 5175:                   '</div><div style=""></div><br />';
 5176:     my %units = (
 5177:                   'passback' => 'days',
 5178:                   'roster'   => 'seconds',
 5179:                 );
 5180:     my %defaulttimes = (
 5181:                      'passback' => '7',
 5182:                      'roster'   => '300',
 5183:                    );
 5184:     foreach my $extra ('passback','roster') {
 5185:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 5186:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5187:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 5188:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 5189:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 5190:                       &mt('Yes').'</label></span></div>'.
 5191:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 5192:                       '<span class="LC_nobreak">'.
 5193:                       &mt("at least [_1] $units{$extra} after launch",
 5194:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 5195:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5196:     }
 5197:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 5198:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5199:     if ($switchserver) {
 5200:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5201:     } else {
 5202:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 5203:     }
 5204:     $datatable .= '</span></fieldset>'.
 5205:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5206:                   '<span class="LC_nobreak">';
 5207:     foreach my $field (@fields) {
 5208:         my ($id,$onclick,$spacer);
 5209:         if ($field eq 'user') {
 5210:             $id = ' id="ltitools_user_field_add"';
 5211:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 5212:         } else {
 5213:             $spacer = ('&nbsp;' x2);
 5214:         }
 5215:         $datatable .= '<label>'.
 5216:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 5217:                       $lt{$field}.'</label>'.$spacer;
 5218:     }
 5219:     $datatable .= '</span>'.
 5220:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 5221:                   '<span class="LC_nobreak"> : '.
 5222:                   '<select name="ltitools_userincdom_add">'.
 5223:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 5224:                   '<option value="0">'.&mt('username').'</option>'.
 5225:                   '<option value="1">'.&mt('username:domain').'</option>'.
 5226:                   '</select></span></div></fieldset>';
 5227:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5228:     foreach my $role (@courseroles) {
 5229:         my ($checked,$checkednone);
 5230:         $datatable .= '<td style="text-align: center">'.
 5231:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5232:                       '<select name="ltitools_add_roles_'.$role.'">'.
 5233:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 5234:         foreach my $ltirole (@ltiroles) {
 5235:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 5236:         }
 5237:         $datatable .= '</select></td>';
 5238:     }
 5239:     $datatable .= '</tr></table></fieldset>'.
 5240:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5241:     foreach my $item ('label','title','target','linktext','explanation','append') {
 5242:         $datatable .= '<label>'.
 5243:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 5244:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5245:     }
 5246:     $datatable .= '</span></fieldset>'.
 5247:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5248:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5249:                   '<tr><td><span class="LC_nobreak">'.
 5250:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 5251:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 5252:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 5253:                   '</table></fieldset>'."\n".
 5254:                   '</td>'."\n".
 5255:                   '</tr>'."\n";
 5256:     $itemcount ++;
 5257:     return $datatable;
 5258: }
 5259: 
 5260: sub ltitools_names {
 5261:     my %lt = &Apache::lonlocal::texthash(
 5262:                                           'title'          => 'Title',
 5263:                                           'version'        => 'Version',
 5264:                                           'msgtype'        => 'Message Type',
 5265:                                           'sigmethod'      => 'Signature Method',
 5266:                                           'url'            => 'URL',
 5267:                                           'key'            => 'Key',
 5268:                                           'lifetime'       => 'Nonce lifetime (s)',
 5269:                                           'secret'         => 'Secret',
 5270:                                           'icon'           => 'Icon',   
 5271:                                           'user'           => 'User',
 5272:                                           'fullname'       => 'Full Name',
 5273:                                           'firstname'      => 'First Name',
 5274:                                           'lastname'       => 'Last Name',
 5275:                                           'email'          => 'E-mail',
 5276:                                           'roles'          => 'Role',
 5277:                                           'window'         => 'Window',
 5278:                                           'tab'            => 'Tab',
 5279:                                           'iframe'         => 'iFrame',
 5280:                                           'height'         => 'Height',
 5281:                                           'width'          => 'Width',
 5282:                                           'linktext'       => 'Default Link Text',
 5283:                                           'explanation'    => 'Default Explanation',
 5284:                                           'passback'       => 'Tool can return grades:',
 5285:                                           'roster'         => 'Tool can retrieve roster:',
 5286:                                           'crstarget'      => 'Display target',
 5287:                                           'crslabel'       => 'Course label',
 5288:                                           'crstitle'       => 'Course title', 
 5289:                                           'crslinktext'    => 'Link Text',
 5290:                                           'crsexplanation' => 'Explanation',
 5291:                                           'crsappend'      => 'Provider URL',
 5292:                                         );
 5293:     return %lt;
 5294: }
 5295: 
 5296: sub print_proctoring {
 5297:     my ($dom,$settings,$rowtotal) = @_;
 5298:     my $itemcount = 1;
 5299:     my (%ordered,%providernames,%current,%currentdef);
 5300:     my $confname = $dom.'-domainconfig';
 5301:     my $switchserver = &check_switchserver($dom,$confname);
 5302:     if (ref($settings) eq 'HASH') {
 5303:         foreach my $item (keys(%{$settings})) {
 5304:             if (ref($settings->{$item}) eq 'HASH') {
 5305:                 my $num = $settings->{$item}{'order'};
 5306:                 $ordered{$num} = $item;
 5307:             }
 5308:         }
 5309:     } else {
 5310:         %ordered = (
 5311:                      1 => 'proctorio',
 5312:                      2 => 'examity',
 5313:                    );
 5314:     }
 5315:     %providernames = &proctoring_providernames();
 5316:     my $maxnum = scalar(keys(%ordered));
 5317:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
 5318:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
 5319:     if (ref($requref) eq 'HASH') {
 5320:         %requserfields = %{$requref};
 5321:     }
 5322:     if (ref($opturef) eq 'HASH') {
 5323:         %optuserfields = %{$opturef};
 5324:     }
 5325:     if (ref($defref) eq 'HASH') {
 5326:         %defaults = %{$defref};
 5327:     }
 5328:     if (ref($extref) eq 'HASH') {
 5329:         %extended = %{$extref};
 5330:     }
 5331:     if (ref($crsref) eq 'HASH') {
 5332:         %crsconf = %{$crsref};
 5333:     }
 5334:     if (ref($rolesref) eq 'ARRAY') {
 5335:         @courseroles = @{$rolesref};
 5336:     }
 5337:     if (ref($ltiref) eq 'ARRAY') {
 5338:         @ltiroles = @{$ltiref};
 5339:     }
 5340:     my $datatable;
 5341:     my $css_class;
 5342:     if (keys(%ordered)) {
 5343:         my @items = sort { $a <=> $b } keys(%ordered);
 5344:         for (my $i=0; $i<@items; $i++) {
 5345:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5346:             my $provider = $ordered{$items[$i]};
 5347:             my $optionsty = 'none';
 5348:             my ($available,$version,$lifetime,$imgsrc,$userincdom,$showroles,
 5349:                 %checkedfields,%rolemaps,%inuse,%crsconfig,%current);
 5350:             if (ref($settings) eq 'HASH') {
 5351:                 if (ref($settings->{$provider}) eq 'HASH') {
 5352:                     %current = %{$settings->{$provider}};
 5353:                     if ($current{'available'}) {
 5354:                         $optionsty = 'block';
 5355:                         $available = 1;
 5356:                     }
 5357:                     if ($current{'lifetime'} =~ /^\d+$/) {
 5358:                         $lifetime = $current{'lifetime'};
 5359:                     }
 5360:                     if ($current{'version'} =~ /^\d+\.\d+$/) {
 5361:                         $version = $current{'version'};
 5362:                     }
 5363:                     if ($current{'image'} ne '') {
 5364:                         $imgsrc = '<img src="'.$current{'image'}.'" alt="'.&mt('Proctoring service icon').'" />';
 5365:                     }
 5366:                     if (ref($current{'fields'}) eq 'ARRAY') {
 5367:                         map { $checkedfields{$_} = 1; } @{$current{'fields'}};
 5368:                     }
 5369:                     $userincdom = $current{'incdom'};
 5370:                     if (ref($current{'roles'}) eq 'HASH') {
 5371:                         %rolemaps = %{$current{'roles'}};
 5372:                         $checkedfields{'roles'} = 1;
 5373:                     }
 5374:                     if (ref($current{'defaults'}) eq 'ARRAY') {
 5375:                         foreach my $val (@{$current{'defaults'}}) {
 5376:                             if (grep(/^\Q$val\E$/,@{$defaults{$provider}})) {
 5377:                                 $inuse{$val} = 1;
 5378:                             } else {
 5379:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5380:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5381:                                         if (grep(/^\Q$val\E$/,@{$extended{$provider}{$poss}})) {
 5382:                                             $inuse{$poss} = $val;
 5383:                                             last;
 5384:                                         }
 5385:                                     }
 5386:                                 }
 5387:                             }
 5388:                         }
 5389:                     } elsif (ref($current{'defaults'}) eq 'HASH') {
 5390:                         foreach my $key (keys(%{$current{'defaults'}})) {
 5391:                             my $currval = $current{'defaults'}{$key}; 
 5392:                             if (grep(/^\Q$key\E$/,@{$defaults{$provider}})) {
 5393:                                 $inuse{$key} = 1;
 5394:                             } else {
 5395:                                 my $match;
 5396:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5397:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5398:                                         if (grep(/^\Q$key\E$/,@{$extended{$provider}{$poss}})) {
 5399:                                             $inuse{$poss} = $key;
 5400:                                             last;
 5401:                                         }
 5402:                                     } elsif (ref($extended{$provider}{$poss}) eq 'HASH') {
 5403:                                         foreach my $inner (sort(keys(%{$extended{$provider}{$poss}}))) {
 5404:                                             if (ref($extended{$provider}{$poss}{$inner}) eq 'ARRAY') {
 5405:                                                 if (grep(/^\Q$currval\E$/,@{$extended{$provider}{$poss}{$inner}})) {
 5406:                                                     $currentdef{$inner} = $currval;
 5407:                                                     $match = 1;
 5408:                                                     last;
 5409:                                                 }
 5410:                                             } elsif ($inner eq $key) {
 5411:                                                 $currentdef{$key} = $currval;
 5412:                                                 $match = 1;
 5413:                                                 last;
 5414:                                             }
 5415:                                         }
 5416:                                     }
 5417:                                     last if ($match);
 5418:                                 }
 5419:                             }
 5420:                         }
 5421:                     }
 5422:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
 5423:                         map { $crsconfig{$_} = 1; } @{$current{'crsconf'}};
 5424:                     }
 5425:                 }
 5426:             }
 5427:             my %lt = &proctoring_titles($provider);
 5428:             my %fieldtitles = &proctoring_fieldtitles($provider);
 5429:             my $onclickavailable = ' onclick="toggleProctoring(this.form,'."'$provider'".');"';
 5430:             my %checkedavailable = (
 5431:                                    yes => '',
 5432:                                    no  => ' checked="checked"',
 5433:                                  );
 5434:             if ($available) {
 5435:                 $checkedavailable{'yes'} = $checkedavailable{'no'};
 5436:                 $checkedavailable{'no'} = '';
 5437:             }
 5438:             my $chgstr = ' onchange="javascript:reorderProctoring(this.form,'."'proctoring_pos_".$provider."'".');"';
 5439:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5440:                          .'<select name="proctoring_pos_'.$provider.'"'.$chgstr.'>';
 5441:             for (my $k=0; $k<$maxnum; $k++) {
 5442:                 my $vpos = $k+1;
 5443:                 my $selstr;
 5444:                 if ($k == $i) {
 5445:                     $selstr = ' selected="selected" ';
 5446:                 }
 5447:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5448:             }
 5449:             if ($version eq '') {
 5450:                 if ($provider eq 'proctorio') {
 5451:                     $version = '1.0';
 5452:                 } elsif ($provider eq 'examity') {
 5453:                     $version = '1.1';
 5454:                 }
 5455:             }
 5456:             if ($lifetime eq '') {
 5457:                 $lifetime = '300';
 5458:             }
 5459:             $datatable .=
 5460:                 '</select>'.('&nbsp;'x2).'<b>'.$providernames{$provider}.'</b></span><br />'.
 5461:                 '<span class="LC_nobreak">'.$lt{'avai'}.'&nbsp;'.
 5462:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="1"'.$onclickavailable.$checkedavailable{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5463:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="0"'.$onclickavailable.$checkedavailable{no}.' />'.&mt('No').'</label></span>'."\n".
 5464:                 '</td>'.
 5465:                 '<td colspan="2">'.
 5466:                 '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'base'}.'</legend>'.
 5467:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="proctoring_'.$provider.'_version">'.
 5468:                 '<option value="'.$version.'" selected="selected">'.$version.'</option></select></span> '."\n".
 5469:                 ('&nbsp;'x2).
 5470:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="proctoring_'.$provider.'_sigmethod">'.
 5471:                 '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5472:                 '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5473:                 ('&nbsp;'x2).
 5474:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="proctoring_'.$provider.'_lifetime" value="'.$lifetime.'" /></span> '."\n".
 5475:                 '<br />'.
 5476:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="proctoring_'.$provider.'_url" value="'.$current{'url'}.'" /></span> '."\n".
 5477:                 '<br />'.
 5478:                 '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="proctoring_'.$provider.'_key" value="'.$current{'key'}.'" /></span> '."\n".
 5479:                 ('&nbsp;'x2).
 5480:                 '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="proctoring_'.$provider.'_secret" value="'.$current{'secret'}.'" />'.
 5481:                 '<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";
 5482:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 5483:             if ($imgsrc) {
 5484:                 $datatable .= $imgsrc.
 5485:                               '<label><input type="checkbox" name="proctoring_image_del"'.
 5486:                               ' value="'.$provider.'" />'.&mt('Delete?').'</label></span> '.
 5487:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:');
 5488:             }
 5489:             $datatable .= '&nbsp;';
 5490:             if ($switchserver) {
 5491:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5492:             } else {
 5493:                 $datatable .= '<input type="file" name="proctoring_image_'.$provider.'" value="" />';
 5494:             }
 5495:             unless ($imgsrc) {
 5496:                 $datatable .= '<br />('.&mt('if larger than 21x21 pixels, image will be scaled').')';
 5497:             }
 5498:             $datatable .= '</fieldset>'."\n";
 5499:             if (ref($requserfields{$provider}) eq 'ARRAY') {
 5500:                 if (@{$requserfields{$provider}} > 0) {
 5501:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'requ'}.'</legend>';
 5502:                     foreach my $field (@{$requserfields{$provider}}) {
 5503:                         $datatable .= '<span class="LC_nobreak">'.
 5504:                                       '<label><input type="checkbox" name="proctoring_reqd_'.$provider.'" value="'.$field.'" checked="checked" disabled="disabled" />'.
 5505:                                       $lt{$field}.'</label>';
 5506:                         if ($field eq 'user') {
 5507:                             my $seluserdom = '';
 5508:                             my $unseluserdom = ' selected="selected"';
 5509:                             if ($userincdom) {
 5510:                                 $seluserdom = $unseluserdom;
 5511:                                 $unseluserdom = '';
 5512:                             }
 5513:                             $datatable .= ':&nbsp;'.
 5514:                                 '<select name="proctoring_userincdom_'.$provider.'">'.
 5515:                                 '<option value="0"'.$unseluserdom.'>'.$lt{'username'}.'</option>'.
 5516:                                 '<option value="1"'.$seluserdom.'>'.$lt{'uname:dom'}.'</option>'.
 5517:                                 '</select>&nbsp;';
 5518:                         } else {
 5519:                             $datatable .= '&nbsp;';
 5520:                             if ($field eq 'roles') {
 5521:                                 $showroles = 1; 
 5522:                             } 
 5523:                         }
 5524:                         $datatable .= '</span> ';
 5525:                     }
 5526:                 }
 5527:                 $datatable .= '</fieldset>'."\n";
 5528:             }
 5529:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
 5530:                 if (@{$optuserfields{$provider}} > 0) {
 5531:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'optu'}.'</legend>'; 
 5532:                     foreach my $field (@{$optuserfields{$provider}}) {
 5533:                         my $checked;
 5534:                         if ($checkedfields{$field}) {
 5535:                             $checked = ' checked="checked"';
 5536:                         }
 5537:                         $datatable .= '<span class="LC_nobreak">'.
 5538:                                       '<label><input type="checkbox" name="proctoring_optional_'.$provider.'" value="'.$field.'"'.$checked.' />'.$lt{$field}.'</label></span>&nbsp; ';
 5539:                     }
 5540:                     $datatable .= '</fieldset>'."\n";
 5541:                 }
 5542:             }
 5543:             if (ref($defaults{$provider}) eq 'ARRAY') {
 5544:                 if (@{$defaults{$provider}}) {
 5545:                     my (%options,@selectboxes);
 5546:                     if (ref($extended{$provider}) eq 'HASH') {
 5547:                         %options = %{$extended{$provider}};
 5548:                     }
 5549:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'defa'}.'</legend>';
 5550:                     my ($rem,$numinrow,$dropdowns);
 5551:                     if ($provider eq 'proctorio') { 
 5552:                         $datatable .= '<table>';
 5553:                         $numinrow = 4;
 5554:                     }
 5555:                     my $i = 0;
 5556:                     foreach my $field (@{$defaults{$provider}}) {
 5557:                         my $checked;
 5558:                         if ($inuse{$field}) {
 5559:                             $checked = ' checked="checked"';
 5560:                         }
 5561:                         if ($provider eq 'examity') {
 5562:                             if ($field eq 'display') {
 5563:                                 $datatable .= '<span class="LC_nobreak">'.&mt('Display target:');
 5564:                                 foreach my $option ('iframe','tab','window') {
 5565:                                     my $checkdisp;
 5566:                                     if ($currentdef{'target'} eq $option) {
 5567:                                         $checkdisp = ' checked="checked"';
 5568:                                     }
 5569:                                     $datatable .= '<label><input type="radio" name="proctoring_target_'.$provider.'" value="'.$option.'"'.$checkdisp.' />'.
 5570:                                     $fieldtitles{$option}.'</label>'.('&nbsp;'x2);
 5571:                                 }
 5572:                                 $datatable .= ('&nbsp;'x4);
 5573:                                 foreach my $dimen ('width','height') {
 5574:                                     $datatable .= '<label>'.$fieldtitles{$dimen}.'&nbsp;'.
 5575:                                                   '<input type="text" name="proctoring_'.$dimen.'_'.$provider.'" size="5" '.
 5576:                                                   'value="'.$currentdef{$dimen}.'" /></label>'.
 5577:                                                   ('&nbsp;'x2);
 5578:                                 }
 5579:                                 $datatable .= '</span><br />'.
 5580:                                               '<div class="LC_left_float">'.$fieldtitles{'linktext'}.'<br />'.
 5581:                                               '<input type="text" name="proctoring_linktext_'.$provider.'" '.
 5582:                                               'size="25" value="'.$currentdef{'linktext'}.'" /></div>'.
 5583:                                               '<div class="LC_left_float">'.$fieldtitles{'explanation'}.'<br />'.
 5584:                                               '<textarea name="proctoring_explanation_'.$provider.'" rows="5" cols="40">'.
 5585:                                               $currentdef{'explanation'}.
 5586:                                               '</textarea></div><div style=""></div><br />';
 5587:                             }
 5588:                         } else {
 5589:                             if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
 5590:                                 my ($output,$selnone);
 5591:                                 unless ($checked) {
 5592:                                     $selnone = ' selected="selected"';
 5593:                                 }
 5594:                                 $output .= '<span class="LC_nobreak">'.$fieldtitles{$field}.': '.
 5595:                                            '<select name="proctoring_defaults_'.$field.'_'.$provider.'">'.
 5596:                                            '<option value=""'.$selnone.'>'.&mt('Not in use').'</option>'; 
 5597:                                 foreach my $option (@{$options{$field}}) {
 5598:                                     my $sel; 
 5599:                                     if ($inuse{$field} eq $option) {
 5600:                                         $sel = ' selected="selected"';
 5601:                                     }
 5602:                                     $output .= '<option value="'.$option.'"'.$sel.'>'.$fieldtitles{$option}.'</option>';
 5603:                                 }
 5604:                                 $output .= '</select></span>';
 5605:                                 push(@selectboxes,$output);
 5606:                             } else {
 5607:                                 $rem = $i%($numinrow);
 5608:                                 if ($rem == 0) {
 5609:                                     if ($i > 0) {
 5610:                                         $datatable .= '</tr>';
 5611:                                     }
 5612:                                     $datatable .= '<tr>';
 5613:                                 }
 5614:                                 $datatable .= '<td class="LC_left_item">'.
 5615:                                               '<span class="LC_nobreak">'.
 5616:                                               '<label><input type="checkbox" name="proctoring_defaults_'.$provider.'" value="'.$field.'"'.$checked.' />'.
 5617:                                               $fieldtitles{$field}.'</label></span></td>';
 5618:                                 $i++;
 5619:                             }
 5620:                         }
 5621:                     }
 5622:                     if ($provider eq 'proctorio') {
 5623:                         if ($numinrow) {
 5624:                             $rem = $i%$numinrow;
 5625:                         }
 5626:                         my $colsleft = $numinrow - $rem;
 5627:                         if ($colsleft > 1) {
 5628:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5629:                         } else {
 5630:                             $datatable .= '<td class="LC_left_item">';
 5631:                         }
 5632:                         $datatable .= '&nbsp;'.
 5633:                                       '</td></tr></table>';
 5634:                         if (@selectboxes) {
 5635:                             $datatable .= '<hr /><table>';
 5636:                             $numinrow = 2;
 5637:                             for (my $i=0; $i<@selectboxes; $i++) {
 5638:                                 $rem = $i%($numinrow);
 5639:                                 if ($rem == 0) {
 5640:                                     if ($i > 0) {
 5641:                                         $datatable .= '</tr>';
 5642:                                     }
 5643:                                     $datatable .= '<tr>';
 5644:                                 }
 5645:                                 $datatable .= '<td class="LC_left_item">'.
 5646:                                               $selectboxes[$i].'</td>';
 5647:                             }
 5648:                             if ($numinrow) {
 5649:                                 $rem = $i%$numinrow;
 5650:                             }
 5651:                             $colsleft = $numinrow - $rem;
 5652:                             if ($colsleft > 1) {
 5653:                                 $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5654:                             } else {
 5655:                                 $datatable .= '<td class="LC_left_item">';
 5656:                             }
 5657:                             $datatable .= '&nbsp;'.
 5658:                                           '</td></tr></table>';
 5659:                         }
 5660:                     }
 5661:                     $datatable .= '</fieldset>';
 5662:                 }
 5663:                 if (ref($crsconf{$provider}) eq 'ARRAY') {
 5664:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5665:                                   '<legend>'.&mt('Configurable in course').'</legend>';
 5666:                     my ($rem,$numinrow);
 5667:                     if ($provider eq 'proctorio') {
 5668:                         $datatable .= '<table>';
 5669:                         $numinrow = 4;
 5670:                     }
 5671:                     my $i = 0;
 5672:                     foreach my $item (@{$crsconf{$provider}}) {
 5673:                         my $name;
 5674:                         if ($provider eq 'examity') {
 5675:                             $name = $lt{'crs'.$item};
 5676:                         } elsif ($provider eq 'proctorio') {
 5677:                             $name = $fieldtitles{$item};
 5678:                             $rem = $i%($numinrow);
 5679:                             if ($rem == 0) {
 5680:                                 if ($i > 0) {
 5681:                                     $datatable .= '</tr>';
 5682:                                 }
 5683:                                 $datatable .= '<tr>';
 5684:                             }
 5685:                             $datatable .= '<td class="LC_left_item>';
 5686:                         }
 5687:                         my $checked;
 5688:                         if ($crsconfig{$item}) {
 5689:                             $checked = ' checked="checked"';
 5690:                         }
 5691:                         $datatable .= '<span class="LC_nobreak"><label>'.
 5692:                                       '<input type="checkbox" name="proctoring_crsconf_'.$provider.'" value="'.$item.'"'.$checked.' />'.
 5693:                                       $name.'</label></span>';
 5694:                         if ($provider eq 'examity') {
 5695:                             $datatable .= '&nbsp; ';
 5696:                         }
 5697:                         $datatable .= "\n";
 5698:                         $i++;
 5699:                     }
 5700:                     if ($provider eq 'proctorio') {
 5701:                         if ($numinrow) {
 5702:                             $rem = $i%$numinrow;
 5703:                         }
 5704:                         my $colsleft = $numinrow - $rem;
 5705:                         if ($colsleft > 1) {
 5706:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5707:                         } else {
 5708:                             $datatable .= '<td class="LC_left_item">';
 5709:                         }
 5710:                         $datatable .= '&nbsp;'.
 5711:                                       '</td></tr></table>';
 5712:                     }
 5713:                     $datatable .= '</fieldset>';
 5714:                 }
 5715:                 if ($showroles) {
 5716:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5717:                                   '<legend>'.&mt('Role mapping').'</legend><table><tr>';
 5718:                     foreach my $role (@courseroles) {
 5719:                         my ($selected,$selectnone);
 5720:                         if (!$rolemaps{$role}) {
 5721:                             $selectnone = ' selected="selected"';
 5722:                         }
 5723:                         $datatable .= '<td style="text-align: center">'.
 5724:                                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5725:                                       '<select name="proctoring_roles_'.$role.'_'.$provider.'">'.
 5726:                                       '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5727:                         foreach my $ltirole (@ltiroles) {
 5728:                             unless ($selectnone) {
 5729:                                 if ($rolemaps{$role} eq $ltirole) {
 5730:                                     $selected = ' selected="selected"';
 5731:                                 } else {
 5732:                                     $selected = '';
 5733:                                 }
 5734:                             }
 5735:                             $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5736:                         }
 5737:                         $datatable .= '</select></td>';
 5738:                     }
 5739:                     $datatable .= '</tr></table></fieldset>'.
 5740:                                   '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5741:                                   '<legend>'.&mt('Custom items sent on launch').'</legend>'.
 5742:                                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5743:                                   '<tr><td></td><td>lms</td>'.
 5744:                                   '<td><input type="text" name="proctoring_customval_lms_'.$provider.'"'.
 5745:                                   ' value="Loncapa" disabled="disabled"/></td></tr>';
 5746:                     if ((ref($settings) eq 'HASH') && (ref($settings->{$provider}) eq 'HASH') &&
 5747:                         (ref($settings->{$provider}->{'custom'}) eq 'HASH')) {
 5748:                         my %custom = %{$settings->{$provider}->{'custom'}};
 5749:                         if (keys(%custom) > 0) {
 5750:                             foreach my $key (sort(keys(%custom))) {
 5751:                                 next if ($key eq 'lms');
 5752:                                 $datatable .= '<tr><td><span class="LC_nobreak">'.
 5753:                                               '<label><input type="checkbox" name="proctoring_customdel_'.$provider.'" value="'.
 5754:                                               $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5755:                                               '<td><input type="text" name="proctoring_customval_'.$key.'_'.$provider.'"'.
 5756:                                               ' value="'.$custom{$key}.'" /></td></tr>';
 5757:                             }
 5758:                         }
 5759:                     }
 5760:                     $datatable .= '<tr><td><span class="LC_nobreak">'.
 5761:                                   '<label><input type="checkbox" name="proctoring_customadd" value="'.$provider.'" />'.
 5762:                                   &mt('Add more').'</label></span></td><td><input type="text" name="proctoring_custom_name_'.$provider.'" />'.
 5763:                                   '</td><td><input type="text" name="proctoring_custom_value_'.$provider.'" /></td></tr>'.
 5764:                                   '</table></fieldset></td></tr>'."\n";
 5765:                 }
 5766:                 $datatable .= '</td></tr>';
 5767:             }
 5768:             $itemcount ++;
 5769:         }
 5770:     }
 5771:     return $datatable;
 5772: }
 5773: 
 5774: sub proctoring_data {
 5775:     my $requserfields = {
 5776:                       proctorio => ['user'],
 5777:                       examity   => ['roles','user'],
 5778:                      };
 5779:     my $optuserfields = {
 5780:                         proctorio => ['fullname'],
 5781:                         examity   => ['fullname','firstname','lastname','email'],
 5782:                      };
 5783:     my $defaults = {
 5784:                   proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 5785:                                 'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 5786:                                 'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 5787:                                 'closetabs','onescreen','print','downloads','cache','rightclick',
 5788:                                 'reentry','calculator','whiteboard'],
 5789:                   examity   => ['display'],
 5790:                 };
 5791:     my $extended = { 
 5792:                   proctorio => {
 5793:                                  verifyid => ['verifyidauto','verifyidlive'],
 5794:                                  fullscreen => ['fullscreenlenient','fullscreenmoderate','fullscreensever'],
 5795:                                  tabslinks => ['notabs','linksonly'],
 5796:                                  reentry => ['noreentry','agentreentry'],
 5797:                                  calculator => ['calculatorbasic','calculatorsci'],
 5798:                                },
 5799:                   examity => {
 5800:                                display => {
 5801:                                            target      => ['iframe','tab','window'],
 5802:                                            width       => '',
 5803:                                            height      => '',
 5804:                                            linktext    => '',
 5805:                                            explanation => '',
 5806:                                           },
 5807:                              },
 5808:                 };
 5809:     my $crsconf = {
 5810:                  proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 5811:                                'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 5812:                                'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 5813:                                'closetabs','onescreen','print','downloads','cache','rightclick',
 5814:                                'reentry','calculator','whiteboard'],
 5815:                  examity => ['label','title','target','linktext','explanation','append'],
 5816:                };
 5817:     my $courseroles = ['cc','in','ta','ep','st'];
 5818:     my $ltiroles = ['Instructor','ContentDeveloper','TeachingAssistant','Learner'];
 5819:     return ($requserfields,$optuserfields,$defaults,$extended,$crsconf,$courseroles,$ltiroles);
 5820: }
 5821: 
 5822: sub proctoring_titles {
 5823:     my ($item) = @_;
 5824:     my (%common_lt,%custom_lt);
 5825:     %common_lt = &Apache::lonlocal::texthash (
 5826:                      'avai'      => 'Available?',
 5827:                      'base'      => 'Basic Settings',
 5828:                      'requ'      => 'User data required to be sent on launch',
 5829:                      'optu'      => 'User data optionally sent on launch',
 5830:                      'udsl'      => 'User data sent on launch',
 5831:                      'defa'      => 'Defaults for items configurable in course',
 5832:                      'sigmethod' => 'Signature Method',
 5833:                      'key'       => 'Key',
 5834:                      'lifetime'  => 'Nonce lifetime (s)',
 5835:                      'secret'    => 'Secret',
 5836:                      'icon'      => 'Icon',
 5837:                      'fullname'  => 'Full Name',
 5838:                      'visible'   => 'Visible input',
 5839:                      'username'  => 'username',
 5840:                      'user'      => 'User',
 5841:                  );
 5842:     if ($item eq 'proctorio') {
 5843:         %custom_lt = &Apache::lonlocal::texthash (
 5844:                          'version'        => 'OAuth version',
 5845:                          'url'            => 'API URL',
 5846:                          'uname:dom'      => 'username-domain',
 5847:         );
 5848:     } elsif ($item eq 'examity') {
 5849:         %custom_lt = &Apache::lonlocal::texthash (
 5850:                          'version'        => 'LTI Version',
 5851:                          'url'            => 'URL',
 5852:                          'uname:dom'      => 'username:domain',
 5853:                          'msgtype'        => 'Message Type',
 5854:                          'firstname'      => 'First Name',
 5855:                          'lastname'       => 'Last Name',
 5856:                          'email'          => 'E-mail',
 5857:                          'roles'          => 'Role',
 5858:                          'crstarget'      => 'Display target',
 5859:                          'crslabel'       => 'Course label',
 5860:                          'crstitle'       => 'Course title', 
 5861:                          'crslinktext'    => 'Link Text',
 5862:                          'crsexplanation' => 'Explanation',
 5863:                          'crsappend'      => 'Provider URL',
 5864:         );
 5865:     }
 5866:     my %lt = (%common_lt,%custom_lt);
 5867:     return %lt;
 5868: }
 5869: 
 5870: sub proctoring_fieldtitles {
 5871:     my ($item) = @_;
 5872:     if ($item eq 'proctorio') {
 5873:         return &Apache::lonlocal::texthash (
 5874:                   'recordvideo' => 'Record video',
 5875:                   'recordaudio' => 'Record audio',
 5876:                   'recordscreen' => 'Record screen',
 5877:                   'recordwebtraffic' => 'Record web traffic',
 5878:                   'recordroomstart' => 'Record room scan',
 5879:                   'verifyvideo' => 'Verify webcam',
 5880:                   'verifyaudio' => 'Verify microphone',
 5881:                   'verifydesktop' => 'Verify desktop recording',
 5882:                   'verifyid' => 'Photo ID verification',
 5883:                   'verifysignature' => 'Require signature',
 5884:                   'fullscreen' => 'Fullscreen',
 5885:                   'clipboard' => 'Disable copy/paste',
 5886:                   'tabslinks' => 'New tabs/windows',
 5887:                   'closetabs' => 'Close other tabs',
 5888:                   'onescreen' => 'Limit to single screen',
 5889:                   'print' => 'Disable Printing',
 5890:                   'downloads' => 'Disable Downloads',
 5891:                   'cache' => 'Empty cache after exam',
 5892:                   'rightclick' => 'Disable right click',
 5893:                   'reentry' => 'Re-entry to exam',
 5894:                   'calculator' => 'Onscreen calculator',
 5895:                   'whiteboard' => 'Onscreen whiteboard',
 5896:                   'verifyidauto' => 'Automated verification',
 5897:                   'verifyidlive' => 'Live agent verification',
 5898:                   'fullscreenlenient' => 'Forced, but can navigate away for up to 30s',
 5899:                   'fullscreenmoderate' => 'Forced, but can navigate away for up to 15s',
 5900:                   'fullscreensever' => 'Forced, navigation away ends exam',
 5901:                   'notabs' => 'Disaallowed',
 5902:                   'linksonly' => 'Allowed from links in exam',
 5903:                   'noreentry' => 'Disallowed',
 5904:                   'agentreentry' => 'Agent required for re-entry',
 5905:                   'calculatorbasic' => 'Basic',
 5906:                   'calculatorsci' => 'Scientific',
 5907:         );
 5908:     } elsif ($item eq 'examity') {
 5909:         return &Apache::lonlocal::texthash (
 5910:                 'target'         => 'Display target',   
 5911:                 'window'         => 'Window',
 5912:                 'tab'            => 'Tab',
 5913:                 'iframe'         => 'iFrame',
 5914:                 'height'         => 'Height (pixels)',
 5915:                 'width'          => 'Width (pixels)',
 5916:                 'linktext'       => 'Default Link Text',
 5917:                 'explanation'    => 'Default Explanation',
 5918:                 'append'         => 'Provider URL',
 5919:         );
 5920:     }
 5921: }
 5922: 
 5923: sub proctoring_providernames {
 5924:     return (
 5925:              proctorio => 'Proctorio',
 5926:              examity   => 'Examity',
 5927:            );
 5928: }
 5929: 
 5930: sub print_lti {
 5931:     my ($dom,$settings,$rowtotal) = @_;
 5932:     my $itemcount = 1;
 5933:     my $maxnum = 0;
 5934:     my $css_class;
 5935:     my %ordered;
 5936:     if (ref($settings) eq 'HASH') {
 5937:         foreach my $item (keys(%{$settings})) {
 5938:             if (ref($settings->{$item}) eq 'HASH') {
 5939:                 my $num = $settings->{$item}{'order'};
 5940:                 $ordered{$num} = $item;
 5941:             }
 5942:         }
 5943:     }
 5944:     my $maxnum = scalar(keys(%ordered));
 5945:     my $datatable;
 5946:     my %lt = &lti_names();
 5947:     if (keys(%ordered)) {
 5948:         my @items = sort { $a <=> $b } keys(%ordered);
 5949:         for (my $i=0; $i<@items; $i++) {
 5950:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5951:             my $item = $ordered{$items[$i]};
 5952:             my ($key,$secret,$lifetime,$consumer,$requser,$current);
 5953:             if (ref($settings->{$item}) eq 'HASH') {
 5954:                 $key = $settings->{$item}->{'key'};
 5955:                 $secret = $settings->{$item}->{'secret'};
 5956:                 $lifetime = $settings->{$item}->{'lifetime'};
 5957:                 $consumer = $settings->{$item}->{'consumer'};
 5958:                 $requser = $settings->{$item}->{'requser'};
 5959:                 $current = $settings->{$item};
 5960:             }
 5961:             my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 5962:             my %checkedrequser = (
 5963:                                    yes => ' checked="checked"',
 5964:                                    no  => '',
 5965:                                  );
 5966:             if (!$requser) {
 5967:                 $checkedrequser{'no'} = $checkedrequser{'yes'};
 5968:                 $checkedrequser{'yes'} = '';
 5969:             }
 5970:             my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 5971:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5972:                          .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 5973:             for (my $k=0; $k<=$maxnum; $k++) {
 5974:                 my $vpos = $k+1;
 5975:                 my $selstr;
 5976:                 if ($k == $i) {
 5977:                     $selstr = ' selected="selected" ';
 5978:                 }
 5979:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5980:             }
 5981:             $datatable .= '</select>'.('&nbsp;'x2).
 5982:                 '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 5983:                 &mt('Delete?').'</label></span></td>'.
 5984:                 '<td colspan="2">'.
 5985:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5986:                 '<span class="LC_nobreak">'.$lt{'consumer'}.
 5987:                 ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 5988:                 ('&nbsp;'x2).
 5989:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 5990:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 5991:                 ('&nbsp;'x2).
 5992:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 5993:                 'value="'.$lifetime.'" size="3" /></span>'.
 5994:                 ('&nbsp;'x2).
 5995:                  '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 5996:                  '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5997:                  '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 5998:                 '<br /><br />'.
 5999:                 '<span class="LC_nobreak">'.$lt{'key'}.
 6000:                 ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 6001:                 ('&nbsp;'x2).
 6002:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 6003:                 '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 6004:                 '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.lti_secret_'.$i.'.type='."'text'".' } else { this.form.lti_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 6005:                 '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 6006:                 '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 6007:             $itemcount ++;
 6008:         }
 6009:     }
 6010:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6011:     my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 6012:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 6013:                   '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 6014:                   '<select name="lti_pos_add"'.$chgstr.'>';
 6015:     for (my $k=0; $k<$maxnum+1; $k++) {
 6016:         my $vpos = $k+1;
 6017:         my $selstr;
 6018:         if ($k == $maxnum) {
 6019:             $selstr = ' selected="selected" ';
 6020:         }
 6021:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6022:     }
 6023:     $datatable .= '</select>&nbsp;'."\n".
 6024:                   '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 6025:                   '<td colspan="2">'.
 6026:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6027:                   '<span class="LC_nobreak">'.$lt{'consumer'}.
 6028:                   ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 6029:                   ('&nbsp;'x2).
 6030:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 6031:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 6032:                   ('&nbsp;'x2).
 6033:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 6034:                   ('&nbsp;'x2).
 6035:                   '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6036:                   '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6037:                   '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 6038:                   '<br /><br />'.
 6039:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 6040:                   ('&nbsp;'x2).
 6041:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 6042:                   '<label><input type="checkbox" name="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".
 6043:                   '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 6044:                   '</td>'."\n".
 6045:                   '</tr>'."\n";
 6046:     $$rowtotal ++;
 6047:     return $datatable;;
 6048: }
 6049: 
 6050: sub lti_names {
 6051:     my %lt = &Apache::lonlocal::texthash(
 6052:                                           'version'   => 'LTI Version',
 6053:                                           'url'       => 'URL',
 6054:                                           'key'       => 'Key',
 6055:                                           'lifetime'  => 'Nonce lifetime (s)',
 6056:                                           'consumer'  => 'Consumer',
 6057:                                           'secret'    => 'Secret',
 6058:                                           'requser'   => "User's identity sent",
 6059:                                           'email'     => 'Email address',
 6060:                                           'sourcedid' => 'User ID',
 6061:                                           'other'     => 'Other',
 6062:                                           'passback'  => 'Can return grades to Consumer:',
 6063:                                           'roster'    => 'Can retrieve roster from Consumer:',
 6064:                                           'topmenu'   => 'Display LON-CAPA page header',
 6065:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 6066:                                         );
 6067:     return %lt;
 6068: }
 6069: 
 6070: sub lti_options {
 6071:     my ($num,$current,$itemcount,%lt) = @_;
 6072:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 6073:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 6074:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 6075:     $checked{'makecrs'}{'N'} = '  checked="checked"';
 6076:     $checked{'mapcrstype'} = {};
 6077:     $checked{'makeuser'} = {};
 6078:     $checked{'selfenroll'} = {};
 6079:     $checked{'crssec'} = {};
 6080:     $checked{'crssecsrc'} = {};
 6081:     $checked{'lcauth'} = {};
 6082:     $checked{'menuitem'} = {};
 6083:     if ($num eq 'add') {
 6084:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 6085:     }
 6086:     my $userfieldsty = 'none';
 6087:     my $crsfieldsty = 'none';
 6088:     my $crssecfieldsty = 'none';
 6089:     my $secsrcfieldsty = 'none';
 6090:     my $callbacksty = 'none';
 6091:     my $passbacksty = 'none';
 6092:     my $optionsty = 'block';
 6093:     my $lcauthparm;
 6094:     my $lcauthparmstyle = 'display:none';
 6095:     my $lcauthparmtext;
 6096:     my $menusty;
 6097:     my $numinrow = 4;
 6098:     my %menutitles = &ltimenu_titles();
 6099: 
 6100:     if (ref($current) eq 'HASH') {
 6101:         if (!$current->{'requser'}) {
 6102:             $optionsty = 'none';
 6103:         }
 6104:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 6105:             $checked{'mapuser'}{'sourcedid'} = '';
 6106:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 6107:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 6108:             } else {
 6109:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 6110:                 $userfield = $current->{'mapuser'};
 6111:                 $userfieldsty = 'inline-block';
 6112:             }
 6113:         }
 6114:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 6115:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 6116:             if ($current->{'mapcrs'} eq 'context_id') {
 6117:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 6118:             } else {
 6119:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 6120:                 $cidfield = $current->{'mapcrs'};
 6121:                 $crsfieldsty = 'inline-block';
 6122:             }
 6123:         }
 6124:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 6125:             foreach my $type (@{$current->{'mapcrstype'}}) {
 6126:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 6127:             }
 6128:         }
 6129:         if ($current->{'makecrs'}) {
 6130:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 6131:         }
 6132:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 6133:             foreach my $role (@{$current->{'makeuser'}}) {
 6134:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 6135:             }
 6136:         }
 6137:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 6138:             $checked{'lcauth'}{$1} = ' checked="checked"';
 6139:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 6140:                 $lcauthparm = $current->{'lcauthparm'};
 6141:                 $lcauthparmstyle = 'display:table-row'; 
 6142:                 if ($current->{'lcauth'} eq 'localauth') {
 6143:                     $lcauthparmtext = &mt('Local auth argument');
 6144:                 } else {
 6145:                     $lcauthparmtext = &mt('Kerberos domain');
 6146:                 }
 6147:             }
 6148:         }
 6149:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 6150:             foreach my $role (@{$current->{'selfenroll'}}) {
 6151:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 6152:             }
 6153:         }
 6154:         if (ref($current->{'maproles'}) eq 'HASH') {
 6155:             %rolemaps = %{$current->{'maproles'}};
 6156:         }
 6157:         if ($current->{'section'} ne '') {
 6158:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 6159:             $crssecfieldsty = 'inline-block';
 6160:             if ($current->{'section'} eq 'course_section_sourcedid') {
 6161:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 6162:             } else {
 6163:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 6164:                 $crssecsrc = $current->{'section'};
 6165:                 $secsrcfieldsty = 'inline-block';
 6166:             }
 6167:         } else {
 6168:             $checked{'crssec'}{'N'} = ' checked="checked"';
 6169:         }
 6170:         if ($current->{'callback'} ne '') {
 6171:             $callback = $current->{'callback'};
 6172:             $checked{'callback'}{'Y'} = ' checked="checked"';
 6173:             $callbacksty = 'inline-block';
 6174:         } else {
 6175:             $checked{'callback'}{'N'} = ' checked="checked"';
 6176:         }
 6177:         if ($current->{'topmenu'}) {
 6178:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 6179:         } else {
 6180:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 6181:         }
 6182:         if ($current->{'inlinemenu'}) {
 6183:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 6184:         } else {
 6185:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 6186:         }
 6187:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 6188:             $menusty = 'inline-block';
 6189:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 6190:                 foreach my $item (@{$current->{'lcmenu'}}) {
 6191:                     if (exists($menutitles{$item})) {
 6192:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 6193:                     }
 6194:                 }
 6195:             }
 6196:         } else {
 6197:             $menusty = 'none';
 6198:         }
 6199:     } else {
 6200:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 6201:         $checked{'crssec'}{'N'} = ' checked="checked"';
 6202:         $checked{'callback'}{'N'} = ' checked="checked"';
 6203:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 6204:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 6205:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 6206:         $menusty = 'inline-block'; 
 6207:     }
 6208:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 6209:     my %coursetypetitles = &Apache::lonlocal::texthash (
 6210:                                official   => 'Official',
 6211:                                unofficial => 'Unofficial',
 6212:                                community  => 'Community',
 6213:                                textbook   => 'Textbook',
 6214:                                placement  => 'Placement Test',
 6215:                                lti        => 'LTI Provider',
 6216:     );
 6217:     my @authtypes = ('internal','krb4','krb5','localauth');
 6218:     my %shortauth = (
 6219:                      internal => 'int',
 6220:                      krb4 => 'krb4',
 6221:                      krb5 => 'krb5',
 6222:                      localauth  => 'loc'
 6223:                     );
 6224:     my %authnames = &authtype_names();
 6225:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 6226:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 6227:     my @courseroles = ('cc','in','ta','ep','st');
 6228:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 6229:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 6230:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 6231:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 6232:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 6233:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 6234:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 6235:     my $output = '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 6236:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 6237:     foreach my $option ('sourcedid','email','other') {
 6238:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 6239:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 6240:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6241:     }
 6242:     $output .= '</span></div>'.
 6243:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 6244:                '<input type="text" name="lti_customuser_'.$num.'" '.
 6245:                'value="'.$userfield.'" /></div></fieldset>'.
 6246:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 6247:     foreach my $ltirole (@lticourseroles) {
 6248:         my ($selected,$selectnone);
 6249:         if ($rolemaps{$ltirole} eq '') {
 6250:             $selectnone = ' selected="selected"';
 6251:         }
 6252:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 6253:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 6254:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 6255:         foreach my $role (@courseroles) {
 6256:             unless ($selectnone) {
 6257:                 if ($rolemaps{$ltirole} eq $role) {
 6258:                     $selected = ' selected="selected"';
 6259:                 } else {
 6260:                     $selected = '';
 6261:                 }
 6262:             }
 6263:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 6264:                        &Apache::lonnet::plaintext($role,'Course').
 6265:                        '</option>';
 6266:         }
 6267:         $output .= '</select></td>';
 6268:     }
 6269:     $output .= '</tr></table></fieldset>'.
 6270:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 6271:     foreach my $ltirole (@ltiroles) {
 6272:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 6273:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 6274:     }
 6275:     $output .= '</fieldset>'.
 6276:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 6277:                '<table>'.
 6278:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 6279:                '</table>'.
 6280:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 6281:                '<td class="LC_left_item">';
 6282:     foreach my $auth ('lti',@authtypes) {
 6283:         my $authtext;
 6284:         if ($auth eq 'lti') {
 6285:             $authtext = &mt('None');
 6286:         } else {
 6287:             $authtext = $authnames{$shortauth{$auth}};
 6288:         }
 6289:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 6290:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 6291:                    $authtext.'</label></span> &nbsp;';
 6292:     }
 6293:     $output .= '</td></tr>'.
 6294:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 6295:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 6296:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 6297:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 6298:                '</table></fieldset>'.
 6299:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 6300:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 6301:                &mt('Unique course identifier').':&nbsp;';
 6302:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 6303:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 6304:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 6305:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6306:     }
 6307:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 6308:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 6309:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6310:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 6311:     foreach my $type (@coursetypes) {
 6312:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 6313:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 6314:                    ('&nbsp;'x2);
 6315:     }
 6316:     $output .= '</span></fieldset>'.
 6317:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Creating courses').'</legend>'.
 6318:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 6319:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 6320:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6321:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 6322:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 6323:                '</fieldset>'.
 6324:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 6325:     foreach my $lticrsrole (@lticourseroles) {
 6326:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 6327:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 6328:     }
 6329:     $output .= '</fieldset>'.
 6330:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Course options').'</legend>'.
 6331:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 6332:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 6333:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6334:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 6335:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 6336:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 6337:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 6338:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 6339:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 6340:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 6341:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 6342:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 6343:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 6344:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 6345:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 6346:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 6347:     foreach my $extra ('roster','passback') {
 6348:         my $checkedon = '';
 6349:         my $checkedoff = ' checked="checked"';
 6350:         if ($extra eq 'passback') {
 6351:             $pb1p1chk = ' checked="checked"';
 6352:             $pb1p0chk = '';
 6353:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 6354:         } else {
 6355:             $onclickpb = ''; 
 6356:         }
 6357:         if (ref($current) eq 'HASH') {
 6358:             if (($current->{$extra})) {
 6359:                 $checkedon = $checkedoff;
 6360:                 $checkedoff = '';
 6361:                 if ($extra eq 'passback') {
 6362:                     $passbacksty = 'inline-block';
 6363:                 }
 6364:                 if ($current->{'passbackformat'} eq '1.0') {
 6365:                     $pb1p0chk =  ' checked="checked"';
 6366:                     $pb1p1chk = '';
 6367:                 }
 6368:             }
 6369:         }
 6370:         $output .= $lt{$extra}.'&nbsp;'.
 6371:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 6372:                    &mt('No').'</label>'.('&nbsp;'x2).
 6373:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 6374:                    &mt('Yes').'</label><br />';
 6375:     }
 6376:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 6377:                '<span class="LC_nobreak">'.&mt('Grade format').
 6378:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 6379:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 6380:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 6381:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 6382:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6383:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback on logout').':&nbsp;'.
 6384:                '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 6385:                $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6386:                '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 6387:                $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 6388:                '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 6389:                '<span class="LC_nobreak">'.&mt('Parameter').': '.
 6390:                '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 6391:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 6392:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Course defaults (Course Coordinator can override)').'</legend>'.
 6393:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 6394:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 6395:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6396:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 6397:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 6398:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6399:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 6400:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 6401:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6402:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 6403:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 6404:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'. 
 6405:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 6406:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 6407:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 6408:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 6409:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 6410:                    ('&nbsp;'x2);
 6411:     }
 6412:     $output .= '</span></div></fieldset>';
 6413: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 6414: #
 6415: #    $output .= '</fieldset>'.
 6416: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 6417:     return $output;
 6418: }
 6419: 
 6420: sub ltimenu_titles {
 6421:     return &Apache::lonlocal::texthash(
 6422:                                         fullname    => 'Full name',
 6423:                                         coursetitle => 'Course title',
 6424:                                         role        => 'Role',
 6425:                                         logout      => 'Logout',
 6426:                                         grades      => 'Grades',
 6427:     );
 6428: }
 6429: 
 6430: sub print_coursedefaults {
 6431:     my ($position,$dom,$settings,$rowtotal) = @_;
 6432:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 6433:     my $itemcount = 1;
 6434:     my %choices =  &Apache::lonlocal::texthash (
 6435:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 6436:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 6437:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 6438:         coursecredits        => 'Credits can be specified for courses',
 6439:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 6440:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 6441:         texengine            => 'Default method to display mathematics',
 6442:         postsubmit           => 'Disable submit button/keypress following student submission',
 6443:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 6444:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 6445:     );
 6446:     my %staticdefaults = (
 6447:                            anonsurvey_threshold => 10,
 6448:                            uploadquota          => 500,
 6449:                            postsubmit           => 60,
 6450:                            mysqltables          => 172800,
 6451:                          );
 6452:     if ($position eq 'top') {
 6453:         %defaultchecked = (
 6454:                             'canuse_pdfforms' => 'off',
 6455:                             'uselcmath'       => 'on',
 6456:                             'usejsme'         => 'on',
 6457:                             'canclone'        => 'none',
 6458:                           );
 6459:         @toggles = ('canuse_pdfforms','uselcmath','usejsme');
 6460:         my $deftex = $Apache::lonnet::deftex;
 6461:         if (ref($settings) eq 'HASH') {
 6462:             if ($settings->{'texengine'}) {
 6463:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 6464:                     $deftex = $settings->{'texengine'};
 6465:                 }
 6466:             }
 6467:         }
 6468:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6469:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 6470:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 6471:                        '</span></td><td class="LC_right_item">'.
 6472:                        '<select name="texengine">'."\n";
 6473:         my %texoptions = (
 6474:                             MathJax  => 'MathJax',
 6475:                             mimetex  => &mt('Convert to Images'),
 6476:                             tth      => &mt('TeX to HTML'),
 6477:                          );
 6478:         foreach my $renderer ('MathJax','mimetex','tth') {
 6479:             my $selected = '';
 6480:             if ($renderer eq $deftex) {
 6481:                 $selected = ' selected="selected"';
 6482:             }
 6483:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 6484:         }
 6485:         $mathdisp .= '</select></td></tr>'."\n";
 6486:         $itemcount ++;
 6487:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 6488:                                                      \%choices,$itemcount);
 6489:         $datatable = $mathdisp.$datatable;
 6490:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6491:         $datatable .=
 6492:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 6493:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 6494:             '</span></td><td class="LC_left_item">';
 6495:         my $currcanclone = 'none';
 6496:         my $onclick;
 6497:         my @cloneoptions = ('none','domain');
 6498:         my %clonetitles = &Apache::lonlocal::texthash (
 6499:                              none     => 'No additional course requesters',
 6500:                              domain   => "Any course requester in course's domain",
 6501:                              instcode => 'Course requests for official courses ...',
 6502:                           );
 6503:         my (%codedefaults,@code_order,@posscodes);
 6504:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 6505:                                                     \@code_order) eq 'ok') {
 6506:             if (@code_order > 0) {
 6507:                 push(@cloneoptions,'instcode');
 6508:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 6509:             }
 6510:         }
 6511:         if (ref($settings) eq 'HASH') {
 6512:             if ($settings->{'canclone'}) {
 6513:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 6514:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 6515:                         if (@code_order > 0) {
 6516:                             $currcanclone = 'instcode';
 6517:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 6518:                         }
 6519:                     }
 6520:                 } elsif ($settings->{'canclone'} eq 'domain') {
 6521:                     $currcanclone = $settings->{'canclone'};
 6522:                 }
 6523:             }
 6524:         }
 6525:         foreach my $option (@cloneoptions) {
 6526:             my ($checked,$additional);
 6527:             if ($currcanclone eq $option) {
 6528:                 $checked = ' checked="checked"';
 6529:             }
 6530:             if ($option eq 'instcode') {
 6531:                 if (@code_order) {
 6532:                     my $show = 'none';
 6533:                     if ($checked) {
 6534:                         $show = 'block';
 6535:                     }
 6536:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 6537:                                   &mt('Institutional codes for new and cloned course have identical:').
 6538:                                   '<br />';
 6539:                     foreach my $item (@code_order) {
 6540:                         my $codechk;
 6541:                         if ($checked) {
 6542:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 6543:                                 $codechk = ' checked="checked"';
 6544:                             }
 6545:                         }
 6546:                         $additional .= '<label>'.
 6547:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 6548:                                        $item.'</label>';
 6549:                     }
 6550:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 6551:                 }
 6552:             }
 6553:             $datatable .=
 6554:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 6555:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 6556:                 '</label>&nbsp;'.$additional.'</span><br />';
 6557:         }
 6558:         $datatable .= '</td>'.
 6559:                       '</tr>';
 6560:         $itemcount ++;
 6561:     } else {
 6562:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6563:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 6564:         my $currusecredits = 0;
 6565:         my $postsubmitclient = 1;
 6566:         my @types = ('official','unofficial','community','textbook','placement');
 6567:         if (ref($settings) eq 'HASH') {
 6568:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 6569:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 6570:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 6571:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 6572:                 }
 6573:             }
 6574:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 6575:                 foreach my $type (@types) {
 6576:                     next if ($type eq 'community');
 6577:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 6578:                     if ($defcredits{$type} ne '') {
 6579:                         $currusecredits = 1;
 6580:                     }
 6581:                 }
 6582:             }
 6583:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 6584:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 6585:                     $postsubmitclient = 0;
 6586:                     foreach my $type (@types) {
 6587:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6588:                     }
 6589:                 } else {
 6590:                     foreach my $type (@types) {
 6591:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 6592:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 6593:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 6594:                             } else {
 6595:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6596:                             }
 6597:                         } else {
 6598:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6599:                         }
 6600:                     }
 6601:                 }
 6602:             } else {
 6603:                 foreach my $type (@types) {
 6604:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6605:                 }
 6606:             }
 6607:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 6608:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 6609:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 6610:                 }
 6611:             } else {
 6612:                 foreach my $type (@types) {
 6613:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 6614:                 }
 6615:             }
 6616:         } else {
 6617:             foreach my $type (@types) {
 6618:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6619:             }
 6620:         }
 6621:         if (!$currdefresponder) {
 6622:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 6623:         } elsif ($currdefresponder < 1) {
 6624:             $currdefresponder = 1;
 6625:         }
 6626:         foreach my $type (@types) {
 6627:             if ($curruploadquota{$type} eq '') {
 6628:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 6629:             }
 6630:         }
 6631:         $datatable .=
 6632:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6633:                 $choices{'anonsurvey_threshold'}.
 6634:                 '</span></td>'.
 6635:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 6636:                 '<input type="text" name="anonsurvey_threshold"'.
 6637:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 6638:                 '</td></tr>'."\n";
 6639:         $itemcount ++;
 6640:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6641:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6642:                       $choices{'uploadquota'}.
 6643:                       '</span></td>'.
 6644:                       '<td style="text-align: right" class="LC_right_item">'.
 6645:                       '<table><tr>';
 6646:         foreach my $type (@types) {
 6647:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 6648:                            '<input type="text" name="uploadquota_'.$type.'"'.
 6649:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 6650:         }
 6651:         $datatable .= '</tr></table></td></tr>'."\n";
 6652:         $itemcount ++;
 6653:         my $onclick = "toggleDisplay(this.form,'credits');";
 6654:         my $display = 'none';
 6655:         if ($currusecredits) {
 6656:             $display = 'block';
 6657:         }
 6658:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 6659:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 6660:         foreach my $type (@types) {
 6661:             next if ($type eq 'community');
 6662:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 6663:                            '<input type="text" name="'.$type.'_credits"'.
 6664:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 6665:         }
 6666:         $additional .= '</tr></table></div>'."\n";
 6667:         %defaultchecked = ('coursecredits' => 'off');
 6668:         @toggles = ('coursecredits');
 6669:         my $current = {
 6670:                         'coursecredits' => $currusecredits,
 6671:                       };
 6672:         (my $table,$itemcount) =
 6673:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 6674:                                \%choices,$itemcount,$onclick,$additional,'left');
 6675:         $datatable .= $table;
 6676:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 6677:         my $display = 'none';
 6678:         if ($postsubmitclient) {
 6679:             $display = 'block';
 6680:         }
 6681:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 6682:                       &mt('Number of seconds submit is disabled').'<br />'.
 6683:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 6684:                       '<table><tr>';
 6685:         foreach my $type (@types) {
 6686:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 6687:                            '<input type="text" name="'.$type.'_timeout" value="'.
 6688:                            $deftimeout{$type}.'" size="5" /></td>';
 6689:         }
 6690:         $additional .= '</tr></table></div>'."\n";
 6691:         %defaultchecked = ('postsubmit' => 'on');
 6692:         @toggles = ('postsubmit');
 6693:         $current = {
 6694:                        'postsubmit' => $postsubmitclient,
 6695:                    };
 6696:         ($table,$itemcount) =
 6697:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 6698:                                \%choices,$itemcount,$onclick,$additional,'left');
 6699:         $datatable .= $table;
 6700:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6701:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6702:                       $choices{'mysqltables'}.
 6703:                       '</span></td>'.
 6704:                       '<td style="text-align: right" class="LC_right_item">'.
 6705:                       '<table><tr>';
 6706:         foreach my $type (@types) {
 6707:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 6708:                            '<input type="text" name="mysqltables_'.$type.'"'.
 6709:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 6710:         }
 6711:         $datatable .= '</tr></table></td></tr>'."\n";
 6712:         $itemcount ++;
 6713: 
 6714:     }
 6715:     $$rowtotal += $itemcount;
 6716:     return $datatable;
 6717: }
 6718: 
 6719: sub print_selfenrollment {
 6720:     my ($position,$dom,$settings,$rowtotal) = @_;
 6721:     my ($css_class,$datatable);
 6722:     my $itemcount = 1;
 6723:     my @types = ('official','unofficial','community','textbook','placement');
 6724:     if (($position eq 'top') || ($position eq 'middle')) {
 6725:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 6726:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 6727:         my @rows;
 6728:         my $key;
 6729:         if ($position eq 'top') {
 6730:             $key = 'admin'; 
 6731:             if (ref($rowsref) eq 'ARRAY') {
 6732:                 @rows = @{$rowsref};
 6733:             }
 6734:         } elsif ($position eq 'middle') {
 6735:             $key = 'default';
 6736:             @rows = ('types','registered','approval','limit');
 6737:         }
 6738:         foreach my $row (@rows) {
 6739:             if (defined($titlesref->{$row})) {
 6740:                 $itemcount ++;
 6741:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6742:                 $datatable .= '<tr'.$css_class.'>'.
 6743:                               '<td>'.$titlesref->{$row}.'</td>'.
 6744:                               '<td class="LC_left_item">'.
 6745:                               '<table><tr>';
 6746:                 my (%current,%currentcap);
 6747:                 if (ref($settings) eq 'HASH') {
 6748:                     if (ref($settings->{$key}) eq 'HASH') {
 6749:                         foreach my $type (@types) {
 6750:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 6751:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 6752:                             }
 6753:                             if (($row eq 'limit') && ($key eq 'default')) {
 6754:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 6755:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 6756:                                 }
 6757:                             }
 6758:                         }
 6759:                     }
 6760:                 }
 6761:                 my %roles = (
 6762:                              '0' => &Apache::lonnet::plaintext('dc'),
 6763:                             ); 
 6764:             
 6765:                 foreach my $type (@types) {
 6766:                     unless (($row eq 'registered') && ($key eq 'default')) {
 6767:                         $datatable .= '<th>'.&mt($type).'</th>';
 6768:                     }
 6769:                 }
 6770:                 unless (($row eq 'registered') && ($key eq 'default')) {
 6771:                     $datatable .= '</tr><tr>';
 6772:                 }
 6773:                 foreach my $type (@types) {
 6774:                     if ($type eq 'community') {
 6775:                         $roles{'1'} = &mt('Community personnel');
 6776:                     } else {
 6777:                         $roles{'1'} = &mt('Course personnel');
 6778:                     }
 6779:                     $datatable .= '<td style="vertical-align: top">';
 6780:                     if ($position eq 'top') {
 6781:                         my %checked;
 6782:                         if ($current{$type} eq '0') {
 6783:                             $checked{'0'} = ' checked="checked"';
 6784:                         } else {
 6785:                             $checked{'1'} = ' checked="checked"';
 6786:                         }
 6787:                         foreach my $role ('1','0') {
 6788:                             $datatable .= '<span class="LC_nobreak"><label>'.
 6789:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 6790:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 6791:                                           $roles{$role}.'</label></span> ';
 6792:                         }
 6793:                     } else {
 6794:                         if ($row eq 'types') {
 6795:                             my %checked;
 6796:                             if ($current{$type} =~ /^(all|dom)$/) {
 6797:                                 $checked{$1} = ' checked="checked"';
 6798:                             } else {
 6799:                                 $checked{''} = ' checked="checked"';
 6800:                             }
 6801:                             foreach my $val ('','dom','all') {
 6802:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6803:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6804:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6805:                             }
 6806:                         } elsif ($row eq 'registered') {
 6807:                             my %checked;
 6808:                             if ($current{$type} eq '1') {
 6809:                                 $checked{'1'} = ' checked="checked"';
 6810:                             } else {
 6811:                                 $checked{'0'} = ' checked="checked"';
 6812:                             }
 6813:                             foreach my $val ('0','1') {
 6814:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6815:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6816:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6817:                             }
 6818:                         } elsif ($row eq 'approval') {
 6819:                             my %checked;
 6820:                             if ($current{$type} =~ /^([12])$/) {
 6821:                                 $checked{$1} = ' checked="checked"';
 6822:                             } else {
 6823:                                 $checked{'0'} = ' checked="checked"';
 6824:                             }
 6825:                             for my $val (0..2) {
 6826:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6827:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6828:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6829:                             }
 6830:                         } elsif ($row eq 'limit') {
 6831:                             my %checked;
 6832:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 6833:                                 $checked{$1} = ' checked="checked"';
 6834:                             } else {
 6835:                                 $checked{'none'} = ' checked="checked"';
 6836:                             }
 6837:                             my $cap;
 6838:                             if ($currentcap{$type} =~ /^\d+$/) {
 6839:                                 $cap = $currentcap{$type};
 6840:                             }
 6841:                             foreach my $val ('none','allstudents','selfenrolled') {
 6842:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6843:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6844:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6845:                             }
 6846:                             $datatable .= '<br />'.
 6847:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 6848:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 6849:                                           '</span>'; 
 6850:                         }
 6851:                     }
 6852:                     $datatable .= '</td>';
 6853:                 }
 6854:                 $datatable .= '</tr>';
 6855:             }
 6856:             $datatable .= '</table></td></tr>';
 6857:         }
 6858:     } elsif ($position eq 'bottom') {
 6859:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 6860:     }
 6861:     $$rowtotal += $itemcount;
 6862:     return $datatable;
 6863: }
 6864: 
 6865: sub print_validation_rows {
 6866:     my ($caller,$dom,$settings,$rowtotal) = @_;
 6867:     my ($itemsref,$namesref,$fieldsref);
 6868:     if ($caller eq 'selfenroll') { 
 6869:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 6870:     } elsif ($caller eq 'requestcourses') {
 6871:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 6872:     }
 6873:     my %currvalidation;
 6874:     if (ref($settings) eq 'HASH') {
 6875:         if (ref($settings->{'validation'}) eq 'HASH') {
 6876:             %currvalidation = %{$settings->{'validation'}};
 6877:         }
 6878:     }
 6879:     my $datatable;
 6880:     my $itemcount = 0;
 6881:     foreach my $item (@{$itemsref}) {
 6882:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6883:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6884:                       $namesref->{$item}.
 6885:                       '</span></td>'.
 6886:                       '<td class="LC_left_item">';
 6887:         if (($item eq 'url') || ($item eq 'button')) {
 6888:             $datatable .= '<span class="LC_nobreak">'.
 6889:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 6890:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 6891:         } elsif ($item eq 'fields') {
 6892:             my @currfields;
 6893:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 6894:                 @currfields = @{$currvalidation{$item}};
 6895:             }
 6896:             foreach my $field (@{$fieldsref}) {
 6897:                 my $check = '';
 6898:                 if (grep(/^\Q$field\E$/,@currfields)) {
 6899:                     $check = ' checked="checked"';
 6900:                 }
 6901:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6902:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 6903:                               ' value="'.$field.'"'.$check.' />'.$field.
 6904:                               '</label></span> ';
 6905:             }
 6906:         } elsif ($item eq 'markup') {
 6907:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 6908:                            $currvalidation{$item}.
 6909:                               '</textarea>';
 6910:         }
 6911:         $datatable .= '</td></tr>'."\n";
 6912:         if (ref($rowtotal)) {
 6913:             $itemcount ++;
 6914:         }
 6915:     }
 6916:     if ($caller eq 'requestcourses') {
 6917:         my %currhash;
 6918:         if (ref($settings) eq 'HASH') {
 6919:             if (ref($settings->{'validation'}) eq 'HASH') {
 6920:                 if ($settings->{'validation'}{'dc'} ne '') {
 6921:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 6922:                 }
 6923:             }
 6924:         }
 6925:         my $numinrow = 2;
 6926:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 6927:                                                        'validationdc',%currhash);
 6928:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6929:         $datatable .= '<tr'.$css_class.'><td>';
 6930:         if ($numdc > 1) {
 6931:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 6932:         } else {
 6933:             $datatable .=  &mt('Course creation processed as: ');
 6934:         }
 6935:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 6936:         $itemcount ++;
 6937:     }
 6938:     if (ref($rowtotal)) {
 6939:         $$rowtotal += $itemcount;
 6940:     }
 6941:     return $datatable;
 6942: }
 6943: 
 6944: sub print_privacy {
 6945:     my ($position,$dom,$settings,$rowtotal) = @_;
 6946:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 6947:     my $itemcount = 0;
 6948:     unless ($position eq 'top') {
 6949:         @items = ('domain','author','course','community');
 6950:         %names = &Apache::lonlocal::texthash (
 6951:                      domain => 'Assigned domain role(s)',
 6952:                      author => 'Assigned co-author role(s)',
 6953:                      course => 'Assigned course role(s)',
 6954:                      community => 'Assigned community role',
 6955:                  );
 6956:         $numinrow = 4;
 6957:         ($othertitle,$usertypes,$types) =
 6958:             &Apache::loncommon::sorted_inst_types($dom);
 6959:     }
 6960:     if (($position eq 'top') || ($position eq 'middle')) {
 6961:         my (%by_ip,%by_location,@intdoms,@instdoms);
 6962:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 6963:         if ($position eq 'top') {
 6964:             my %curr;
 6965:             my @options = ('none','user','domain','auto');
 6966:             my %titles = &Apache::lonlocal::texthash (
 6967:                 none   => 'Not allowed',
 6968:                 user   => 'User authorizes',
 6969:                 domain => 'DC authorizes',
 6970:                 auto   => 'Unrestricted',
 6971:                 instdom => 'Other domain shares institution/provider',
 6972:                 extdom => 'Other domain has different institution/provider',
 6973:             );
 6974:             my %names = &Apache::lonlocal::texthash (
 6975:                 domain => 'Domain role',
 6976:                 author => 'Co-author role',
 6977:                 course => 'Course role',
 6978:                 community => 'Community role',
 6979:             );
 6980:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6981:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6982:             foreach my $domtype ('instdom','extdom') {
 6983:                 my (%checked,$skip);
 6984:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6985:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 6986:                               '<td class="LC_left_item">';
 6987:                 if ($domtype eq 'instdom') {
 6988:                     unless (@instdoms > 1) {
 6989:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 6990:                         $skip = 1;
 6991:                     }
 6992:                 } elsif ($domtype eq 'extdom') {
 6993:                     if (keys(%by_location) == 0) {
 6994:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 6995:                         $skip = 1;
 6996:                     }
 6997:                 }
 6998:                 unless ($skip) {
 6999:                     foreach my $roletype ('domain','author','course','community') {
 7000:                         $checked{'auto'} = ' checked="checked"';
 7001:                         if (ref($settings) eq 'HASH') {
 7002:                             if (ref($settings->{approval}) eq 'HASH') {
 7003:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 7004:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 7005:                                         $checked{$1} = ' checked="checked"';
 7006:                                         $checked{'auto'} = '';
 7007:                                     }
 7008:                                 }
 7009:                             }
 7010:                         }
 7011:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 7012:                         foreach my $option (@options) {
 7013:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7014:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 7015:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7016:                                           '</label></span>&nbsp; ';
 7017:                         }
 7018:                         $datatable .= '</fieldset>';
 7019:                     }
 7020:                 }
 7021:                 $datatable .= '</td></tr>';
 7022:                 $itemcount ++;
 7023:             }
 7024:         } elsif ($position eq 'middle') {
 7025:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7026:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7027:                     foreach my $item (@{$types}) {
 7028:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 7029:                                                                $numinrow,$itemcount,'','','','','',
 7030:                                                                '',$usertypes->{$item});
 7031:                         $itemcount ++;
 7032:                     }
 7033:                 }
 7034:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 7035:                                                        $numinrow,$itemcount,'','','','','',
 7036:                                                        '',$othertitle);
 7037:                 $itemcount ++;
 7038:             } else {
 7039:                 my (@insttypes,%insttitles);
 7040:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7041:                     @insttypes = @{$types};
 7042:                     %insttitles = %{$usertypes};
 7043:                 }
 7044:                 foreach my $item (@insttypes,'default') {
 7045:                     my $title;
 7046:                     if ($item eq 'default') {
 7047:                         $title = $othertitle;
 7048:                     } else {
 7049:                         $title = $insttitles{$item};
 7050:                     }
 7051:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7052:                     $datatable .= '<tr'.$css_class.'>'.
 7053:                                   '<td class="LC_left_item">'.$title.'</td>'.
 7054:                                   '<td class="LC_left_item">'.
 7055:                                   &mt('Nothing to set here, as there are no other domains').
 7056:                                   '</td></tr>';
 7057:                     $itemcount ++;
 7058:                 }
 7059:             }
 7060:         }
 7061:     } else {
 7062:         my $prefix;
 7063:         if ($position eq 'lower') {
 7064:             $prefix = 'priv';
 7065:         } else {
 7066:             $prefix = 'unpriv';
 7067:         }
 7068:         foreach my $item (@items) {
 7069:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 7070:                                                    $numinrow,$itemcount,'','','','','',
 7071:                                                    '',$names{$item});
 7072:             $itemcount ++;
 7073:         }
 7074:     }
 7075:     if (ref($rowtotal)) {
 7076:         $$rowtotal += $itemcount;
 7077:     }
 7078:     return $datatable;
 7079: }
 7080: 
 7081: sub print_passwords {
 7082:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 7083:     my ($datatable,$css_class);
 7084:     my $itemcount = 0;
 7085:     my %titles = &Apache::lonlocal::texthash (
 7086:         captcha        => '"Forgot Password" CAPTCHA validation',
 7087:         link           => 'Reset link expiration (hours)',
 7088:         case           => 'Case-sensitive usernames/e-mail',
 7089:         prelink        => 'Information required (form 1)',
 7090:         postlink       => 'Information required (form 2)',
 7091:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 7092:         customtext     => 'Domain specific text (HTML)',
 7093:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 7094:         intauth_check  => 'Check bcrypt cost if authenticated',
 7095:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 7096:         permanent      => 'Permanent e-mail address',
 7097:         critical       => 'Critical notification address',
 7098:         notify         => 'Notification address',
 7099:         min            => 'Minimum password length',
 7100:         max            => 'Maximum password length',
 7101:         chars          => 'Required characters',
 7102:         expire         => 'Password expiration (days)',
 7103:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 7104:     );
 7105:     if ($position eq 'top') {
 7106:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7107:         my $shownlinklife = 2;
 7108:         my $prelink = 'both';
 7109:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 7110:         if (ref($settings) eq 'HASH') {
 7111:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 7112:                 $shownlinklife = $settings->{resetlink};
 7113:             }
 7114:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 7115:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 7116:             }
 7117:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 7118:                 $prelink = $settings->{resetprelink};
 7119:             }
 7120:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 7121:                 %postlink = %{$settings->{resetpostlink}};
 7122:             }
 7123:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 7124:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 7125:             }
 7126:             if ($settings->{resetremove}) {
 7127:                 $nostdtext = 1;
 7128:             }
 7129:             if ($settings->{resetcustom}) {
 7130:                 $customurl = $settings->{resetcustom};
 7131:             }
 7132:         } else {
 7133:             if (ref($types) eq 'ARRAY') {
 7134:                 foreach my $item (@{$types}) {
 7135:                     $casesens{$item} = 1;
 7136:                     $postlink{$item} = ['username','email'];
 7137:                 }
 7138:             }
 7139:             $casesens{'default'} = 1;
 7140:             $postlink{'default'} = ['username','email'];
 7141:             $prelink = 'both';
 7142:             %emailsrc = (
 7143:                           permanent => 1,
 7144:                           critical  => 1,
 7145:                           notify    => 1,
 7146:             );
 7147:         }
 7148:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 7149:         $itemcount ++;
 7150:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7151:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 7152:                       '<td class="LC_left_item">'.
 7153:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 7154:                       'name="passwords_link" size="3" /></td></tr>';
 7155:         $itemcount ++;
 7156:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7157:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 7158:                       '<td class="LC_left_item">';
 7159:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7160:             foreach my $item (@{$types}) {
 7161:                 my $checkedcase;
 7162:                 if ($casesens{$item}) {
 7163:                     $checkedcase = ' checked="checked"';
 7164:                 }
 7165:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7166:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 7167:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 7168:                               '</span>&nbsp;&nbsp; ';
 7169:             }
 7170:         }
 7171:         my $checkedcase;
 7172:         if ($casesens{'default'}) {
 7173:             $checkedcase = ' checked="checked"';
 7174:         }
 7175:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7176:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 7177:                       $othertitle.'</label></span></td>';
 7178:         $itemcount ++;
 7179:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7180:         my %checkedpre = (
 7181:                              both => ' checked="checked"',
 7182:                              either => '',
 7183:                          );
 7184:         if ($prelink eq 'either') {
 7185:             $checkedpre{either} = ' checked="checked"';
 7186:             $checkedpre{both} = '';
 7187:         }
 7188:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 7189:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7190:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 7191:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 7192:                       '<span class="LC_nobreak"><label>'.
 7193:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 7194:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 7195:         $itemcount ++;
 7196:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7197:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 7198:                       '<td class="LC_left_item">';
 7199:         my %postlinked;
 7200:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7201:             foreach my $item (@{$types}) {
 7202:                 undef(%postlinked);
 7203:                 $datatable .= '<fieldset style="display: inline-block;">'.
 7204:                               '<legend>'.$usertypes->{$item}.'</legend>';
 7205:                 if (ref($postlink{$item}) eq 'ARRAY') {
 7206:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 7207:                 }
 7208:                 foreach my $field ('email','username') {
 7209:                     my $checked;
 7210:                     if ($postlinked{$field}) {
 7211:                         $checked = ' checked="checked"';
 7212:                     }
 7213:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7214:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 7215:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 7216:                                   '<span>&nbsp;&nbsp; ';
 7217:                 }
 7218:                 $datatable .= '</fieldset>';
 7219:             }
 7220:         }
 7221:         if (ref($postlink{'default'}) eq 'ARRAY') {
 7222:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 7223:         }
 7224:         $datatable .= '<fieldset style="display: inline-block;">'.
 7225:                       '<legend>'.$othertitle.'</legend>';
 7226:         foreach my $field ('email','username') {
 7227:             my $checked;
 7228:             if ($postlinked{$field}) {
 7229:                 $checked = ' checked="checked"';
 7230:             }
 7231:             $datatable .= '<span class="LC_nobreak"><label>'.
 7232:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 7233:                           $field.'"'.$checked.' />'.$field.'</label>'.
 7234:                           '<span>&nbsp;&nbsp; ';
 7235:         }
 7236:         $datatable .= '</fieldset></td></tr>';
 7237:         $itemcount ++;
 7238:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7239:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 7240:                       '<td class="LC_left_item">';
 7241:         foreach my $type ('permanent','critical','notify') {
 7242:             my $checkedemail;
 7243:             if ($emailsrc{$type}) {
 7244:                 $checkedemail = ' checked="checked"';
 7245:             }
 7246:             $datatable .= '<span class="LC_nobreak"><label>'.
 7247:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 7248:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 7249:                           '<span>&nbsp;&nbsp; ';
 7250:         }
 7251:         $datatable .= '</td></tr>';
 7252:         $itemcount ++;
 7253:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7254:         my $switchserver = &check_switchserver($dom,$confname);
 7255:         my ($showstd,$noshowstd);
 7256:         if ($nostdtext) {
 7257:             $noshowstd = ' checked="checked"';
 7258:         } else {
 7259:             $showstd = ' checked="checked"';
 7260:         }
 7261:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 7262:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7263:                       &mt('Retain standard text:').
 7264:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 7265:                       &mt('Yes').'</label>'.'&nbsp;'.
 7266:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 7267:                       &mt('No').'</label></span><br />'.
 7268:                       '<span class="LC_fontsize_small">'.
 7269:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 7270:                       &mt('Include custom text:');
 7271:         if ($customurl) {
 7272:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 7273:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 7274:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 7275:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 7276:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 7277:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 7278:         }
 7279:         if ($switchserver) {
 7280:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 7281:         } else {
 7282:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 7283:                          '<input type="file" name="passwords_customfile" /></span>';
 7284:         }
 7285:         $datatable .= '</td></tr>';
 7286:     } elsif ($position eq 'middle') {
 7287:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 7288:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 7289:         my %defaults;
 7290:         if (ref($domconf{'defaults'}) eq 'HASH') {
 7291:             %defaults = %{$domconf{'defaults'}};
 7292:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 7293:                 $defaults{'intauth_cost'} = 10;
 7294:             }
 7295:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 7296:                 $defaults{'intauth_check'} = 0;
 7297:             }
 7298:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 7299:                 $defaults{'intauth_switch'} = 0;
 7300:             }
 7301:         } else {
 7302:             %defaults = (
 7303:                           'intauth_cost'   => 10,
 7304:                           'intauth_check'  => 0,
 7305:                           'intauth_switch' => 0,
 7306:                         );
 7307:         }
 7308:         foreach my $item (@items) {
 7309:             if ($itemcount%2) {
 7310:                 $css_class = '';
 7311:             } else {
 7312:                 $css_class = ' class="LC_odd_row" ';
 7313:             }
 7314:             $datatable .= '<tr'.$css_class.'>'.
 7315:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 7316:                           '</span></td><td class="LC_left_item" colspan="3">';
 7317:             if ($item eq 'intauth_switch') {
 7318:                 my @options = (0,1,2);
 7319:                 my %optiondesc = &Apache::lonlocal::texthash (
 7320:                                    0 => 'No',
 7321:                                    1 => 'Yes',
 7322:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 7323:                                  );
 7324:                 $datatable .= '<table width="100%">';
 7325:                 foreach my $option (@options) {
 7326:                     my $checked = ' ';
 7327:                     if ($defaults{$item} eq $option) {
 7328:                         $checked = ' checked="checked"';
 7329:                     }
 7330:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 7331:                                   '<label><input type="radio" name="'.$item.
 7332:                                   '" value="'.$option.'"'.$checked.' />'.
 7333:                                   $optiondesc{$option}.'</label></span></td></tr>';
 7334:                 }
 7335:                 $datatable .= '</table>';
 7336:             } elsif ($item eq 'intauth_check') {
 7337:                 my @options = (0,1,2);
 7338:                 my %optiondesc = &Apache::lonlocal::texthash (
 7339:                                    0 => 'No',
 7340:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 7341:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 7342:                                  );
 7343:                 $datatable .= '<table width="100%">';
 7344:                 foreach my $option (@options) {
 7345:                     my $checked = ' ';
 7346:                     my $onclick;
 7347:                     if ($defaults{$item} eq $option) {
 7348:                         $checked = ' checked="checked"';
 7349:                     }
 7350:                     if ($option == 2) {
 7351:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 7352:                     }
 7353:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 7354:                                   '<label><input type="radio" name="'.$item.
 7355:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 7356:                                   $optiondesc{$option}.'</label></span></td></tr>';
 7357:                 }
 7358:                 $datatable .= '</table>';
 7359:             } else {
 7360:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 7361:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 7362:             }
 7363:             $datatable .= '</td></tr>';
 7364:             $itemcount ++;
 7365:         }
 7366:     } elsif ($position eq 'lower') {
 7367:         my ($min,$max,%chars,$expire,$numsaved);
 7368:         $min = $Apache::lonnet::passwdmin;
 7369:         if (ref($settings) eq 'HASH') {
 7370:             if ($settings->{min}) {
 7371:                 $min = $settings->{min};
 7372:             }
 7373:             if ($settings->{max}) {
 7374:                 $max = $settings->{max};
 7375:             }
 7376:             if (ref($settings->{chars}) eq 'ARRAY') {
 7377:                 map { $chars{$_} = 1; } (@{$settings->{chars}});
 7378:             }
 7379:             if ($settings->{expire}) {
 7380:                 $expire = $settings->{expire};
 7381:             }
 7382:             if ($settings->{numsaved}) {
 7383:                 $numsaved = $settings->{numsaved};
 7384:             }
 7385:         }
 7386:         my %rulenames = &Apache::lonlocal::texthash(
 7387:                                                      uc => 'At least one upper case letter',
 7388:                                                      lc => 'At least one lower case letter',
 7389:                                                      num => 'At least one number',
 7390:                                                      spec => 'At least one non-alphanumeric',
 7391:                                                    );
 7392:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7393:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 7394:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7395:                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" '.
 7396:                       'onblur="javascript:warnIntPass(this);" />'.
 7397:                       '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 7398:                       '</span></td></tr>';
 7399:         $itemcount ++;
 7400:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7401:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 7402:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7403:                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" '.
 7404:                       'onblur="javascript:warnIntPass(this);" />'.
 7405:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 7406:                       '</span></td></tr>';
 7407:         $itemcount ++;
 7408:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7409:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 7410:                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 7411:                       '</span></td>';
 7412:         my $numinrow = 2;
 7413:         my @possrules = ('uc','lc','num','spec');
 7414:         $datatable .= '<td class="LC_left_item"><table>';
 7415:         for (my $i=0; $i<@possrules; $i++) {
 7416:             my ($rem,$checked);
 7417:             if ($chars{$possrules[$i]}) {
 7418:                 $checked = ' checked="checked"';
 7419:             }
 7420:             $rem = $i%($numinrow);
 7421:             if ($rem == 0) {
 7422:                 if ($i > 0) {
 7423:                     $datatable .= '</tr>';
 7424:                 }
 7425:                 $datatable .= '<tr>';
 7426:             }
 7427:             $datatable .= '<td><span class="LC_nobreak"><label>'.
 7428:                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 7429:                           $rulenames{$possrules[$i]}.'</label></span></td>';
 7430:         }
 7431:         my $rem = @possrules%($numinrow);
 7432:         my $colsleft = $numinrow - $rem;
 7433:         if ($colsleft > 1 ) {
 7434:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7435:                           '&nbsp;</td>';
 7436:         } elsif ($colsleft == 1) {
 7437:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7438:         }
 7439:         $datatable .='</table></td></tr>';
 7440:         $itemcount ++;
 7441:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7442:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 7443:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7444:                       '<input type="text" name="passwords_expire" value="'.$expire.'" size="4" '.
 7445:                       'onblur="javascript:warnIntPass(this);" />'.
 7446:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 7447:                       '</span></td></tr>';
 7448:         $itemcount ++;
 7449:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7450:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 7451:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7452:                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" '.
 7453:                       'onblur="javascript:warnIntPass(this);" />'. 
 7454:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 7455:                       '</span></td></tr>';
 7456:     } else {
 7457:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7458:         my %ownerchg = (
 7459:                           by  => {},
 7460:                           for => {},
 7461:                        );
 7462:         my %ownertitles = &Apache::lonlocal::texthash (
 7463:                             by  => 'Course owner status(es) allowed',
 7464:                             for => 'Student status(es) allowed',
 7465:                           );
 7466:         if (ref($settings) eq 'HASH') {
 7467:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 7468:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 7469:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 7470:                 }
 7471:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 7472:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 7473:                 }
 7474:             }
 7475:         }
 7476:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7477:         $datatable .= '<tr '.$css_class.'>'.
 7478:                       '<td>'.
 7479:                       &mt('Requirements').'<ul>'.
 7480:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 7481:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 7482:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 7483:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 7484:                       '</ul>'.
 7485:                       '</td>'.
 7486:                       '<td class="LC_left_item">';
 7487:         foreach my $item ('by','for') {
 7488:             $datatable .= '<fieldset style="display: inline-block;">'.
 7489:                           '<legend>'.$ownertitles{$item}.'</legend>';
 7490:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7491:                 foreach my $type (@{$types}) {
 7492:                     my $checked;
 7493:                     if ($ownerchg{$item}{$type}) {
 7494:                         $checked = ' checked="checked"';
 7495:                     }
 7496:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7497:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 7498:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 7499:                                   '</span>&nbsp;&nbsp; ';
 7500:                 }
 7501:             }
 7502:             my $checked;
 7503:             if ($ownerchg{$item}{'default'}) {
 7504:                 $checked = ' checked="checked"';
 7505:             }
 7506:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7507:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 7508:                           $othertitle.'</label></span></fieldset>';
 7509:         }
 7510:         $datatable .= '</td></tr>';
 7511:     }
 7512:     return $datatable;
 7513: }
 7514: 
 7515: sub print_wafproxy {
 7516:     my ($position,$dom,$settings,$rowtotal) = @_;
 7517:     my $css_class;
 7518:     my $itemcount = 0;
 7519:     my $datatable;
 7520:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7521:     my (%othercontrol,%otherdoms,%aliases,%values,$setdom,$showdom);
 7522:     my %lt = &wafproxy_titles();
 7523:     foreach my $server (sort(keys(%servers))) {
 7524:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 7525:         next if ($serverhome eq '');
 7526:         my $serverdom;
 7527:         if ($serverhome ne $server) {
 7528:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 7529:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 7530:                 $othercontrol{$server} = $serverdom;
 7531:             }
 7532:         } else {
 7533:             $serverdom = &Apache::lonnet::host_domain($server);
 7534:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 7535:             if ($serverdom ne $dom) {
 7536:                 $othercontrol{$server} = $serverdom;
 7537:             } else {
 7538:                 $setdom = 1;
 7539:                 if (ref($settings) eq 'HASH') {
 7540:                     if (ref($settings->{'alias'}) eq 'HASH') {
 7541:                         $aliases{$dom} = $settings->{'alias'};
 7542:                         if ($aliases{$dom} ne '') {
 7543:                             $showdom = 1;
 7544:                         }
 7545:                     }
 7546:                 }
 7547:             }
 7548:         }
 7549:     }
 7550:     if ($setdom) {
 7551:         %{$values{$dom}} = ();
 7552:         if (ref($settings) eq 'HASH') {
 7553:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7554:                 $values{$dom}{$item} = $settings->{$item};
 7555:             }
 7556:         }
 7557:     }
 7558:     if (keys(%othercontrol)) {
 7559:         %otherdoms = reverse(%othercontrol);
 7560:         foreach my $domain (keys(%otherdoms)) {
 7561:             %{$values{$domain}} = ();
 7562:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 7563:             if (ref($config{'wafproxy'}) eq 'HASH') {
 7564:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 7565:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7566:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 7567:                 }
 7568:             }
 7569:         }
 7570:     }
 7571:     if ($position eq 'top') {
 7572:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7573:         my %aliasinfo;
 7574:         foreach my $server (sort(keys(%servers))) {
 7575:             $itemcount ++;
 7576:             my $dom_in_effect;
 7577:             my $aliasrows = '<tr>'.
 7578:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7579:                             &mt('Hostname').':&nbsp;'.
 7580:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 7581:             if ($othercontrol{$server}) {
 7582:                 $dom_in_effect = $othercontrol{$server};
 7583:                 my $current;
 7584:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 7585:                     $current = $aliases{$dom_in_effect}{$server};
 7586:                 }
 7587:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7588:                               &mt('Alias').':&nbsp';
 7589:                 if ($current) {
 7590:                     $aliasrows .= $current;
 7591:                 } else {
 7592:                     $aliasrows .= &mt('None');
 7593:                 }
 7594:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 7595:                               &mt('controlled by domain: [_1]',
 7596:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 7597:             } else {
 7598:                 $dom_in_effect = $dom;
 7599:                 my $current;
 7600:                 if (ref($aliases{$dom}) eq 'HASH') {
 7601:                     if ($aliases{$dom}{$server}) {
 7602:                         $current = $aliases{$dom}{$server};
 7603:                     }
 7604:                 }
 7605:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7606:                               &mt('Alias').':&nbsp;'.
 7607:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 7608:                               'value="'.$current.'" size="30" /></td>';
 7609:             }
 7610:             $aliasrows .= '</tr>';
 7611:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 7612:         }
 7613:         if ($aliasinfo{$dom}) {
 7614:             my ($onclick,$wafon,$wafoff,$showtable);
 7615:             $onclick = ' onclick="javascript:toggleWAF();"';
 7616:             $wafoff = ' checked="checked"';
 7617:             $showtable = ' style="display:none";';
 7618:             if ($showdom) {
 7619:                 $wafon = $wafoff;
 7620:                 $wafoff = '';
 7621:                 $showtable = ' style="display:inline;"';
 7622:             }
 7623:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7624:             $datatable = '<tr'.$css_class.'>'.
 7625:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 7626:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 7627:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 7628:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 7629:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 7630:                          &mt('No').'</label></span></td>'.
 7631:                          '<td class="LC_left_item">'.
 7632:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 7633:                          '</table></td></tr>';
 7634:             $itemcount++;
 7635:         }
 7636:         if (keys(%otherdoms)) {
 7637:             foreach my $key (sort(keys(%otherdoms))) {
 7638:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7639:                 $datatable .= '<tr'.$css_class.'>'.
 7640:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 7641:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 7642:                               '</table></td></tr>';
 7643:                 $itemcount++;
 7644:             }
 7645:         }
 7646:     } else {
 7647:         my %ip_methods = &remoteip_methods();
 7648:         if ($setdom) {
 7649:             $itemcount ++;
 7650:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7651:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 7652:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 7653:             $wafstyle = ' style="display:none;"';
 7654:             $nowafstyle = ' style="display:table-row;"';
 7655:             $currwafdisplay = ' style="display: none"';
 7656:             $wafrangestyle = ' style="display: none"';
 7657:             $curr_remotip = 'n';
 7658:             $ssltossl = ' checked="checked"';
 7659:             if ($showdom) {
 7660:                 $wafstyle = ' style="display:table-row;"';
 7661:                 $nowafstyle =  ' style="display:none;"';
 7662:                 if (keys(%{$values{$dom}})) {
 7663:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 7664:                         $curr_remotip = $values{$dom}{remoteip};
 7665:                     }
 7666:                     if ($curr_remotip eq 'h') {
 7667:                         $currwafdisplay = ' style="display:table-row"';
 7668:                         $wafrangestyle = ' style="display:inline-block;"';
 7669:                     }
 7670:                     if ($values{$dom}{'sslopt'}) {
 7671:                         $alltossl = ' checked="checked"';
 7672:                         $ssltossl = '';
 7673:                     }
 7674:                 }
 7675:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 7676:                     $vpndircheck = ' checked="checked"';
 7677:                     $currwafvpn = ' style="display:table-row;"';
 7678:                     $wafrangestyle = ' style="display:inline-block;"';
 7679:                 } else {
 7680:                     $vpnaliascheck = ' checked="checked"';
 7681:                     $currwafvpn = ' style="display:none;"';
 7682:                 }
 7683:             }
 7684:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7685:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 7686:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 7687:                           '</tr>'.
 7688:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7689:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 7690:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 7691:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'</div></td>'.
 7692:                           '<td class="LC_left_item"><table>'.
 7693:                           '<tr>'.
 7694:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 7695:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 7696:             foreach my $option ('m','h','n') {
 7697:                 my $sel;
 7698:                 if ($option eq $curr_remotip) {
 7699:                    $sel = ' selected="selected"';
 7700:                 }
 7701:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 7702:                               $ip_methods{$option}.'</option>';
 7703:             }
 7704:             $datatable .= '</select></td></tr>'."\n".
 7705:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 7706:                           $lt{'ipheader'}.':&nbsp;'.
 7707:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 7708:                           'name="wafproxy_ipheader" />'.
 7709:                           '</td></tr>'."\n".
 7710:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 7711:                           $lt{'trusted'}.':<br />'.
 7712:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 7713:                           $values{$dom}{'trusted'}.'</textarea>'.
 7714:                           '</td></tr>'."\n".
 7715:                           '<tr><td><hr /></td></tr>'."\n".
 7716:                           '<tr>'.
 7717:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 7718:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 7719:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 7720:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 7721:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 7722:             foreach my $item ('vpnint','vpnext') {
 7723:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 7724:                               '<td valign="top">'.$lt{$item}.':<br />'.
 7725:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 7726:                               $values{$dom}{$item}.'</textarea>'.
 7727:                               '</td></tr>'."\n";
 7728:             }
 7729:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 7730:                           '<tr>'.
 7731:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 7732:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 7733:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 7734:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 7735:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 7736:                           '</table></td></tr>';
 7737:         }
 7738:         if (keys(%otherdoms)) {
 7739:             foreach my $domain (sort(keys(%otherdoms))) {
 7740:                 $itemcount ++;
 7741:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7742:                 $datatable .= '<tr'.$css_class.'>'.
 7743:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 7744:                               '<td class="LC_left_item"><table>';
 7745:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 7746:                     my $showval = &mt('None');
 7747:                     if ($item eq 'ssl') {
 7748:                         $showval = $lt{'ssltossl'};
 7749:                     }
 7750:                     if ($values{$domain}{$item}) {
 7751:                         $showval = $values{$domain}{$item};
 7752:                         if ($item eq 'ssl') {
 7753:                             $showval = $lt{'alltossl'};
 7754:                         } elsif ($item eq 'remoteip') {
 7755:                             $showval = $ip_methods{$values{$domain}{$item}};
 7756:                         }
 7757:                     }
 7758:                     $datatable .= '<tr>'.
 7759:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 7760:                 }
 7761:                 $datatable .= '</table></td></tr>';
 7762:             }
 7763:         }
 7764:     }
 7765:     $$rowtotal += $itemcount;
 7766:     return $datatable;
 7767: }
 7768: 
 7769: sub wafproxy_titles {
 7770:     return &Apache::lonlocal::texthash(
 7771:                remoteip   => "Method for determining user's IP",
 7772:                ipheader   => 'Request header containing remote IP',
 7773:                trusted    => 'Trusted IP range(s)',
 7774:                vpnaccess  => 'Access from institutional VPN',
 7775:                vpndirect  => 'via regular hostname (no WAF)',
 7776:                vpnaliased => 'via aliased hostname (WAF)',
 7777:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 7778:                vpnext     => 'IP Range(s) for backend WAF connections',
 7779:                sslopt     => 'Forwarding http/https',
 7780:                alltossl   => 'WAF forwards both http and https requests to https',
 7781:                ssltossl   => 'WAF forwards http requests to http and https to https',
 7782:            );
 7783: }
 7784: 
 7785: sub remoteip_methods {
 7786:     return &Apache::lonlocal::texthash(
 7787:               m => 'Use Apache mod_remoteip',
 7788:               h => 'Use headers parsed by LON-CAPA',
 7789:               n => 'Not in use',
 7790:            );
 7791: }
 7792: 
 7793: sub print_usersessions {
 7794:     my ($position,$dom,$settings,$rowtotal) = @_;
 7795:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 7796:     my (%by_ip,%by_location,@intdoms,@instdoms);
 7797:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7798: 
 7799:     my @alldoms = &Apache::lonnet::all_domains();
 7800:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 7801:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7802:     my %altids = &id_for_thisdom(%servers);
 7803:     if ($position eq 'top') {
 7804:         if (keys(%serverhomes) > 1) {
 7805:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 7806:             my ($curroffloadnow,$curroffloadoth);
 7807:             if (ref($settings) eq 'HASH') {
 7808:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 7809:                     $curroffloadnow = $settings->{'offloadnow'};
 7810:                 }
 7811:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 7812:                     $curroffloadoth = $settings->{'offloadoth'};
 7813:                 }
 7814:             }
 7815:             my $other_insts = scalar(keys(%by_location));
 7816:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 7817:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 7818:         } else {
 7819:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 7820:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 7821:                           '</td></tr>';
 7822:         }
 7823:     } else {
 7824:         my %titles = &usersession_titles();
 7825:         my ($prefix,@types);
 7826:         if ($position eq 'bottom') {
 7827:             $prefix = 'remote';
 7828:             @types = ('version','excludedomain','includedomain');
 7829:         } else {
 7830:             $prefix = 'hosted';
 7831:             @types = ('excludedomain','includedomain');
 7832:         }
 7833:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 7834:     }
 7835:     $$rowtotal += $itemcount;
 7836:     return $datatable;
 7837: }
 7838: 
 7839: sub rules_by_location {
 7840:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 7841:     my ($datatable,$itemcount,$css_class);
 7842:     if (keys(%{$by_location}) == 0) {
 7843:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7844:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 7845:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 7846:                      '</td></tr>';
 7847:         $itemcount = 1;
 7848:     } else {
 7849:         $itemcount = 0;
 7850:         my $numinrow = 5;
 7851:         my (%current,%checkedon,%checkedoff);
 7852:         my @locations = sort(keys(%{$by_location}));
 7853:         foreach my $type (@{$types}) {
 7854:             $checkedon{$type} = '';
 7855:             $checkedoff{$type} = ' checked="checked"';
 7856:         }
 7857:         if (ref($settings) eq 'HASH') {
 7858:             if (ref($settings->{$prefix}) eq 'HASH') {
 7859:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 7860:                     $current{$key} = $settings->{$prefix}{$key};
 7861:                     if ($key eq 'version') {
 7862:                         if ($current{$key} ne '') {
 7863:                             $checkedon{$key} = ' checked="checked"';
 7864:                             $checkedoff{$key} = '';
 7865:                         }
 7866:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 7867:                         $checkedon{$key} = ' checked="checked"';
 7868:                         $checkedoff{$key} = '';
 7869:                     }
 7870:                 }
 7871:             }
 7872:         }
 7873:         foreach my $type (@{$types}) {
 7874:             next if ($type ne 'version' && !@locations);
 7875:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7876:             $datatable .= '<tr'.$css_class.'>
 7877:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 7878:                            <span class="LC_nobreak">&nbsp;
 7879:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 7880:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 7881:             if ($type eq 'version') {
 7882:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 7883:                 my $selector = '<select name="'.$prefix.'_version">';
 7884:                 foreach my $version (@lcversions) {
 7885:                     my $selected = '';
 7886:                     if ($current{'version'} eq $version) {
 7887:                         $selected = ' selected="selected"';
 7888:                     }
 7889:                     $selector .= ' <option value="'.$version.'"'.
 7890:                                  $selected.'>'.$version.'</option>';
 7891:                 }
 7892:                 $selector .= '</select> ';
 7893:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 7894:             } else {
 7895:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 7896:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 7897:                              ' />'.('&nbsp;'x2).
 7898:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 7899:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 7900:                              "\n".
 7901:                              '</div><div><table>';
 7902:                 my $rem;
 7903:                 for (my $i=0; $i<@locations; $i++) {
 7904:                     my ($showloc,$value,$checkedtype);
 7905:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 7906:                         my $ip = $by_location->{$locations[$i]}->[0];
 7907:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7908:                             $value = join(':',@{$by_ip->{$ip}});
 7909:                             $showloc = join(', ',@{$by_ip->{$ip}});
 7910:                             if (ref($current{$type}) eq 'ARRAY') {
 7911:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 7912:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 7913:                                         $checkedtype = ' checked="checked"';
 7914:                                         last;
 7915:                                     }
 7916:                                 }
 7917:                             }
 7918:                         }
 7919:                     }
 7920:                     $rem = $i%($numinrow);
 7921:                     if ($rem == 0) {
 7922:                         if ($i > 0) {
 7923:                             $datatable .= '</tr>';
 7924:                         }
 7925:                         $datatable .= '<tr>';
 7926:                     }
 7927:                     $datatable .= '<td class="LC_left_item">'.
 7928:                                   '<span class="LC_nobreak"><label>'.
 7929:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 7930:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 7931:                                   '</label></span></td>';
 7932:                 }
 7933:                 $rem = @locations%($numinrow);
 7934:                 my $colsleft = $numinrow - $rem;
 7935:                 if ($colsleft > 1 ) {
 7936:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7937:                                   '&nbsp;</td>';
 7938:                 } elsif ($colsleft == 1) {
 7939:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7940:                 }
 7941:                 $datatable .= '</tr></table>';
 7942:             }
 7943:             $datatable .= '</td></tr>';
 7944:             $itemcount ++;
 7945:         }
 7946:     }
 7947:     return ($datatable,$itemcount);
 7948: }
 7949: 
 7950: sub print_ssl {
 7951:     my ($position,$dom,$settings,$rowtotal) = @_;
 7952:     my ($css_class,$datatable);
 7953:     my $itemcount = 1;
 7954:     if ($position eq 'top') {
 7955:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7956:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7957:         my $same_institution;
 7958:         if ($intdom ne '') {
 7959:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 7960:             if (ref($internet_names) eq 'ARRAY') {
 7961:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 7962:                     $same_institution = 1;
 7963:                 }
 7964:             }
 7965:         }
 7966:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7967:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 7968:         if ($same_institution) {
 7969:             my %domservers = &Apache::lonnet::get_servers($dom);
 7970:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 7971:         } else {
 7972:             $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.");
 7973:         }
 7974:         $datatable .= '</td></tr>';
 7975:         $itemcount ++;
 7976:     } else {
 7977:         my %titles = &ssl_titles();
 7978:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7979:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7980:         my @alldoms = &Apache::lonnet::all_domains();
 7981:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 7982:         my @domservers = &Apache::lonnet::get_servers($dom);
 7983:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7984:         my %altids = &id_for_thisdom(%servers);
 7985:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 7986:             my $legacy;
 7987:             unless (ref($settings) eq 'HASH') {
 7988:                 my $name;
 7989:                 if ($position eq 'connto') {
 7990:                     $name = 'loncAllowInsecure';
 7991:                 } else {
 7992:                     $name = 'londAllowInsecure';
 7993:                 }
 7994:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 7995:                 my @ids=&Apache::lonnet::current_machine_ids();
 7996:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 7997:                     my %what = (
 7998:                                    $name => 1,
 7999:                                );
 8000:                     my ($result,$returnhash) =
 8001:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 8002:                     if ($result eq 'ok') {
 8003:                         if (ref($returnhash) eq 'HASH') {
 8004:                             $legacy = $returnhash->{$name};
 8005:                         }
 8006:                     }
 8007:                 } else {
 8008:                     $legacy = $Apache::lonnet::perlvar{$name};
 8009:                 }
 8010:             }
 8011:             foreach my $type ('dom','intdom','other') {
 8012:                 my %checked;
 8013:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8014:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 8015:                               '<td class="LC_right_item">';
 8016:                 my $skip; 
 8017:                 if ($type eq 'dom') {
 8018:                     unless (keys(%servers) > 1) {
 8019:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 8020:                         $skip = 1;
 8021:                     }
 8022:                 }
 8023:                 if ($type eq 'intdom') {
 8024:                     unless (@instdoms > 1) {
 8025:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 8026:                         $skip = 1;
 8027:                     } 
 8028:                 } elsif ($type eq 'other') {
 8029:                     if (keys(%by_location) == 0) {
 8030:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 8031:                         $skip = 1;
 8032:                     }
 8033:                 }
 8034:                 unless ($skip) {
 8035:                     $checked{'yes'} = ' checked="checked"'; 
 8036:                     if (ref($settings) eq 'HASH') {
 8037:                         if (ref($settings->{$position}) eq 'HASH') {
 8038:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 8039:                                 $checked{$1} = $checked{'yes'};
 8040:                                 delete($checked{'yes'}); 
 8041:                             }
 8042:                         }
 8043:                     } else {
 8044:                         if ($legacy == 0) {
 8045:                             $checked{'req'} = $checked{'yes'};
 8046:                             delete($checked{'yes'});    
 8047:                         }
 8048:                     }
 8049:                     foreach my $option ('no','yes','req') {
 8050:                         $datatable .= '<span class="LC_nobreak"><label>'.
 8051:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 8052:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 8053:                                       '</label></span>'.('&nbsp;'x2);
 8054:                     }
 8055:                 }
 8056:                 $datatable .= '</td></tr>';
 8057:                 $itemcount ++; 
 8058:             }
 8059:         } else {
 8060:             my $prefix = 'replication';
 8061:             my @types = ('certreq','nocertreq');
 8062:             if (keys(%by_location) == 0) {
 8063:                 $datatable .= '<tr'.$css_class.'><td>'.
 8064:                               &mt('Nothing to set here, as there are no other institutions').
 8065:                               '</td></tr>';
 8066:                 $itemcount ++;
 8067:             } else {
 8068:                 ($datatable,$itemcount) = 
 8069:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8070:             }
 8071:         }
 8072:     }
 8073:     $$rowtotal += $itemcount;
 8074:     return $datatable;
 8075: }
 8076: 
 8077: sub ssl_titles {
 8078:     return &Apache::lonlocal::texthash (
 8079:                dom           => 'LON-CAPA servers/VMs from same domain',
 8080:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 8081:                other         => 'External LON-CAPA servers/VMs',
 8082:                connto        => 'Connections to other servers',
 8083:                connfrom      => 'Connections from other servers',
 8084:                replication   => 'Replicating content to other institutions',
 8085:                certreq       => 'Client certificate required, but specific domains exempt',
 8086:                nocertreq     => 'No client certificate required, except for specific domains',
 8087:                no            => 'SSL not used',
 8088:                yes           => 'SSL Optional (used if available)',
 8089:                req           => 'SSL Required',
 8090:     );
 8091: }
 8092: 
 8093: sub print_trust {
 8094:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 8095:     my ($css_class,$datatable,%checked,%choices);
 8096:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8097:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8098:     my $itemcount = 1;
 8099:     my %titles = &trust_titles();
 8100:     my @types = ('exc','inc');
 8101:     if ($prefix eq 'top') {
 8102:         $prefix = 'content';
 8103:     } elsif ($prefix eq 'bottom') {
 8104:         $prefix = 'msg';
 8105:     }
 8106:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8107:     $$rowtotal += $itemcount;
 8108:     return $datatable;
 8109: }
 8110: 
 8111: sub trust_titles {
 8112:     return &Apache::lonlocal::texthash(
 8113:                content  => "Access to this domain's content by others",
 8114:                shared   => "Access to other domain's content by this domain",
 8115:                enroll   => "Enrollment in this domain's courses by others", 
 8116:                othcoau  => "Co-author roles in this domain for others",
 8117:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 8118:                domroles => "Domain roles in this domain assignable to others",
 8119:                catalog  => "Course Catalog for this domain displayed elsewhere",
 8120:                reqcrs   => "Requests for creation of courses in this domain by others",
 8121:                msg      => "Users in other domains can send messages to this domain",
 8122:                exc      => "Allow all, but exclude specific domains",
 8123:                inc      => "Deny all, but include specific domains",
 8124:            );
 8125: } 
 8126: 
 8127: sub build_location_hashes {
 8128:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 8129:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 8130:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 8131:     my %iphost = &Apache::lonnet::get_iphost();
 8132:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 8133:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 8134:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 8135:         foreach my $id (@{$iphost{$primary_ip}}) {
 8136:             my $intdom = &Apache::lonnet::internet_dom($id);
 8137:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 8138:                 push(@{$intdoms},$intdom);
 8139:             }
 8140:         }
 8141:     }
 8142:     foreach my $ip (keys(%iphost)) {
 8143:         if (ref($iphost{$ip}) eq 'ARRAY') {
 8144:             foreach my $id (@{$iphost{$ip}}) {
 8145:                 my $location = &Apache::lonnet::internet_dom($id);
 8146:                 if ($location) {
 8147:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 8148:                         my $dom = &Apache::lonnet::host_domain($id);
 8149:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 8150:                             push(@{$instdoms},$dom);
 8151:                         }
 8152:                         next;
 8153:                     }
 8154:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8155:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 8156:                             push(@{$by_ip->{$ip}},$location);
 8157:                         }
 8158:                     } else {
 8159:                         $by_ip->{$ip} = [$location];
 8160:                     }
 8161:                 }
 8162:             }
 8163:         }
 8164:     }
 8165:     foreach my $ip (sort(keys(%{$by_ip}))) {
 8166:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8167:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 8168:             my $first = $by_ip->{$ip}->[0];
 8169:             if (ref($by_location->{$first}) eq 'ARRAY') {
 8170:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 8171:                     push(@{$by_location->{$first}},$ip);
 8172:                 }
 8173:             } else {
 8174:                 $by_location->{$first} = [$ip];
 8175:             }
 8176:         }
 8177:     }
 8178:     return;
 8179: }
 8180: 
 8181: sub current_offloads_to {
 8182:     my ($dom,$settings,$servers) = @_;
 8183:     my (%spareid,%otherdomconfigs);
 8184:     if (ref($servers) eq 'HASH') {
 8185:         foreach my $lonhost (sort(keys(%{$servers}))) {
 8186:             my $gotspares;
 8187:             if (ref($settings) eq 'HASH') {
 8188:                 if (ref($settings->{'spares'}) eq 'HASH') {
 8189:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 8190:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 8191:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 8192:                         $gotspares = 1;
 8193:                     }
 8194:                 }
 8195:             }
 8196:             unless ($gotspares) {
 8197:                 my $gotspares;
 8198:                 my $serverhomeID =
 8199:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 8200:                 my $serverhomedom =
 8201:                     &Apache::lonnet::host_domain($serverhomeID);
 8202:                 if ($serverhomedom ne $dom) {
 8203:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 8204:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 8205:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 8206:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 8207:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 8208:                                 $gotspares = 1;
 8209:                             }
 8210:                         }
 8211:                     } else {
 8212:                         $otherdomconfigs{$serverhomedom} =
 8213:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 8214:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 8215:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 8216:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 8217:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 8218:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 8219:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 8220:                                         $gotspares = 1;
 8221:                                     }
 8222:                                 }
 8223:                             }
 8224:                         }
 8225:                     }
 8226:                 }
 8227:             }
 8228:             unless ($gotspares) {
 8229:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 8230:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 8231:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 8232:                } else {
 8233:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 8234:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 8235:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 8236:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 8237:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 8238:                     } else {
 8239:                         my %what = (
 8240:                              spareid => 1,
 8241:                         );
 8242:                         my ($result,$returnhash) = 
 8243:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 8244:                         if ($result eq 'ok') { 
 8245:                             if (ref($returnhash) eq 'HASH') {
 8246:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 8247:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 8248:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 8249:                                 }
 8250:                             }
 8251:                         }
 8252:                     }
 8253:                 }
 8254:             }
 8255:         }
 8256:     }
 8257:     return %spareid;
 8258: }
 8259: 
 8260: sub spares_row {
 8261:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 8262:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 8263:     my $css_class;
 8264:     my $numinrow = 4;
 8265:     my $itemcount = 1;
 8266:     my $datatable;
 8267:     my %typetitles = &sparestype_titles();
 8268:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8269:         foreach my $server (sort(keys(%{$servers}))) {
 8270:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 8271:             my ($othercontrol,$serverdom);
 8272:             if ($serverhome ne $server) {
 8273:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 8274:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8275:             } else {
 8276:                 $serverdom = &Apache::lonnet::host_domain($server);
 8277:                 if ($serverdom ne $dom) {
 8278:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8279:                 }
 8280:             }
 8281:             next unless (ref($spareid->{$server}) eq 'HASH');
 8282:             my ($checkednow,$checkedoth);
 8283:             if (ref($curroffloadnow) eq 'HASH') {
 8284:                 if ($curroffloadnow->{$server}) {
 8285:                     $checkednow = ' checked="checked"';
 8286:                 }
 8287:             }
 8288:             if (ref($curroffloadoth) eq 'HASH') {
 8289:                 if ($curroffloadoth->{$server}) {
 8290:                     $checkedoth = ' checked="checked"';
 8291:                 }
 8292:             }
 8293:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8294:             $datatable .= '<tr'.$css_class.'>
 8295:                            <td rowspan="2">
 8296:                             <span class="LC_nobreak">'.
 8297:                           &mt('[_1] when busy, offloads to:'
 8298:                               ,'<b>'.$server.'</b>').'</span><br />'.
 8299:                           '<span class="LC_nobreak">'."\n".
 8300:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 8301:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 8302:                           "\n";
 8303:             if ($other_insts) {
 8304:                 $datatable .= '<br />'.
 8305:                               '<span class="LC_nobreak">'."\n".
 8306:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 8307:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 8308:                           "\n";
 8309:             }
 8310:             my (%current,%canselect);
 8311:             my @choices = 
 8312:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 8313:             foreach my $type ('primary','default') {
 8314:                 if (ref($spareid->{$server}) eq 'HASH') {
 8315:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 8316:                         my @spares = @{$spareid->{$server}{$type}};
 8317:                         if (@spares > 0) {
 8318:                             if ($othercontrol) {
 8319:                                 $current{$type} = join(', ',@spares);
 8320:                             } else {
 8321:                                 $current{$type} .= '<table>';
 8322:                                 my $numspares = scalar(@spares);
 8323:                                 for (my $i=0;  $i<@spares; $i++) {
 8324:                                     my $rem = $i%($numinrow);
 8325:                                     if ($rem == 0) {
 8326:                                         if ($i > 0) {
 8327:                                             $current{$type} .= '</tr>';
 8328:                                         }
 8329:                                         $current{$type} .= '<tr>';
 8330:                                     }
 8331:                                     $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;'.
 8332:                                                        $spareid->{$server}{$type}[$i].
 8333:                                                        '</label></td>'."\n";
 8334:                                 }
 8335:                                 my $rem = @spares%($numinrow);
 8336:                                 my $colsleft = $numinrow - $rem;
 8337:                                 if ($colsleft > 1 ) {
 8338:                                     $current{$type} .= '<td colspan="'.$colsleft.
 8339:                                                        '" class="LC_left_item">'.
 8340:                                                        '&nbsp;</td>';
 8341:                                 } elsif ($colsleft == 1) {
 8342:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 8343:                                 }
 8344:                                 $current{$type} .= '</tr></table>';
 8345:                             }
 8346:                         }
 8347:                     }
 8348:                     if ($current{$type} eq '') {
 8349:                         $current{$type} = &mt('None specified');
 8350:                     }
 8351:                     if ($othercontrol) {
 8352:                         if ($type eq 'primary') {
 8353:                             $canselect{$type} = $othercontrol;
 8354:                         }
 8355:                     } else {
 8356:                         $canselect{$type} = 
 8357:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 8358:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 8359:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 8360:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 8361:                         if (@choices > 0) {
 8362:                             foreach my $lonhost (@choices) {
 8363:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 8364:                             }
 8365:                         }
 8366:                         $canselect{$type} .= '</select>'."\n";
 8367:                     }
 8368:                 } else {
 8369:                     $current{$type} = &mt('Could not be determined');
 8370:                     if ($type eq 'primary') {
 8371:                         $canselect{$type} =  $othercontrol;
 8372:                     }
 8373:                 }
 8374:                 if ($type eq 'default') {
 8375:                     $datatable .= '<tr'.$css_class.'>';
 8376:                 }
 8377:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 8378:                               '<td>'.$current{$type}.'</td>'."\n".
 8379:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 8380:             }
 8381:             $itemcount ++;
 8382:         }
 8383:     }
 8384:     $$rowtotal += $itemcount;
 8385:     return $datatable;
 8386: }
 8387: 
 8388: sub possible_newspares {
 8389:     my ($server,$currspares,$serverhomes,$altids) = @_;
 8390:     my $serverhostname = &Apache::lonnet::hostname($server);
 8391:     my %excluded;
 8392:     if ($serverhostname ne '') {
 8393:         %excluded = (
 8394:                        $serverhostname => 1,
 8395:                     );
 8396:     }
 8397:     if (ref($currspares) eq 'HASH') {
 8398:         foreach my $type (keys(%{$currspares})) {
 8399:             if (ref($currspares->{$type}) eq 'ARRAY') {
 8400:                 if (@{$currspares->{$type}} > 0) {
 8401:                     foreach my $curr (@{$currspares->{$type}}) {
 8402:                         my $hostname = &Apache::lonnet::hostname($curr);
 8403:                         $excluded{$hostname} = 1;
 8404:                     }
 8405:                 }
 8406:             }
 8407:         }
 8408:     }
 8409:     my @choices;
 8410:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8411:         if (keys(%{$serverhomes}) > 1) {
 8412:             foreach my $name (sort(keys(%{$serverhomes}))) {
 8413:                 unless ($excluded{$name}) {
 8414:                     if (exists($altids->{$serverhomes->{$name}})) {
 8415:                         push(@choices,$altids->{$serverhomes->{$name}});
 8416:                     } else {
 8417:                         push(@choices,$serverhomes->{$name});
 8418:                     }
 8419:                 }
 8420:             }
 8421:         }
 8422:     }
 8423:     return sort(@choices);
 8424: }
 8425: 
 8426: sub print_loadbalancing {
 8427:     my ($dom,$settings,$rowtotal) = @_;
 8428:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8429:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8430:     my $numinrow = 1;
 8431:     my $datatable;
 8432:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8433:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 8434:     if (ref($settings) eq 'HASH') {
 8435:         %existing = %{$settings};
 8436:     }
 8437:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 8438:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 8439:                                   \%currtargets,\%currrules,\%currcookies);
 8440:     } else {
 8441:         return;
 8442:     }
 8443:     my ($othertitle,$usertypes,$types) =
 8444:         &Apache::loncommon::sorted_inst_types($dom);
 8445:     my $rownum = 8;
 8446:     if (ref($types) eq 'ARRAY') {
 8447:         $rownum += scalar(@{$types});
 8448:     }
 8449:     my @css_class = ('LC_odd_row','LC_even_row');
 8450:     my $balnum = 0;
 8451:     my $islast;
 8452:     my (@toshow,$disabledtext);
 8453:     if (keys(%currbalancer) > 0) {
 8454:         @toshow = sort(keys(%currbalancer));
 8455:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 8456:             push(@toshow,'');
 8457:         }
 8458:     } else {
 8459:         @toshow = ('');
 8460:         $disabledtext = &mt('No existing load balancer');
 8461:     }
 8462:     foreach my $lonhost (@toshow) {
 8463:         if ($balnum == scalar(@toshow)-1) {
 8464:             $islast = 1;
 8465:         } else {
 8466:             $islast = 0;
 8467:         }
 8468:         my $cssidx = $balnum%2;
 8469:         my $targets_div_style = 'display: none';
 8470:         my $disabled_div_style = 'display: block';
 8471:         my $homedom_div_style = 'display: none';
 8472:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 8473:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 8474:                       '<p>';
 8475:         if ($lonhost eq '') {
 8476:             $datatable .= '<span class="LC_nobreak">';
 8477:             if (keys(%currbalancer) > 0) {
 8478:                 $datatable .= &mt('Add balancer:');
 8479:             } else {
 8480:                 $datatable .= &mt('Enable balancer:');
 8481:             }
 8482:             $datatable .= '&nbsp;'.
 8483:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 8484:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 8485:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 8486:                           '<option value="" selected="selected">'.&mt('None').
 8487:                           '</option>'."\n";
 8488:             foreach my $server (sort(keys(%servers))) {
 8489:                 next if ($currbalancer{$server});
 8490:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 8491:             }
 8492:             $datatable .=
 8493:                 '</select>'."\n".
 8494:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 8495:         } else {
 8496:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 8497:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 8498:                            &mt('Stop balancing').'</label>'.
 8499:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 8500:             $targets_div_style = 'display: block';
 8501:             $disabled_div_style = 'display: none';
 8502:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 8503:                 $homedom_div_style = 'display: block';
 8504:             }
 8505:         }
 8506:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 8507:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 8508:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 8509:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 8510:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 8511:         my @sparestypes = ('primary','default');
 8512:         my %typetitles = &sparestype_titles();
 8513:         my %hostherechecked = (
 8514:                                   no => ' checked="checked"',
 8515:                               );
 8516:         my %balcookiechecked = (
 8517:                                   no => ' checked="checked"', 
 8518:                                );
 8519:         foreach my $sparetype (@sparestypes) {
 8520:             my $targettable;
 8521:             for (my $i=0; $i<$numspares; $i++) {
 8522:                 my $checked;
 8523:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 8524:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 8525:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 8526:                             $checked = ' checked="checked"';
 8527:                         }
 8528:                     }
 8529:                 }
 8530:                 my ($chkboxval,$disabled);
 8531:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 8532:                     $chkboxval = $spares[$i];
 8533:                 }
 8534:                 if (exists($currbalancer{$spares[$i]})) {
 8535:                     $disabled = ' disabled="disabled"';
 8536:                 }
 8537:                 $targettable .=
 8538:                     '<td><span class="LC_nobreak"><label>'.
 8539:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 8540:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 8541:                     '</span></label></span></td>';
 8542:                 my $rem = $i%($numinrow);
 8543:                 if ($rem == 0) {
 8544:                     if (($i > 0) && ($i < $numspares-1)) {
 8545:                         $targettable .= '</tr>';
 8546:                     }
 8547:                     if ($i < $numspares-1) {
 8548:                         $targettable .= '<tr>';
 8549:                     }
 8550:                 }
 8551:             }
 8552:             if ($targettable ne '') {
 8553:                 my $rem = $numspares%($numinrow);
 8554:                 my $colsleft = $numinrow - $rem;
 8555:                 if ($colsleft > 1 ) {
 8556:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8557:                                     '&nbsp;</td>';
 8558:                 } elsif ($colsleft == 1) {
 8559:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 8560:                 }
 8561:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 8562:                                '<table><tr>'.$targettable.'</tr></table><br />';
 8563:             }
 8564:             $hostherechecked{$sparetype} = '';
 8565:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 8566:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 8567:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 8568:                         $hostherechecked{$sparetype} = ' checked="checked"';
 8569:                         $hostherechecked{'no'} = '';
 8570:                     }
 8571:                 }
 8572:             }
 8573:         }
 8574:         if ($currcookies{$lonhost}) {
 8575:             %balcookiechecked = (
 8576:                                     yes => ' checked="checked"',
 8577:                                 );
 8578:         }
 8579:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 8580:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 8581:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 8582:         foreach my $sparetype (@sparestypes) {
 8583:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 8584:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 8585:                           '</i></label><br />';
 8586:         }
 8587:         $datatable .= &mt('Use balancer cookie').'<br />'.
 8588:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 8589:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 8590:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 8591:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 8592:                       '</div></td></tr>'.
 8593:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 8594:                                            $othertitle,$usertypes,$types,\%servers,
 8595:                                            \%currbalancer,$lonhost,
 8596:                                            $targets_div_style,$homedom_div_style,
 8597:                                            $css_class[$cssidx],$balnum,$islast);
 8598:         $$rowtotal += $rownum;
 8599:         $balnum ++;
 8600:     }
 8601:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 8602:     return $datatable;
 8603: }
 8604: 
 8605: sub get_loadbalancers_config {
 8606:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 8607:     return unless ((ref($servers) eq 'HASH') &&
 8608:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 8609:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 8610:                    (ref($currcookies) eq 'HASH'));
 8611:     if (keys(%{$existing}) > 0) {
 8612:         my $oldlonhost;
 8613:         foreach my $key (sort(keys(%{$existing}))) {
 8614:             if ($key eq 'lonhost') {
 8615:                 $oldlonhost = $existing->{'lonhost'};
 8616:                 $currbalancer->{$oldlonhost} = 1;
 8617:             } elsif ($key eq 'targets') {
 8618:                 if ($oldlonhost) {
 8619:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 8620:                 }
 8621:             } elsif ($key eq 'rules') {
 8622:                 if ($oldlonhost) {
 8623:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 8624:                 }
 8625:             } elsif (ref($existing->{$key}) eq 'HASH') {
 8626:                 $currbalancer->{$key} = 1;
 8627:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 8628:                 $currrules->{$key} = $existing->{$key}{'rules'};
 8629:                 if ($existing->{$key}{'cookie'}) {
 8630:                     $currcookies->{$key} = 1;
 8631:                 }
 8632:             }
 8633:         }
 8634:     } else {
 8635:         my ($balancerref,$targetsref) =
 8636:                 &Apache::lonnet::get_lonbalancer_config($servers);
 8637:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 8638:             foreach my $server (sort(keys(%{$balancerref}))) {
 8639:                 $currbalancer->{$server} = 1;
 8640:                 $currtargets->{$server} = $targetsref->{$server};
 8641:             }
 8642:         }
 8643:     }
 8644:     return;
 8645: }
 8646: 
 8647: sub loadbalancing_rules {
 8648:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 8649:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 8650:         $css_class,$balnum,$islast) = @_;
 8651:     my $output;
 8652:     my $num = 0;
 8653:     my ($alltypes,$othertypes,$titles) =
 8654:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 8655:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 8656:         foreach my $type (@{$alltypes}) {
 8657:             $num ++;
 8658:             my $current;
 8659:             if (ref($currrules) eq 'HASH') {
 8660:                 $current = $currrules->{$type};
 8661:             }
 8662:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8663:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 8664:                     $current = '';
 8665:                 }
 8666:             }
 8667:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 8668:                                              $servers,$currbalancer,$lonhost,$dom,
 8669:                                              $targets_div_style,$homedom_div_style,
 8670:                                              $css_class,$balnum,$num,$islast);
 8671:         }
 8672:     }
 8673:     return $output;
 8674: }
 8675: 
 8676: sub loadbalancing_titles {
 8677:     my ($dom,$intdom,$usertypes,$types) = @_;
 8678:     my %othertypes = (
 8679:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 8680:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 8681:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 8682:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 8683:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 8684:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 8685:                      );
 8686:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 8687:     my @available;
 8688:     if (ref($types) eq 'ARRAY') {
 8689:         @available = @{$types};
 8690:     }
 8691:     unless (grep(/^default$/,@available)) {
 8692:         push(@available,'default');
 8693:     }
 8694:     unshift(@alltypes,@available);
 8695:     my %titles;
 8696:     foreach my $type (@alltypes) {
 8697:         if ($type =~ /^_LC_/) {
 8698:             $titles{$type} = $othertypes{$type};
 8699:         } elsif ($type eq 'default') {
 8700:             $titles{$type} = &mt('All users from [_1]',$dom);
 8701:             if (ref($types) eq 'ARRAY') {
 8702:                 if (@{$types} > 0) {
 8703:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 8704:                 }
 8705:             }
 8706:         } elsif (ref($usertypes) eq 'HASH') {
 8707:             $titles{$type} = $usertypes->{$type};
 8708:         }
 8709:     }
 8710:     return (\@alltypes,\%othertypes,\%titles);
 8711: }
 8712: 
 8713: sub loadbalance_rule_row {
 8714:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 8715:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 8716:     my @rulenames;
 8717:     my %ruletitles = &offloadtype_text();
 8718:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 8719:         @rulenames = ('balancer','offloadedto','specific');
 8720:     } else {
 8721:         @rulenames = ('default','homeserver');
 8722:         if ($type eq '_LC_external') {
 8723:             push(@rulenames,'externalbalancer');
 8724:         } else {
 8725:             push(@rulenames,'specific');
 8726:         }
 8727:         push(@rulenames,'none');
 8728:     }
 8729:     my $style = $targets_div_style;
 8730:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8731:         $style = $homedom_div_style;
 8732:     }
 8733:     my $space;
 8734:     if ($islast && $num == 1) {
 8735:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 8736:     }
 8737:     my $output =
 8738:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 8739:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 8740:         '<td valaign="top">'.$space.
 8741:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 8742:     for (my $i=0; $i<@rulenames; $i++) {
 8743:         my $rule = $rulenames[$i];
 8744:         my ($checked,$extra);
 8745:         if ($rulenames[$i] eq 'default') {
 8746:             $rule = '';
 8747:         }
 8748:         if ($rulenames[$i] eq 'specific') {
 8749:             if (ref($servers) eq 'HASH') {
 8750:                 my $default;
 8751:                 if (($current ne '') && (exists($servers->{$current}))) {
 8752:                     $checked = ' checked="checked"';
 8753:                 }
 8754:                 unless ($checked) {
 8755:                     $default = ' selected="selected"';
 8756:                 }
 8757:                 $extra =
 8758:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8759:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8760:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 8761:                     '<option value=""'.$default.'></option>'."\n";
 8762:                 foreach my $server (sort(keys(%{$servers}))) {
 8763:                     if (ref($currbalancer) eq 'HASH') {
 8764:                         next if (exists($currbalancer->{$server}));
 8765:                     }
 8766:                     my $selected;
 8767:                     if ($server eq $current) {
 8768:                         $selected = ' selected="selected"';
 8769:                     }
 8770:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 8771:                 }
 8772:                 $extra .= '</select>';
 8773:             }
 8774:         } elsif ($rule eq $current) {
 8775:             $checked = ' checked="checked"';
 8776:         }
 8777:         $output .= '<span class="LC_nobreak"><label>'.
 8778:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 8779:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 8780:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 8781:                    ')"'.$checked.' />&nbsp;';
 8782:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 8783:             $output .= $ruletitles{'particular'};
 8784:         } else {
 8785:             $output .= $ruletitles{$rulenames[$i]};
 8786:         }
 8787:         $output .= '</label>'.$extra.'</span><br />'."\n";
 8788:     }
 8789:     $output .= '</div></td></tr>'."\n";
 8790:     return $output;
 8791: }
 8792: 
 8793: sub offloadtype_text {
 8794:     my %ruletitles = &Apache::lonlocal::texthash (
 8795:            'default'          => 'Offloads to default destinations',
 8796:            'homeserver'       => "Offloads to user's home server",
 8797:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 8798:            'specific'         => 'Offloads to specific server',
 8799:            'none'             => 'No offload',
 8800:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 8801:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 8802:            'particular'       => 'Session hosted (after re-auth) on server:',
 8803:     );
 8804:     return %ruletitles;
 8805: }
 8806: 
 8807: sub sparestype_titles {
 8808:     my %typestitles = &Apache::lonlocal::texthash (
 8809:                           'primary' => 'primary',
 8810:                           'default' => 'default',
 8811:                       );
 8812:     return %typestitles;
 8813: }
 8814: 
 8815: sub contact_titles {
 8816:     my %titles = &Apache::lonlocal::texthash (
 8817:                    'supportemail'    => 'Support E-mail address',
 8818:                    'adminemail'      => 'Default Server Admin E-mail address',
 8819:                    'errormail'       => 'Error reports to be e-mailed to',
 8820:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 8821:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 8822:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 8823:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 8824:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 8825:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 8826:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 8827:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 8828:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 8829:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 8830:                    'errorweights'    => 'Weights used to compute error count',
 8831:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 8832:                  );
 8833:     my %short_titles = &Apache::lonlocal::texthash (
 8834:                            adminemail   => 'Admin E-mail address',
 8835:                            supportemail => 'Support E-mail',
 8836:                        );   
 8837:     return (\%titles,\%short_titles);
 8838: }
 8839: 
 8840: sub helpform_fields {
 8841:     my %titles =  &Apache::lonlocal::texthash (
 8842:                        'username'   => 'Name',
 8843:                        'user'       => 'Username/domain',
 8844:                        'phone'      => 'Phone',
 8845:                        'cc'         => 'Cc e-mail',
 8846:                        'course'     => 'Course Details',
 8847:                        'section'    => 'Sections',
 8848:                        'screenshot' => 'File upload',
 8849:     );
 8850:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 8851:     my %possoptions = (
 8852:                         username     => ['yes','no','req'],
 8853:                         phone        => ['yes','no','req'],
 8854:                         user         => ['yes','no'],
 8855:                         cc           => ['yes','no'],
 8856:                         course       => ['yes','no'],
 8857:                         section      => ['yes','no'],
 8858:                         screenshot   => ['yes','no'],
 8859:                       );
 8860:     my %fieldoptions = &Apache::lonlocal::texthash (
 8861:                          'yes'  => 'Optional',
 8862:                          'req'  => 'Required',
 8863:                          'no'   => "Not shown",
 8864:     );
 8865:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 8866: }
 8867: 
 8868: sub tool_titles {
 8869:     my %titles = &Apache::lonlocal::texthash (
 8870:                      aboutme    => 'Personal web page',
 8871:                      blog       => 'Blog',
 8872:                      webdav     => 'WebDAV',
 8873:                      portfolio  => 'Portfolio',
 8874:                      official   => 'Official courses (with institutional codes)',
 8875:                      unofficial => 'Unofficial courses',
 8876:                      community  => 'Communities',
 8877:                      textbook   => 'Textbook courses',
 8878:                      placement  => 'Placement tests',
 8879:                  );
 8880:     return %titles;
 8881: }
 8882: 
 8883: sub courserequest_titles {
 8884:     my %titles = &Apache::lonlocal::texthash (
 8885:                                    official   => 'Official',
 8886:                                    unofficial => 'Unofficial',
 8887:                                    community  => 'Communities',
 8888:                                    textbook   => 'Textbook',
 8889:                                    placement  => 'Placement tests',
 8890:                                    lti        => 'LTI Provider',
 8891:                                    norequest  => 'Not allowed',
 8892:                                    approval   => 'Approval by DC',
 8893:                                    validate   => 'With validation',
 8894:                                    autolimit  => 'Numerical limit',
 8895:                                    unlimited  => '(blank for unlimited)',
 8896:                  );
 8897:     return %titles;
 8898: }
 8899: 
 8900: sub authorrequest_titles {
 8901:     my %titles = &Apache::lonlocal::texthash (
 8902:                                    norequest  => 'Not allowed',
 8903:                                    approval   => 'Approval by Dom. Coord.',
 8904:                                    automatic  => 'Automatic approval',
 8905:                  );
 8906:     return %titles;
 8907: }
 8908: 
 8909: sub courserequest_conditions {
 8910:     my %conditions = &Apache::lonlocal::texthash (
 8911:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 8912:        validate   => '(Processing of request subject to institutional validation).',
 8913:                  );
 8914:     return %conditions;
 8915: }
 8916: 
 8917: 
 8918: sub print_usercreation {
 8919:     my ($position,$dom,$settings,$rowtotal) = @_;
 8920:     my $numinrow = 4;
 8921:     my $datatable;
 8922:     if ($position eq 'top') {
 8923:         $$rowtotal ++;
 8924:         my $rowcount = 0;
 8925:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 8926:         if (ref($rules) eq 'HASH') {
 8927:             if (keys(%{$rules}) > 0) {
 8928:                 $datatable .= &user_formats_row('username',$settings,$rules,
 8929:                                                 $ruleorder,$numinrow,$rowcount);
 8930:                 $$rowtotal ++;
 8931:                 $rowcount ++;
 8932:             }
 8933:         }
 8934:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 8935:         if (ref($idrules) eq 'HASH') {
 8936:             if (keys(%{$idrules}) > 0) {
 8937:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 8938:                                                 $idruleorder,$numinrow,$rowcount);
 8939:                 $$rowtotal ++;
 8940:                 $rowcount ++;
 8941:             }
 8942:         }
 8943:         if ($rowcount == 0) {
 8944:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 8945:             $$rowtotal ++;
 8946:             $rowcount ++;
 8947:         }
 8948:     } elsif ($position eq 'middle') {
 8949:         my @creators = ('author','course','requestcrs');
 8950:         my ($rules,$ruleorder) =
 8951:             &Apache::lonnet::inst_userrules($dom,'username');
 8952:         my %lt = &usercreation_types();
 8953:         my %checked;
 8954:         if (ref($settings) eq 'HASH') {
 8955:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 8956:                 foreach my $item (@creators) {
 8957:                     $checked{$item} = $settings->{'cancreate'}{$item};
 8958:                 }
 8959:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 8960:                 foreach my $item (@creators) {
 8961:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 8962:                         $checked{$item} = 'none';
 8963:                     }
 8964:                 }
 8965:             }
 8966:         }
 8967:         my $rownum = 0;
 8968:         foreach my $item (@creators) {
 8969:             $rownum ++;
 8970:             if ($checked{$item} eq '') {
 8971:                 $checked{$item} = 'any';
 8972:             }
 8973:             my $css_class;
 8974:             if ($rownum%2) {
 8975:                 $css_class = '';
 8976:             } else {
 8977:                 $css_class = ' class="LC_odd_row" ';
 8978:             }
 8979:             $datatable .= '<tr'.$css_class.'>'.
 8980:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 8981:                          '</span></td><td style="text-align: right">';
 8982:             my @options = ('any');
 8983:             if (ref($rules) eq 'HASH') {
 8984:                 if (keys(%{$rules}) > 0) {
 8985:                     push(@options,('official','unofficial'));
 8986:                 }
 8987:             }
 8988:             push(@options,'none');
 8989:             foreach my $option (@options) {
 8990:                 my $type = 'radio';
 8991:                 my $check = ' ';
 8992:                 if ($checked{$item} eq $option) {
 8993:                     $check = ' checked="checked" ';
 8994:                 } 
 8995:                 $datatable .= '<span class="LC_nobreak"><label>'.
 8996:                               '<input type="'.$type.'" name="can_createuser_'.
 8997:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 8998:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 8999:             }
 9000:             $datatable .= '</td></tr>';
 9001:         }
 9002:     } else {
 9003:         my @contexts = ('author','course','domain');
 9004:         my @authtypes = ('int','krb4','krb5','loc','lti');
 9005:         my %checked;
 9006:         if (ref($settings) eq 'HASH') {
 9007:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 9008:                 foreach my $item (@contexts) {
 9009:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 9010:                         foreach my $auth (@authtypes) {
 9011:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 9012:                                 $checked{$item}{$auth} = ' checked="checked" ';
 9013:                             }
 9014:                         }
 9015:                     }
 9016:                 }
 9017:             }
 9018:         } else {
 9019:             foreach my $item (@contexts) {
 9020:                 foreach my $auth (@authtypes) {
 9021:                     $checked{$item}{$auth} = ' checked="checked" ';
 9022:                 }
 9023:             }
 9024:         }
 9025:         my %title = &context_names();
 9026:         my %authname = &authtype_names();
 9027:         my $rownum = 0;
 9028:         my $css_class; 
 9029:         foreach my $item (@contexts) {
 9030:             if ($rownum%2) {
 9031:                 $css_class = '';
 9032:             } else {
 9033:                 $css_class = ' class="LC_odd_row" ';
 9034:             }
 9035:             $datatable .=   '<tr'.$css_class.'>'.
 9036:                             '<td>'.$title{$item}.
 9037:                             '</td><td class="LC_left_item">'.
 9038:                             '<span class="LC_nobreak">';
 9039:             foreach my $auth (@authtypes) {
 9040:                 $datatable .= '<label>'. 
 9041:                               '<input type="checkbox" name="'.$item.'_auth" '.
 9042:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 9043:                               $authname{$auth}.'</label>&nbsp;';
 9044:             }
 9045:             $datatable .= '</span></td></tr>';
 9046:             $rownum ++;
 9047:         }
 9048:         $$rowtotal += $rownum;
 9049:     }
 9050:     return $datatable;
 9051: }
 9052: 
 9053: sub print_selfcreation {
 9054:     my ($position,$dom,$settings,$rowtotal) = @_;
 9055:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 9056:         $emaildomain,$datatable);
 9057:     if (ref($settings) eq 'HASH') {
 9058:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 9059:             $createsettings = $settings->{'cancreate'};
 9060:             if (ref($createsettings) eq 'HASH') {
 9061:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 9062:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 9063:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 9064:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 9065:                         @selfcreate = ('email','login','sso');
 9066:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 9067:                         @selfcreate = ($createsettings->{'selfcreate'});
 9068:                     }
 9069:                 }
 9070:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 9071:                     $processing = $createsettings->{'selfcreateprocessing'};
 9072:                 }
 9073:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 9074:                     $emailoptions = $createsettings->{'emailoptions'};
 9075:                 }
 9076:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 9077:                     $emailverified = $createsettings->{'emailverified'};
 9078:                 }
 9079:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 9080:                     $emaildomain = $createsettings->{'emaildomain'};
 9081:                 }
 9082:             }
 9083:         }
 9084:     }
 9085:     my %radiohash;
 9086:     my $numinrow = 4;
 9087:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 9088:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9089:     if ($position eq 'top') {
 9090:         my %choices = &Apache::lonlocal::texthash (
 9091:                                                       cancreate_login      => 'Institutional Login',
 9092:                                                       cancreate_sso        => 'Institutional Single Sign On',
 9093:                                                   );
 9094:         my @toggles = sort(keys(%choices));
 9095:         my %defaultchecked = (
 9096:                                'cancreate_login' => 'off',
 9097:                                'cancreate_sso'   => 'off',
 9098:                              );
 9099:         my ($onclick,$itemcount);
 9100:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9101:                                                      \%choices,$itemcount,$onclick);
 9102:         $$rowtotal += $itemcount;
 9103:         
 9104:         if (ref($usertypes) eq 'HASH') {
 9105:             if (keys(%{$usertypes}) > 0) {
 9106:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 9107:                                              $dom,$numinrow,$othertitle,
 9108:                                              'statustocreate',$rowtotal);
 9109:                 $$rowtotal ++;
 9110:             }
 9111:         }
 9112:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 9113:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9114:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 9115:         my $rem;
 9116:         my $numperrow = 2;
 9117:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 9118:         $datatable .= '<tr'.$css_class.'>'.
 9119:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 9120:                      '<td class="LC_left_item">'."\n".
 9121:                      '<table>'."\n";
 9122:         for (my $i=0; $i<@fields; $i++) {
 9123:             $rem = $i%($numperrow);
 9124:             if ($rem == 0) {
 9125:                 if ($i > 0) {
 9126:                     $datatable .= '</tr>';
 9127:                 }
 9128:                 $datatable .= '<tr>';
 9129:             }
 9130:             my $currval;
 9131:             if (ref($createsettings) eq 'HASH') {
 9132:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 9133:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 9134:                 }
 9135:             }
 9136:             $datatable .= '<td class="LC_left_item">'.
 9137:                           '<span class="LC_nobreak">'.
 9138:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 9139:                           'value="'.$currval.'" size="10" />&nbsp;'.
 9140:                           $fieldtitles{$fields[$i]}.'</span></td>';
 9141:         }
 9142:         my $colsleft = $numperrow - $rem;
 9143:         if ($colsleft > 1 ) {
 9144:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9145:                          '&nbsp;</td>';
 9146:         } elsif ($colsleft == 1) {
 9147:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 9148:         }
 9149:         $datatable .= '</tr></table></td></tr>';
 9150:         $$rowtotal ++;
 9151:     } elsif ($position eq 'middle') {
 9152:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 9153:         my @posstypes;
 9154:         if (ref($types) eq 'ARRAY') {
 9155:             @posstypes = @{$types};
 9156:         }
 9157:         unless (grep(/^default$/,@posstypes)) {
 9158:             push(@posstypes,'default');
 9159:         }
 9160:         my %usertypeshash;
 9161:         if (ref($usertypes) eq 'HASH') {
 9162:             %usertypeshash = %{$usertypes};
 9163:         }
 9164:         $usertypeshash{'default'} = $othertitle;
 9165:         foreach my $status (@posstypes) {
 9166:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 9167:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 9168:             $$rowtotal ++;
 9169:         }
 9170:     } else {
 9171:         my %choices = &Apache::lonlocal::texthash (
 9172:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 9173:                                                   );
 9174:         my @toggles = sort(keys(%choices));
 9175:         my %defaultchecked = (
 9176:                                'cancreate_email' => 'off',
 9177:                              );
 9178:         my $customclass = 'LC_selfcreate_email';
 9179:         my $classprefix = 'LC_canmodify_emailusername_';
 9180:         my $optionsprefix = 'LC_options_emailusername_';
 9181:         my $display = 'none';
 9182:         my $rowstyle = 'display:none';
 9183:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 9184:             $display = 'block';
 9185:             $rowstyle = 'display:table-row';
 9186:         }
 9187:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 9188:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9189:                                                      \%choices,$$rowtotal,$onclick);
 9190:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 9191:                                          $rowstyle);
 9192:         $$rowtotal ++;
 9193:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 9194:                                       $rowstyle);
 9195:         $$rowtotal ++;
 9196:         my (@ordered,@posstypes,%usertypeshash);
 9197:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 9198:         my ($emailrules,$emailruleorder) =
 9199:             &Apache::lonnet::inst_userrules($dom,'email');
 9200:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 9201:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 9202:         if (ref($types) eq 'ARRAY') {
 9203:             @posstypes = @{$types};
 9204:         }
 9205:         if (@posstypes) {
 9206:             unless (grep(/^default$/,@posstypes)) {
 9207:                 push(@posstypes,'default');
 9208:             }
 9209:             if (ref($usertypes) eq 'HASH') {
 9210:                 %usertypeshash = %{$usertypes};
 9211:             }
 9212:             my $currassign;
 9213:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 9214:                 $currassign = {
 9215:                                   selfassign => $domdefaults{'inststatusguest'},
 9216:                               };
 9217:                 @ordered = @{$domdefaults{'inststatusguest'}};
 9218:             } else {
 9219:                 $currassign = { selfassign => [] };
 9220:             }
 9221:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 9222:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 9223:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 9224:                                          $numinrow,$othertitle,'selfassign',
 9225:                                          $rowtotal,$onclicktypes,$customclass,
 9226:                                          $rowstyle);
 9227:             $$rowtotal ++;
 9228:             $usertypeshash{'default'} = $othertitle;
 9229:             foreach my $status (@posstypes) {
 9230:                 my $css_class;
 9231:                 if ($$rowtotal%2) {
 9232:                     $css_class = 'LC_odd_row ';
 9233:                 }
 9234:                 $css_class .= $customclass;
 9235:                 my $rowid = $optionsprefix.$status;
 9236:                 my $hidden = 1;
 9237:                 my $currstyle = 'display:none';
 9238:                 if (grep(/^\Q$status\E$/,@ordered)) {
 9239:                     $currstyle = $rowstyle;
 9240:                     $hidden = 0; 
 9241:                 }
 9242:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9243:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 9244:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 9245:                 unless ($hidden) {
 9246:                     $$rowtotal ++;
 9247:                 }
 9248:             }
 9249:         } else {
 9250:             my $css_class;
 9251:             if ($$rowtotal%2) {
 9252:                 $css_class = 'LC_odd_row ';
 9253:             }
 9254:             $css_class .= $customclass;
 9255:             $usertypeshash{'default'} = $othertitle;
 9256:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9257:                                          $emailrules,$emailruleorder,$settings,'default','',
 9258:                                          $othertitle,$css_class,$rowstyle,$intdom);
 9259:             $$rowtotal ++;
 9260:         }
 9261:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 9262:         $numinrow = 1;
 9263:         if (@posstypes) {
 9264:             foreach my $status (@posstypes) {
 9265:                 my $rowid = $classprefix.$status;
 9266:                 my $datarowstyle = 'display:none';
 9267:                 if (grep(/^\Q$status\E$/,@ordered)) { 
 9268:                     $datarowstyle = $rowstyle; 
 9269:                 }
 9270:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 9271:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9272:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 9273:                 unless ($datarowstyle eq 'display:none') {
 9274:                     $$rowtotal ++;
 9275:                 }
 9276:             }
 9277:         } else {
 9278:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 9279:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9280:                                                    $infotitles,'',$customclass,$rowstyle);
 9281:         }
 9282:     }
 9283:     return $datatable;
 9284: }
 9285: 
 9286: sub selfcreate_javascript {
 9287:     return <<"ENDSCRIPT";
 9288: 
 9289: <script type="text/javascript">
 9290: // <![CDATA[
 9291: 
 9292: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 9293:     var x = document.getElementsByClassName(target);
 9294:     var insttypes = 0;
 9295:     var insttypeRegExp = new RegExp(prefix);
 9296:     if ((x.length != undefined) && (x.length > 0)) {
 9297:         if (form.elements[radio].length != undefined) {
 9298:             for (var i=0; i<form.elements[radio].length; i++) {
 9299:                 if (form.elements[radio][i].checked) {
 9300:                     if (form.elements[radio][i].value == 1) {
 9301:                         for (var j=0; j<x.length; j++) {
 9302:                             if (x[j].id == 'undefined') {
 9303:                                 x[j].style.display = 'table-row';
 9304:                             } else if (insttypeRegExp.test(x[j].id)) {
 9305:                                 insttypes ++;
 9306:                             } else {
 9307:                                 x[j].style.display = 'table-row';
 9308:                             }
 9309:                         }
 9310:                     } else {
 9311:                         for (var j=0; j<x.length; j++) {
 9312:                             x[j].style.display = 'none';
 9313:                         }
 9314:                     }
 9315:                     break;
 9316:                 }
 9317:             }
 9318:             if (insttypes > 0) {
 9319:                 toggleDataRow(form,checkbox,target,altprefix);
 9320:                 toggleDataRow(form,checkbox,target,prefix,1);
 9321:             }
 9322:         }
 9323:     }
 9324:     return;
 9325: }
 9326: 
 9327: function toggleDataRow(form,checkbox,target,prefix,docount) {
 9328:     if (form.elements[checkbox].length != undefined) {
 9329:         var count = 0;
 9330:         if (docount) {
 9331:             for (var i=0; i<form.elements[checkbox].length; i++) {
 9332:                 if (form.elements[checkbox][i].checked) {
 9333:                     count ++;
 9334:                 }
 9335:             }
 9336:         }
 9337:         for (var i=0; i<form.elements[checkbox].length; i++) {
 9338:             var type = form.elements[checkbox][i].value;
 9339:             if (document.getElementById(prefix+type)) {
 9340:                 if (form.elements[checkbox][i].checked) {
 9341:                     document.getElementById(prefix+type).style.display = 'table-row';
 9342:                     if (count % 2 == 1) {
 9343:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 9344:                     } else {
 9345:                         document.getElementById(prefix+type).className = target;
 9346:                     }
 9347:                     count ++;
 9348:                 } else {
 9349:                     document.getElementById(prefix+type).style.display = 'none';
 9350:                 }
 9351:             }
 9352:         }
 9353:     }
 9354:     return;
 9355: }
 9356: 
 9357: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 9358:     var caller = radio+'_'+status;
 9359:     if (form.elements[caller].length != undefined) {
 9360:         for (var i=0; i<form.elements[caller].length; i++) {
 9361:             if (form.elements[caller][i].checked) {
 9362:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 9363:                     var curr = form.elements[caller][i].value;
 9364:                     if (prefix) {
 9365:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 9366:                     }
 9367:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 9368:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 9369:                     if (curr == 'custom') {
 9370:                         if (prefix) { 
 9371:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 9372:                         }
 9373:                     } else if (curr == 'inst') {
 9374:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 9375:                     } else if (curr == 'noninst') {
 9376:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 9377:                     }
 9378:                     break;
 9379:                 }
 9380:             }
 9381:         }
 9382:     }
 9383: }
 9384: 
 9385: // ]]>
 9386: </script>
 9387: 
 9388: ENDSCRIPT
 9389: }
 9390: 
 9391: sub noninst_users {
 9392:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 9393:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
 9394:     my $class = 'LC_left_item';
 9395:     if ($css_class) {
 9396:         $css_class = ' class="'.$css_class.'"'; 
 9397:     }
 9398:     if ($rowid) {
 9399:         $rowid = ' id="'.$rowid.'"';
 9400:     }
 9401:     if ($rowstyle) {
 9402:         $rowstyle = ' style="'.$rowstyle.'"';
 9403:     }
 9404:     my ($output,$description);
 9405:     if ($type eq 'default') {
 9406:         $description = &mt('Requests for: [_1]',$typetitle);
 9407:     } else {
 9408:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 9409:     }
 9410:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 9411:               "<td>$description</td>\n".           
 9412:               '<td class="'.$class.'" colspan="2">'.
 9413:               '<table><tr>';
 9414:     my %headers = &Apache::lonlocal::texthash( 
 9415:               approve  => 'Processing',
 9416:               email    => 'E-mail',
 9417:               username => 'Username',
 9418:     );
 9419:     foreach my $item ('approve','email','username') {
 9420:         $output .= '<th>'.$headers{$item}.'</th>';
 9421:     }
 9422:     $output .= '</tr><tr>';
 9423:     foreach my $item ('approve','email','username') {
 9424:         $output .= '<td style="vertical-align: top">';
 9425:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 9426:         if ($item eq 'approve') {
 9427:             %choices = &Apache::lonlocal::texthash (
 9428:                                                      automatic => 'Automatically approved',
 9429:                                                      approval  => 'Queued for approval',
 9430:                                                    );
 9431:             @options = ('automatic','approval');
 9432:             $hashref = $processing;
 9433:             $defoption = 'automatic';
 9434:             $name = 'cancreate_emailprocess_'.$type;
 9435:         } elsif ($item eq 'email') {
 9436:             %choices = &Apache::lonlocal::texthash (
 9437:                                                      any     => 'Any e-mail',
 9438:                                                      inst    => 'Institutional only',
 9439:                                                      noninst => 'Non-institutional only',
 9440:                                                      custom  => 'Custom restrictions',
 9441:                                                    );
 9442:             @options = ('any','inst','noninst');
 9443:             my $showcustom;
 9444:             if (ref($emailrules) eq 'HASH') {
 9445:                 if (keys(%{$emailrules}) > 0) {
 9446:                     push(@options,'custom');
 9447:                     $showcustom = 'cancreate_emailrule';
 9448:                     if (ref($settings) eq 'HASH') {
 9449:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 9450:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 9451:                                 if (exists($emailrules->{$rule})) {
 9452:                                     $hascustom ++;
 9453:                                 }
 9454:                             }
 9455:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 9456:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 9457:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 9458:                                     if (exists($emailrules->{$rule})) {
 9459:                                         $hascustom ++;
 9460:                                     }
 9461:                                 }
 9462:                             }
 9463:                         }
 9464:                     }
 9465:                 }
 9466:             }
 9467:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 9468:                                                      "'cancreate_emaildomain','$type'".');"';
 9469:             $hashref = $emailoptions;
 9470:             $defoption = 'any';
 9471:             $name = 'cancreate_emailoptions_'.$type;
 9472:         } elsif ($item eq 'username') {
 9473:             %choices = &Apache::lonlocal::texthash (
 9474:                                                      all    => 'Same as e-mail',
 9475:                                                      first  => 'Omit @domain',
 9476:                                                      free   => 'Free to choose',
 9477:                                                    );
 9478:             @options = ('all','first','free');
 9479:             $hashref = $emailverified;
 9480:             $defoption = 'all';
 9481:             $name = 'cancreate_usernameoptions_'.$type;
 9482:         }
 9483:         foreach my $option (@options) {
 9484:             my $checked;
 9485:             if (ref($hashref) eq 'HASH') {
 9486:                 if ($type eq '') {
 9487:                     if (!exists($hashref->{'default'})) {
 9488:                         if ($option eq $defoption) {
 9489:                             $checked = ' checked="checked"';
 9490:                         }
 9491:                     } else {
 9492:                         if ($hashref->{'default'} eq $option) {
 9493:                             $checked = ' checked="checked"';
 9494:                         }
 9495:                     }
 9496:                 } else {
 9497:                     if (!exists($hashref->{$type})) {
 9498:                         if ($option eq $defoption) {
 9499:                             $checked = ' checked="checked"';
 9500:                         }
 9501:                     } else {
 9502:                         if ($hashref->{$type} eq $option) {
 9503:                             $checked = ' checked="checked"';
 9504:                         }
 9505:                     }
 9506:                 }
 9507:             } elsif (($item eq 'email') && ($hascustom)) {
 9508:                 if ($option eq 'custom') {
 9509:                     $checked = ' checked="checked"';
 9510:                 }
 9511:             } elsif ($option eq $defoption) {
 9512:                 $checked = ' checked="checked"';
 9513:             }
 9514:             $output .= '<span class="LC_nobreak"><label>'.
 9515:                        '<input type="radio" name="'.$name.'"'.
 9516:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 9517:                        $choices{$option}.'</label></span><br />';
 9518:             if ($item eq 'email') {
 9519:                 if ($option eq 'custom') {
 9520:                     my $id = 'cancreate_emailrule_'.$type;
 9521:                     my $display = 'none';
 9522:                     if ($checked) {
 9523:                         $display = 'inline';
 9524:                     }
 9525:                     my $numinrow = 2;
 9526:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 9527:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 9528:                                &user_formats_row('email',$settings,$emailrules,
 9529:                                                  $emailruleorder,$numinrow,'',$type);
 9530:                               '</table></fieldset>';
 9531:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 9532:                     my %text = &Apache::lonlocal::texthash (
 9533:                                                              inst    => 'must end:',
 9534:                                                              noninst => 'cannot end:',
 9535:                                                            );
 9536:                     my $value;
 9537:                     if (ref($emaildomain) eq 'HASH') {
 9538:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 9539:                             $value = $emaildomain->{$type}->{$option}; 
 9540:                         }
 9541:                     }
 9542:                     if ($value eq '') {
 9543:                         $value = '@'.$intdom;
 9544:                     }
 9545:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 9546:                     my $display = 'none';
 9547:                     if ($checked) {
 9548:                         $display = 'inline';
 9549:                     }
 9550:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 9551:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 9552:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 9553:                                '</div>';
 9554:                 }
 9555:             }
 9556:         }
 9557:         $output .= '</td>'."\n";
 9558:     }
 9559:     $output .= "</tr></table></td></tr>\n";
 9560:     return $output;
 9561: }
 9562: 
 9563: sub captcha_choice {
 9564:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 9565:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 9566:         $vertext,$currver);
 9567:     my %lt = &captcha_phrases();
 9568:     $keyentry = 'hidden';
 9569:     my $colspan=2;
 9570:     if ($context eq 'cancreate') {
 9571:         $rowname = &mt('CAPTCHA validation');
 9572:     } elsif ($context eq 'login') {
 9573:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 9574:     } elsif ($context eq 'passwords') {
 9575:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 9576:         $colspan=1;
 9577:     }
 9578:     if (ref($settings) eq 'HASH') {
 9579:         if ($settings->{'captcha'}) {
 9580:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 9581:         } else {
 9582:             $checked{'original'} = ' checked="checked"';
 9583:         }
 9584:         if ($settings->{'captcha'} eq 'recaptcha') {
 9585:             $pubtext = $lt{'pub'};
 9586:             $privtext = $lt{'priv'};
 9587:             $keyentry = 'text';
 9588:             $vertext = $lt{'ver'};
 9589:             $currver = $settings->{'recaptchaversion'};
 9590:             if ($currver ne '2') {
 9591:                 $currver = 1;
 9592:             }
 9593:         }
 9594:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 9595:             $currpub = $settings->{'recaptchakeys'}{'public'};
 9596:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 9597:         }
 9598:     } else {
 9599:         $checked{'original'} = ' checked="checked"';
 9600:     }
 9601:     my $css_class;
 9602:     if ($itemcount%2) {
 9603:         $css_class = 'LC_odd_row';
 9604:     }
 9605:     if ($customcss) {
 9606:         $css_class .= " $customcss";
 9607:     }
 9608:     $css_class =~ s/^\s+//;
 9609:     if ($css_class) {
 9610:         $css_class = ' class="'.$css_class.'"';
 9611:     }
 9612:     if ($rowstyle) {
 9613:         $css_class .= ' style="'.$rowstyle.'"';
 9614:     }
 9615:     my $output = '<tr'.$css_class.'>'.
 9616:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 9617:                  '<table><tr><td>'."\n";
 9618:     foreach my $option ('original','recaptcha','notused') {
 9619:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 9620:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 9621:                    $lt{$option}.'</label></span>';
 9622:         unless ($option eq 'notused') {
 9623:             $output .= ('&nbsp;'x2)."\n";
 9624:         }
 9625:     }
 9626: #
 9627: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 9628: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 9629: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 9630: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 9631: #
 9632:     $output .= '</td></tr>'."\n".
 9633:                '<tr><td class="LC_zero_height">'."\n".
 9634:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 9635:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 9636:                $currpub.'" size="40" /></span><br />'."\n".
 9637:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 9638:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 9639:                $currpriv.'" size="40" /></span><br />'.
 9640:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 9641:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 9642:                $currver.'" size="3" /></span><br />'.
 9643:                '</td></tr></table>'."\n".
 9644:                '</td></tr>';
 9645:     return $output;
 9646: }
 9647: 
 9648: sub user_formats_row {
 9649:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 9650:     my $output;
 9651:     my %text = (
 9652:                    'username' => 'new usernames',
 9653:                    'id'       => 'IDs',
 9654:                );
 9655:     unless ($type eq 'email') {
 9656:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 9657:         $output = '<tr '.$css_class.'>'.
 9658:                   '<td><span class="LC_nobreak">'.
 9659:                   &mt("Format rules to check for $text{$type}: ").
 9660:                   '</td><td class="LC_left_item" colspan="2"><table>';
 9661:     }
 9662:     my $rem;
 9663:     if (ref($ruleorder) eq 'ARRAY') {
 9664:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 9665:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 9666:                 my $rem = $i%($numinrow);
 9667:                 if ($rem == 0) {
 9668:                     if ($i > 0) {
 9669:                         $output .= '</tr>';
 9670:                     }
 9671:                     $output .= '<tr>';
 9672:                 }
 9673:                 my $check = ' ';
 9674:                 if (ref($settings) eq 'HASH') {
 9675:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 9676:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 9677:                             $check = ' checked="checked" ';
 9678:                         }
 9679:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 9680:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 9681:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 9682:                                 $check = ' checked="checked" ';
 9683:                             }
 9684:                         }
 9685:                     }
 9686:                 }
 9687:                 my $name = $type.'_rule';
 9688:                 if ($type eq 'email') {
 9689:                     $name .= '_'.$status;
 9690:                 }
 9691:                 $output .= '<td class="LC_left_item">'.
 9692:                            '<span class="LC_nobreak"><label>'.
 9693:                            '<input type="checkbox" name="'.$name.'" '.
 9694:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 9695:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 9696:             }
 9697:         }
 9698:         $rem = @{$ruleorder}%($numinrow);
 9699:     }
 9700:     my $colsleft;
 9701:     if ($rem) {
 9702:         $colsleft = $numinrow - $rem;
 9703:     }
 9704:     if ($colsleft > 1 ) {
 9705:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9706:                    '&nbsp;</td>';
 9707:     } elsif ($colsleft == 1) {
 9708:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 9709:     }
 9710:     $output .= '</tr></table>';
 9711:     unless ($type eq 'email') {
 9712:         $output .= '</td></tr>';
 9713:     }
 9714:     return $output;
 9715: }
 9716: 
 9717: sub usercreation_types {
 9718:     my %lt = &Apache::lonlocal::texthash (
 9719:                     author     => 'When adding a co-author',
 9720:                     course     => 'When adding a user to a course',
 9721:                     requestcrs => 'When requesting a course',
 9722:                     any        => 'Any',
 9723:                     official   => 'Institutional only ',
 9724:                     unofficial => 'Non-institutional only',
 9725:                     none       => 'None',
 9726:     );
 9727:     return %lt;
 9728: }
 9729: 
 9730: sub selfcreation_types {
 9731:     my %lt = &Apache::lonlocal::texthash (
 9732:                     selfcreate => 'User creates own account',
 9733:                     any        => 'Any',
 9734:                     official   => 'Institutional only ',
 9735:                     unofficial => 'Non-institutional only',
 9736:                     email      => 'E-mail address',
 9737:                     login      => 'Institutional Login',
 9738:                     sso        => 'SSO',
 9739:              );
 9740: }
 9741: 
 9742: sub authtype_names {
 9743:     my %lt = &Apache::lonlocal::texthash(
 9744:                       int    => 'Internal',
 9745:                       krb4   => 'Kerberos 4',
 9746:                       krb5   => 'Kerberos 5',
 9747:                       loc    => 'Local',
 9748:                       lti    => 'LTI',
 9749:                   );
 9750:     return %lt;
 9751: }
 9752: 
 9753: sub context_names {
 9754:     my %context_title = &Apache::lonlocal::texthash(
 9755:        author => 'Creating users when an Author',
 9756:        course => 'Creating users when in a course',
 9757:        domain => 'Creating users when a Domain Coordinator',
 9758:     );
 9759:     return %context_title;
 9760: }
 9761: 
 9762: sub print_usermodification {
 9763:     my ($position,$dom,$settings,$rowtotal) = @_;
 9764:     my $numinrow = 4;
 9765:     my ($context,$datatable,$rowcount);
 9766:     if ($position eq 'top') {
 9767:         $rowcount = 0;
 9768:         $context = 'author'; 
 9769:         foreach my $role ('ca','aa') {
 9770:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9771:                                                    $numinrow,$rowcount);
 9772:             $$rowtotal ++;
 9773:             $rowcount ++;
 9774:         }
 9775:     } elsif ($position eq 'bottom') {
 9776:         $context = 'course';
 9777:         $rowcount = 0;
 9778:         foreach my $role ('st','ep','ta','in','cr') {
 9779:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9780:                                                    $numinrow,$rowcount);
 9781:             $$rowtotal ++;
 9782:             $rowcount ++;
 9783:         }
 9784:     }
 9785:     return $datatable;
 9786: }
 9787: 
 9788: sub print_defaults {
 9789:     my ($position,$dom,$settings,$rowtotal) = @_;
 9790:     my $rownum = 0;
 9791:     my ($datatable,$css_class,$titles);
 9792:     unless ($position eq 'bottom') {
 9793:         $titles = &defaults_titles($dom);
 9794:     }
 9795:     if ($position eq 'top') {
 9796:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 9797:                      'datelocale_def','portal_def');
 9798:         my %defaults;
 9799:         if (ref($settings) eq 'HASH') {
 9800:             %defaults = %{$settings};
 9801:         } else {
 9802:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 9803:             foreach my $item (@items) {
 9804:                 $defaults{$item} = $domdefaults{$item};
 9805:             }
 9806:         }
 9807:         foreach my $item (@items) {
 9808:             if ($rownum%2) {
 9809:                 $css_class = '';
 9810:             } else {
 9811:                 $css_class = ' class="LC_odd_row" ';
 9812:             }
 9813:             $datatable .= '<tr'.$css_class.'>'.
 9814:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 9815:                           '</span></td><td class="LC_right_item" colspan="3">';
 9816:             if ($item eq 'auth_def') {
 9817:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
 9818:                 my %shortauth = (
 9819:                                  internal => 'int',
 9820:                                  krb4 => 'krb4',
 9821:                                  krb5 => 'krb5',
 9822:                                  localauth  => 'loc',
 9823:                                  lti => 'lti',
 9824:                                 );
 9825:                 my %authnames = &authtype_names();
 9826:                 foreach my $auth (@authtypes) {
 9827:                     my $checked = ' ';
 9828:                     if ($defaults{$item} eq $auth) {
 9829:                         $checked = ' checked="checked" ';
 9830:                     }
 9831:                     $datatable .= '<label><input type="radio" name="'.$item.
 9832:                                   '" value="'.$auth.'"'.$checked.'/>'.
 9833:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 9834:                 }
 9835:             } elsif ($item eq 'timezone_def') {
 9836:                 my $includeempty = 1;
 9837:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 9838:             } elsif ($item eq 'datelocale_def') {
 9839:                 my $includeempty = 1;
 9840:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 9841:             } elsif ($item eq 'lang_def') {
 9842:                 my $includeempty = 1;
 9843:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 9844:             } else {
 9845:                 my $size;
 9846:                 if ($item eq 'portal_def') {
 9847:                     $size = ' size="25"';
 9848:                 }
 9849:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 9850:                               $defaults{$item}.'"'.$size.' />';
 9851:             }
 9852:             $datatable .= '</td></tr>';
 9853:             $rownum ++;
 9854:         }
 9855:     } else {
 9856:         my %defaults;
 9857:         if (ref($settings) eq 'HASH') {
 9858:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9859:                 my $maxnum = @{$settings->{'inststatusorder'}};
 9860:                 for (my $i=0; $i<$maxnum; $i++) {
 9861:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 9862:                     my $item = $settings->{'inststatusorder'}->[$i];
 9863:                     my $title = $settings->{'inststatustypes'}->{$item};
 9864:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 9865:                     $datatable .= '<tr'.$css_class.'>'.
 9866:                                   '<td><span class="LC_nobreak">'.
 9867:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 9868:                     for (my $k=0; $k<=$maxnum; $k++) {
 9869:                         my $vpos = $k+1;
 9870:                         my $selstr;
 9871:                         if ($k == $i) {
 9872:                             $selstr = ' selected="selected" ';
 9873:                         }
 9874:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9875:                     }
 9876:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 9877:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 9878:                                   &mt('delete').'</span></td>'.
 9879:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 9880:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 9881:                                   '</span></td></tr>';
 9882:                 }
 9883:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 9884:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 9885:                 $datatable .= '<tr '.$css_class.'>'.
 9886:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 9887:                 for (my $k=0; $k<=$maxnum; $k++) {
 9888:                     my $vpos = $k+1;
 9889:                     my $selstr;
 9890:                     if ($k == $maxnum) {
 9891:                         $selstr = ' selected="selected" ';
 9892:                     }
 9893:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9894:                 }
 9895:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 9896:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 9897:                               '&nbsp;'.&mt('(new)').
 9898:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
 9899:                               &mt('Name displayed').':'.
 9900:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 9901:                               '</tr>'."\n";
 9902:                 $rownum ++;
 9903:             }
 9904:         }
 9905:     }
 9906:     $$rowtotal += $rownum;
 9907:     return $datatable;
 9908: }
 9909: 
 9910: sub get_languages_hash {
 9911:     my %langchoices;
 9912:     foreach my $id (&Apache::loncommon::languageids()) {
 9913:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 9914:         if ($code ne '') {
 9915:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 9916:         }
 9917:     }
 9918:     return %langchoices;
 9919: }
 9920: 
 9921: sub defaults_titles {
 9922:     my ($dom) = @_;
 9923:     my %titles = &Apache::lonlocal::texthash (
 9924:                    'auth_def'      => 'Default authentication type',
 9925:                    'auth_arg_def'  => 'Default authentication argument',
 9926:                    'lang_def'      => 'Default language',
 9927:                    'timezone_def'  => 'Default timezone',
 9928:                    'datelocale_def' => 'Default locale for dates',
 9929:                    'portal_def'     => 'Portal/Default URL',
 9930:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 9931:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 9932:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 9933:                  );
 9934:     if ($dom) {
 9935:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 9936:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 9937:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 9938:         $protocol = 'http' if ($protocol ne 'https');
 9939:         if ($uint_dom) {
 9940:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 9941:                                          $uint_dom);
 9942:         }
 9943:     }
 9944:     return (\%titles);
 9945: }
 9946: 
 9947: sub print_scantron {
 9948:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 9949:     if ($position eq 'top') {
 9950:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 9951:     } else {
 9952:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 9953:     }
 9954: }
 9955: 
 9956: sub scantron_javascript {
 9957:     return <<"ENDSCRIPT";
 9958: 
 9959: <script type="text/javascript">
 9960: // <![CDATA[
 9961: 
 9962: function toggleScantron(form) {
 9963:     var csvfieldset = new Array();
 9964:     if (document.getElementById('scantroncsv_cols')) {
 9965:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 9966:     }
 9967:     if (document.getElementById('scantroncsv_options')) {
 9968:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 9969:     }
 9970:     if (csvfieldset.length) {
 9971:         if (document.getElementById('scantronconfcsv')) {
 9972:             var scantroncsv = document.getElementById('scantronconfcsv');
 9973:             if (scantroncsv.checked) {
 9974:                 for (var i=0; i<csvfieldset.length; i++) {
 9975:                     csvfieldset[i].style.display = 'block';
 9976:                 }
 9977:             } else {
 9978:                 for (var i=0; i<csvfieldset.length; i++) {
 9979:                     csvfieldset[i].style.display = 'none';
 9980:                 }
 9981:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 9982:                 if (csvselects.length) {
 9983:                     for (var j=0; j<csvselects.length; j++) {
 9984:                         csvselects[j].selectedIndex = 0;
 9985:                     }
 9986:                 }
 9987:             }
 9988:         }
 9989:     }
 9990:     return;
 9991: }
 9992: // ]]>
 9993: </script>
 9994: 
 9995: ENDSCRIPT
 9996: 
 9997: }
 9998: 
 9999: sub print_scantronformat {
10000:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
10001:     my $itemcount = 1;
10002:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
10003:         %confhash);
10004:     my $switchserver = &check_switchserver($dom,$confname);
10005:     my %lt = &Apache::lonlocal::texthash (
10006:                 default => 'Default bubblesheet format file error',
10007:                 custom  => 'Custom bubblesheet format file error',
10008:              );
10009:     my %scantronfiles = (
10010:         default => 'default.tab',
10011:         custom => 'custom.tab',
10012:     );
10013:     foreach my $key (keys(%scantronfiles)) {
10014:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
10015:                               .$scantronfiles{$key};
10016:     }
10017:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
10018:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
10019:         if (!$switchserver) {
10020:             my $servadm = $r->dir_config('lonAdmEMail');
10021:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
10022:             if ($configuserok eq 'ok') {
10023:                 if ($author_ok eq 'ok') {
10024:                     my %legacyfile = (
10025:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
10026:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
10027:                     );
10028:                     my %md5chk;
10029:                     foreach my $type (keys(%legacyfile)) {
10030:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
10031:                         chomp($md5chk{$type});
10032:                     }
10033:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
10034:                         foreach my $type (keys(%legacyfile)) {
10035:                             ($scantronurls{$type},my $error) =
10036:                                 &legacy_scantronformat($r,$dom,$confname,
10037:                                                  $type,$legacyfile{$type},
10038:                                                  $scantronurls{$type},
10039:                                                  $scantronfiles{$type});
10040:                             if ($error ne '') {
10041:                                 $error{$type} = $error;
10042:                             }
10043:                         }
10044:                         if (keys(%error) == 0) {
10045:                             $is_custom = 1;
10046:                             $confhash{'scantron'}{'scantronformat'} =
10047:                                 $scantronurls{'custom'};
10048:                             my $putresult =
10049:                                 &Apache::lonnet::put_dom('configuration',
10050:                                                          \%confhash,$dom);
10051:                             if ($putresult ne 'ok') {
10052:                                 $error{'custom'} =
10053:                                     '<span class="LC_error">'.
10054:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10055:                             }
10056:                         }
10057:                     } else {
10058:                         ($scantronurls{'default'},my $error) =
10059:                             &legacy_scantronformat($r,$dom,$confname,
10060:                                           'default',$legacyfile{'default'},
10061:                                           $scantronurls{'default'},
10062:                                           $scantronfiles{'default'});
10063:                         if ($error eq '') {
10064:                             $confhash{'scantron'}{'scantronformat'} = ''; 
10065:                             my $putresult =
10066:                                 &Apache::lonnet::put_dom('configuration',
10067:                                                          \%confhash,$dom);
10068:                             if ($putresult ne 'ok') {
10069:                                 $error{'default'} =
10070:                                     '<span class="LC_error">'.
10071:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10072:                             }
10073:                         } else {
10074:                             $error{'default'} = $error;
10075:                         }
10076:                     }
10077:                 }
10078:             }
10079:         } else {
10080:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
10081:         }
10082:     }
10083:     if (ref($settings) eq 'HASH') {
10084:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
10085:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
10086:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
10087:                 $scantronurl = '';
10088:             } else {
10089:                 $scantronurl = $settings->{'scantronformat'};
10090:             }
10091:             $is_custom = 1;
10092:         } else {
10093:             $scantronurl = $scantronurls{'default'};
10094:         }
10095:     } else {
10096:         if ($is_custom) {
10097:             $scantronurl = $scantronurls{'custom'};
10098:         } else {
10099:             $scantronurl = $scantronurls{'default'};
10100:         }
10101:     }
10102:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10103:     $datatable .= '<tr'.$css_class.'>';
10104:     if (!$is_custom) {
10105:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
10106:                       '<span class="LC_nobreak">';
10107:         if ($scantronurl) {
10108:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
10109:                                                          undef,undef,undef,undef,'background-color:#ffffff');
10110:         } else {
10111:             $datatable = &mt('File unavailable for display');
10112:         }
10113:         $datatable .= '</span></td>';
10114:         if (keys(%error) == 0) { 
10115:             $datatable .= '<td style="vertical-align: bottom">';
10116:             if (!$switchserver) {
10117:                 $datatable .= &mt('Upload:').'<br />';
10118:             }
10119:         } else {
10120:             my $errorstr;
10121:             foreach my $key (sort(keys(%error))) {
10122:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10123:             }
10124:             $datatable .= '<td>'.$errorstr;
10125:         }
10126:     } else {
10127:         if (keys(%error) > 0) {
10128:             my $errorstr;
10129:             foreach my $key (sort(keys(%error))) {
10130:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10131:             } 
10132:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
10133:         } elsif ($scantronurl) {
10134:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
10135:                                                        undef,undef,undef,undef,'background-color:#ffffff');
10136:             $datatable .= '<td><span class="LC_nobreak">'.
10137:                           $link.
10138:                           '<label><input type="checkbox" name="scantronformat_del"'.
10139:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
10140:                           '<td><span class="LC_nobreak">&nbsp;'.
10141:                           &mt('Replace:').'</span><br />';
10142:         }
10143:     }
10144:     if (keys(%error) == 0) {
10145:         if ($switchserver) {
10146:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
10147:         } else {
10148:             $datatable .='<span class="LC_nobreak">&nbsp;'.
10149:                          '<input type="file" name="scantronformat" /></span>';
10150:         }
10151:     }
10152:     $datatable .= '</td></tr>';
10153:     $$rowtotal ++;
10154:     return $datatable;
10155: }
10156: 
10157: sub legacy_scantronformat {
10158:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
10159:     my ($url,$error);
10160:     my @statinfo = &Apache::lonnet::stat_file($newurl);
10161:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
10162:         (my $result,$url) =
10163:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
10164:                          '','',$newfile);
10165:         if ($result ne 'ok') {
10166:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
10167:         }
10168:     }
10169:     return ($url,$error);
10170: }
10171: 
10172: sub print_scantronconfig {
10173:     my ($dom,$settings,$rowtotal) = @_;
10174:     my $itemcount = 2;
10175:     my $is_checked = ' checked="checked"';
10176:     my %optionson = (
10177:                      hdr => ' checked="checked"',
10178:                      pad => ' checked="checked"',
10179:                      rem => ' checked="checked"',
10180:                     );
10181:     my %optionsoff = (
10182:                       hdr => '',
10183:                       pad => '',
10184:                       rem => '',
10185:                      );
10186:     my $currcsvsty = 'none';
10187:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
10188:     my @fields = &scantroncsv_fields();
10189:     my %titles = &scantronconfig_titles();
10190:     if (ref($settings) eq 'HASH') {
10191:         if (ref($settings->{config}) eq 'HASH') {
10192:             if ($settings->{config}->{dat}) {
10193:                 $checked{'dat'} = $is_checked;
10194:             }
10195:             if (ref($settings->{config}->{csv}) eq 'HASH') {
10196:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
10197:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
10198:                     if (keys(%csvfields) > 0) {
10199:                         $checked{'csv'} = $is_checked;
10200:                         $currcsvsty = 'block';
10201:                     }
10202:                 }
10203:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
10204:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
10205:                     foreach my $option (keys(%optionson)) {
10206:                         unless ($csvoptions{$option}) {
10207:                             $optionsoff{$option} = $optionson{$option};
10208:                             $optionson{$option} = '';
10209:                         }
10210:                     }
10211:                 }
10212:             }
10213:         } else {
10214:             $checked{'dat'} = $is_checked;
10215:         }
10216:     } else {
10217:         $checked{'dat'} = $is_checked;
10218:     }
10219:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
10220:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
10221:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
10222:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
10223:     foreach my $item ('dat','csv') {
10224:         my $id;
10225:         if ($item eq 'csv') {
10226:             $id = 'id="scantronconfcsv" ';
10227:         }
10228:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
10229:                       $titles{$item}.'</label>'.('&nbsp;'x3);
10230:         if ($item eq 'csv') {
10231:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
10232:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
10233:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
10234:             foreach my $col (@fields) {
10235:                 my $selnone;
10236:                 if ($csvfields{$col} eq '') {
10237:                     $selnone = ' selected="selected"';
10238:                 }
10239:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
10240:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
10241:                               '<option value=""'.$selnone.'></option>';
10242:                 for (my $i=0; $i<20; $i++) {
10243:                     my $shown = $i+1;
10244:                     my $sel;
10245:                     unless ($selnone) {
10246:                         if (exists($csvfields{$col})) {
10247:                             if ($csvfields{$col} == $i) {
10248:                                 $sel = ' selected="selected"';
10249:                             }
10250:                         }
10251:                     }
10252:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
10253:                 }
10254:                 $datatable .= '</select></td></tr>';
10255:            }
10256:            $datatable .= '</table></fieldset>'.
10257:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
10258:                          '<legend>'.&mt('CSV Options').'</legend>';
10259:            foreach my $option ('hdr','pad','rem') {
10260:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
10261:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
10262:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
10263:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
10264:            }
10265:            $datatable .= '</fieldset>';
10266:            $itemcount ++;
10267:         }
10268:     }
10269:     $datatable .= '</td></tr>';
10270:     $$rowtotal ++;
10271:     return $datatable;
10272: }
10273: 
10274: sub scantronconfig_titles {
10275:     return &Apache::lonlocal::texthash(
10276:                                           dat => 'Standard format (.dat)',
10277:                                           csv => 'Comma separated values (.csv)',
10278:                                           hdr => 'Remove first line in file (contains column titles)',
10279:                                           pad => 'Prepend 0s to PaperID',
10280:                                           rem => 'Remove leading spaces (except Question Response columns)',
10281:                                           CODE => 'CODE',
10282:                                           ID   => 'Student ID',
10283:                                           PaperID => 'Paper ID',
10284:                                           FirstName => 'First Name',
10285:                                           LastName => 'Last Name',
10286:                                           FirstQuestion => 'First Question Response',
10287:                                           Section => 'Section',
10288:     );
10289: }
10290: 
10291: sub scantroncsv_fields {
10292:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
10293: }
10294: 
10295: sub print_coursecategories {
10296:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
10297:     my $datatable;
10298:     if ($position eq 'top') {
10299:         my (%checked);
10300:         my @catitems = ('unauth','auth');
10301:         my @cattypes = ('std','domonly','codesrch','none');
10302:         $checked{'unauth'} = 'std';
10303:         $checked{'auth'} = 'std';
10304:         if (ref($settings) eq 'HASH') {
10305:             foreach my $type (@cattypes) {
10306:                 if ($type eq $settings->{'unauth'}) {
10307:                     $checked{'unauth'} = $type;
10308:                 }
10309:                 if ($type eq $settings->{'auth'}) {
10310:                     $checked{'auth'} = $type;
10311:                 }
10312:             }
10313:         }
10314:         my %lt = &Apache::lonlocal::texthash (
10315:                                                unauth   => 'Catalog type for unauthenticated users',
10316:                                                auth     => 'Catalog type for authenticated users',
10317:                                                none     => 'No catalog',
10318:                                                std      => 'Standard catalog',
10319:                                                domonly  => 'Domain-only catalog',
10320:                                                codesrch => "Code search form",
10321:                                              );
10322:        my $itemcount = 0;
10323:        foreach my $item (@catitems) {
10324:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
10325:            $datatable .= '<tr '.$css_class.'>'.
10326:                          '<td>'.$lt{$item}.'</td>'.
10327:                          '<td class="LC_right_item"><span class="LC_nobreak">';
10328:            foreach my $type (@cattypes) {
10329:                my $ischecked;
10330:                if ($checked{$item} eq $type) {
10331:                    $ischecked=' checked="checked"';
10332:                }
10333:                $datatable .= '<label>'.
10334:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
10335:                              ' />'.$lt{$type}.'</label>&nbsp;';
10336:            }
10337:            $datatable .= '</span></td></tr>';
10338:            $itemcount ++;
10339:         }
10340:         $$rowtotal += $itemcount;
10341:     } elsif ($position eq 'middle') {
10342:         my $toggle_cats_crs = ' ';
10343:         my $toggle_cats_dom = ' checked="checked" ';
10344:         my $can_cat_crs = ' ';
10345:         my $can_cat_dom = ' checked="checked" ';
10346:         my $toggle_catscomm_comm = ' ';
10347:         my $toggle_catscomm_dom = ' checked="checked" ';
10348:         my $can_catcomm_comm = ' ';
10349:         my $can_catcomm_dom = ' checked="checked" ';
10350:         my $toggle_catsplace_place = ' ';
10351:         my $toggle_catsplace_dom = ' checked="checked" ';
10352:         my $can_catplace_place = ' ';
10353:         my $can_catplace_dom = ' checked="checked" ';
10354: 
10355:         if (ref($settings) eq 'HASH') {
10356:             if ($settings->{'togglecats'} eq 'crs') {
10357:                 $toggle_cats_crs = $toggle_cats_dom;
10358:                 $toggle_cats_dom = ' ';
10359:             }
10360:             if ($settings->{'categorize'} eq 'crs') {
10361:                 $can_cat_crs = $can_cat_dom;
10362:                 $can_cat_dom = ' ';
10363:             }
10364:             if ($settings->{'togglecatscomm'} eq 'comm') {
10365:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
10366:                 $toggle_catscomm_dom = ' ';
10367:             }
10368:             if ($settings->{'categorizecomm'} eq 'comm') {
10369:                 $can_catcomm_comm = $can_catcomm_dom;
10370:                 $can_catcomm_dom = ' ';
10371:             }
10372:             if ($settings->{'togglecatsplace'} eq 'place') {
10373:                 $toggle_catsplace_place = $toggle_catsplace_dom;
10374:                 $toggle_catsplace_dom = ' ';
10375:             }
10376:             if ($settings->{'categorizeplace'} eq 'place') {
10377:                 $can_catplace_place = $can_catplace_dom;
10378:                 $can_catplace_dom = ' ';
10379:             }
10380:         }
10381:         my %title = &Apache::lonlocal::texthash (
10382:                      togglecats      => 'Show/Hide a course in catalog',
10383:                      togglecatscomm  => 'Show/Hide a community in catalog',
10384:                      togglecatsplace => 'Show/Hide a placement test in catalog',
10385:                      categorize      => 'Assign a category to a course',
10386:                      categorizecomm  => 'Assign a category to a community',
10387:                      categorizeplace => 'Assign a category to a placement test',
10388:                     );
10389:         my %level = &Apache::lonlocal::texthash (
10390:                      dom   => 'Set in Domain',
10391:                      crs   => 'Set in Course',
10392:                      comm  => 'Set in Community',
10393:                      place => 'Set in Placement Test',
10394:                     );
10395:         $datatable = '<tr class="LC_odd_row">'.
10396:                   '<td>'.$title{'togglecats'}.'</td>'.
10397:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10398:                   '<input type="radio" name="togglecats"'.
10399:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10400:                   '<label><input type="radio" name="togglecats"'.
10401:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
10402:                   '</tr><tr>'.
10403:                   '<td>'.$title{'categorize'}.'</td>'.
10404:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10405:                   '<label><input type="radio" name="categorize"'.
10406:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10407:                   '<label><input type="radio" name="categorize"'.
10408:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
10409:                   '</tr><tr class="LC_odd_row">'.
10410:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
10411:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10412:                   '<input type="radio" name="togglecatscomm"'.
10413:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10414:                   '<label><input type="radio" name="togglecatscomm"'.
10415:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
10416:                   '</tr><tr>'.
10417:                   '<td>'.$title{'categorizecomm'}.'</td>'.
10418:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10419:                   '<label><input type="radio" name="categorizecomm"'.
10420:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10421:                   '<label><input type="radio" name="categorizecomm"'.
10422:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
10423:                   '</tr><tr class="LC_odd_row">'.
10424:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
10425:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10426:                   '<input type="radio" name="togglecatsplace"'.
10427:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10428:                   '<label><input type="radio" name="togglecatscomm"'.
10429:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
10430:                   '</tr><tr>'.
10431:                   '<td>'.$title{'categorizeplace'}.'</td>'.
10432:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10433:                   '<label><input type="radio" name="categorizeplace"'.
10434:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10435:                   '<label><input type="radio" name="categorizeplace"'.
10436:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
10437:                   '</tr>';
10438:         $$rowtotal += 6;
10439:     } else {
10440:         my $css_class;
10441:         my $itemcount = 1;
10442:         my $cathash; 
10443:         if (ref($settings) eq 'HASH') {
10444:             $cathash = $settings->{'cats'};
10445:         }
10446:         if (ref($cathash) eq 'HASH') {
10447:             my (@cats,@trails,%allitems,%idx,@jsarray);
10448:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
10449:                                                    \%allitems,\%idx,\@jsarray);
10450:             my $maxdepth = scalar(@cats);
10451:             my $colattrib = '';
10452:             if ($maxdepth > 2) {
10453:                 $colattrib = ' colspan="2" ';
10454:             }
10455:             my @path;
10456:             if (@cats > 0) {
10457:                 if (ref($cats[0]) eq 'ARRAY') {
10458:                     my $numtop = @{$cats[0]};
10459:                     my $maxnum = $numtop;
10460:                     my %default_names = (
10461:                           instcode    => &mt('Official courses'),
10462:                           communities => &mt('Communities'),
10463:                           placement   => &mt('Placement Tests'),
10464:                     );
10465: 
10466:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
10467:                         ($cathash->{'instcode::0'} eq '') ||
10468:                         (!grep(/^communities$/,@{$cats[0]})) || 
10469:                         ($cathash->{'communities::0'} eq '') ||
10470:                         (!grep(/^placement$/,@{$cats[0]})) ||
10471:                         ($cathash->{'placement::0'} eq '')) {
10472:                         $maxnum ++;
10473:                     }
10474:                     my $lastidx;
10475:                     for (my $i=0; $i<$numtop; $i++) {
10476:                         my $parent = $cats[0][$i];
10477:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10478:                         my $item = &escape($parent).'::0';
10479:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
10480:                         $lastidx = $idx{$item};
10481:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10482:                                       .'<select name="'.$item.'"'.$chgstr.'>';
10483:                         for (my $k=0; $k<=$maxnum; $k++) {
10484:                             my $vpos = $k+1;
10485:                             my $selstr;
10486:                             if ($k == $i) {
10487:                                 $selstr = ' selected="selected" ';
10488:                             }
10489:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10490:                         }
10491:                         $datatable .= '</select></span></td><td>';
10492:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
10493:                             $datatable .=  '<span class="LC_nobreak">'
10494:                                            .$default_names{$parent}.'</span>';
10495:                             if ($parent eq 'instcode') {
10496:                                 $datatable .= '<br /><span class="LC_nobreak">('
10497:                                               .&mt('with institutional codes')
10498:                                               .')</span></td><td'.$colattrib.'>';
10499:                             } else {
10500:                                 $datatable .= '<table><tr><td>';
10501:                             }
10502:                             $datatable .= '<span class="LC_nobreak">'
10503:                                           .'<label><input type="radio" name="'
10504:                                           .$parent.'" value="1" checked="checked" />'
10505:                                           .&mt('Display').'</label>';
10506:                             if ($parent eq 'instcode') {
10507:                                 $datatable .= '&nbsp;';
10508:                             } else {
10509:                                 $datatable .= '</span></td></tr><tr><td>'
10510:                                               .'<span class="LC_nobreak">';
10511:                             }
10512:                             $datatable .= '<label><input type="radio" name="'
10513:                                           .$parent.'" value="0" />'
10514:                                           .&mt('Do not display').'</label></span>';
10515:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
10516:                                 $datatable .= '</td></tr></table>';
10517:                             }
10518:                             $datatable .= '</td>';
10519:                         } else {
10520:                             $datatable .= $parent
10521:                                           .'&nbsp;<span class="LC_nobreak"><label>'
10522:                                           .'<input type="checkbox" name="deletecategory" '
10523:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
10524:                         }
10525:                         my $depth = 1;
10526:                         push(@path,$parent);
10527:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
10528:                         pop(@path);
10529:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10530:                         $itemcount ++;
10531:                     }
10532:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10533:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
10534:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
10535:                     for (my $k=0; $k<=$maxnum; $k++) {
10536:                         my $vpos = $k+1;
10537:                         my $selstr;
10538:                         if ($k == $numtop) {
10539:                             $selstr = ' selected="selected" ';
10540:                         }
10541:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10542:                     }
10543:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
10544:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
10545:                                   .'</tr>'."\n";
10546:                     $itemcount ++;
10547:                     foreach my $default ('instcode','communities','placement') {
10548:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
10549:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
10550:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
10551:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
10552:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
10553:                             for (my $k=0; $k<=$maxnum; $k++) {
10554:                                 my $vpos = $k+1;
10555:                                 my $selstr;
10556:                                 if ($k == $maxnum) {
10557:                                     $selstr = ' selected="selected" ';
10558:                                 }
10559:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10560:                             }
10561:                             $datatable .= '</select></span></td>'.
10562:                                           '<td><span class="LC_nobreak">'.
10563:                                           $default_names{$default}.'</span>';
10564:                             if ($default eq 'instcode') {
10565:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
10566:                                               .&mt('with institutional codes').')</span>';
10567:                             }
10568:                             $datatable .= '</td>'
10569:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
10570:                                           .&mt('Display').'</label>&nbsp;'
10571:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
10572:                                           .&mt('Do not display').'</label></span></td></tr>';
10573:                         }
10574:                     }
10575:                 }
10576:             } else {
10577:                 $datatable .= &initialize_categories($itemcount);
10578:             }
10579:         } else {
10580:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
10581:                           .&initialize_categories($itemcount);
10582:         }
10583:         $$rowtotal += $itemcount;
10584:     }
10585:     return $datatable;
10586: }
10587: 
10588: sub print_serverstatuses {
10589:     my ($dom,$settings,$rowtotal) = @_;
10590:     my $datatable;
10591:     my @pages = &serverstatus_pages();
10592:     my (%namedaccess,%machineaccess);
10593:     foreach my $type (@pages) {
10594:         $namedaccess{$type} = '';
10595:         $machineaccess{$type}= '';
10596:     }
10597:     if (ref($settings) eq 'HASH') {
10598:         foreach my $type (@pages) {
10599:             if (exists($settings->{$type})) {
10600:                 if (ref($settings->{$type}) eq 'HASH') {
10601:                     foreach my $key (keys(%{$settings->{$type}})) {
10602:                         if ($key eq 'namedusers') {
10603:                             $namedaccess{$type} = $settings->{$type}->{$key};
10604:                         } elsif ($key eq 'machines') {
10605:                             $machineaccess{$type} = $settings->{$type}->{$key};
10606:                         }
10607:                     }
10608:                 }
10609:             }
10610:         }
10611:     }
10612:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
10613:     my $rownum = 0;
10614:     my $css_class;
10615:     foreach my $type (@pages) {
10616:         $rownum ++;
10617:         $css_class = $rownum%2?' class="LC_odd_row"':'';
10618:         $datatable .= '<tr'.$css_class.'>'.
10619:                       '<td><span class="LC_nobreak">'.
10620:                       $titles->{$type}.'</span></td>'.
10621:                       '<td class="LC_left_item">'.
10622:                       '<input type="text" name="'.$type.'_namedusers" '.
10623:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
10624:                       '<td class="LC_right_item">'.
10625:                       '<span class="LC_nobreak">'.
10626:                       '<input type="text" name="'.$type.'_machines" '.
10627:                       'value="'.$machineaccess{$type}.'" size="10" />'.
10628:                       '</span></td></tr>'."\n";
10629:     }
10630:     $$rowtotal += $rownum;
10631:     return $datatable;
10632: }
10633: 
10634: sub serverstatus_pages {
10635:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
10636:             'checksums','clusterstatus','certstatus','metadata_keywords',
10637:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
10638:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
10639: }
10640: 
10641: sub defaults_javascript {
10642:     my ($settings) = @_;
10643:     return unless (ref($settings) eq 'HASH');
10644:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10645:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
10646:         if ($maxnum eq '') {
10647:             $maxnum = 0;
10648:         }
10649:         $maxnum ++;
10650:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
10651:         return <<"ENDSCRIPT";
10652: <script type="text/javascript">
10653: // <![CDATA[
10654: function reorderTypes(form,caller) {
10655:     var changedVal;
10656: $jstext 
10657:     var newpos = 'addinststatus_pos';
10658:     var current = new Array;
10659:     var maxh = $maxnum;
10660:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10661:     var oldVal;
10662:     if (caller == newpos) {
10663:         changedVal = newitemVal;
10664:     } else {
10665:         var curritem = 'inststatus_pos_'+caller;
10666:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
10667:         current[newitemVal] = newpos;
10668:     }
10669:     for (var i=0; i<inststatuses.length; i++) {
10670:         if (inststatuses[i] != caller) {
10671:             var elementName = 'inststatus_pos_'+inststatuses[i];
10672:             if (form.elements[elementName]) {
10673:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10674:                 current[currVal] = elementName;
10675:             }
10676:         }
10677:     }
10678:     for (var j=0; j<maxh; j++) {
10679:         if (current[j] == undefined) {
10680:             oldVal = j;
10681:         }
10682:     }
10683:     if (oldVal < changedVal) {
10684:         for (var k=oldVal+1; k<=changedVal ; k++) {
10685:            var elementName = current[k];
10686:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10687:         }
10688:     } else {
10689:         for (var k=changedVal; k<oldVal; k++) {
10690:             var elementName = current[k];
10691:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10692:         }
10693:     }
10694:     return;
10695: }
10696: 
10697: // ]]>
10698: </script>
10699: 
10700: ENDSCRIPT
10701:     }
10702:     return;
10703: }
10704: 
10705: sub passwords_javascript {
10706:     my %intalert = &Apache::lonlocal::texthash (
10707:         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.',
10708:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
10709:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
10710:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
10711:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
10712:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
10713:     );
10714:     &js_escape(\%intalert);
10715:     my $defmin = $Apache::lonnet::passwdmin;
10716:     my $intauthjs = <<"ENDSCRIPT";
10717: 
10718: function warnIntAuth(field) {
10719:     if (field.name == 'intauth_check') {
10720:         if (field.value == '2') {
10721:             alert('$intalert{authcheck}');
10722:         }
10723:     }
10724:     if (field.name == 'intauth_cost') {
10725:         field.value.replace(/\s/g,'');
10726:         if (field.value != '') {
10727:             var regexdigit=/^\\d+\$/;
10728:             if (!regexdigit.test(field.value)) {
10729:                 alert('$intalert{authcost}');
10730:             }
10731:         }
10732:     }
10733:     return;
10734: }
10735: 
10736: function warnIntPass(field) {
10737:     field.value.replace(/^\s+/,'');
10738:     field.value.replace(/\s+\$/,'');
10739:     var regexdigit=/^\\d+\$/;
10740:     if (field.name == 'passwords_min') {
10741:         if (field.value == '') {
10742:             alert('$intalert{passmin}');
10743:             field.value = '$defmin';
10744:         } else {
10745:             if (!regexdigit.test(field.value)) {
10746:                 alert('$intalert{passmin}');
10747:                 field.value = '$defmin';
10748:             }
10749:             var minval = parseInt(field.value,10);
10750:             if (minval < $defmin) {
10751:                 alert('$intalert{passmin}');
10752:                 field.value = '$defmin';
10753:             }
10754:         }
10755:     } else {
10756:         if (field.value == '0') {
10757:             field.value = '';
10758:         }
10759:         if (field.value != '') {
10760:             if (field.name == 'passwords_expire') {
10761:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
10762:                 if (!regexpposnum.test(field.value)) {
10763:                     alert('$intalert{passexp}');
10764:                     field.value = '';
10765:                 } else {
10766:                     var expval = parseFloat(field.value);
10767:                     if (expval == 0) {
10768:                         alert('$intalert{passexp}');
10769:                         field.value = '';
10770:                     }
10771:                 }
10772:             } else {
10773:                 if (!regexdigit.test(field.value)) {
10774:                     if (field.name == 'passwords_max') {
10775:                         alert('$intalert{passmax}');
10776:                     } else {
10777:                         if (field.name == 'passwords_numsaved') {
10778:                             alert('$intalert{passnum}');
10779:                         }
10780:                     }
10781:                     field.value = '';
10782:                 }
10783:             }
10784:         }
10785:     }
10786:     return;
10787: }
10788: 
10789: ENDSCRIPT
10790:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
10791: }
10792: 
10793: sub coursecategories_javascript {
10794:     my ($settings) = @_;
10795:     my ($output,$jstext,$cathash);
10796:     if (ref($settings) eq 'HASH') {
10797:         $cathash = $settings->{'cats'};
10798:     }
10799:     if (ref($cathash) eq 'HASH') {
10800:         my (@cats,@jsarray,%idx);
10801:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
10802:         if (@jsarray > 0) {
10803:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
10804:             for (my $i=0; $i<@jsarray; $i++) {
10805:                 if (ref($jsarray[$i]) eq 'ARRAY') {
10806:                     my $catstr = join('","',@{$jsarray[$i]});
10807:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
10808:                 }
10809:             }
10810:         }
10811:     } else {
10812:         $jstext  = '    var categories = Array(1);'."\n".
10813:                    '    categories[0] = Array("instcode_pos");'."\n"; 
10814:     }
10815:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
10816:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
10817:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
10818:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
10819:     &js_escape(\$instcode_reserved);
10820:     &js_escape(\$communities_reserved);
10821:     &js_escape(\$placement_reserved);
10822:     &js_escape(\$choose_again);
10823:     $output = <<"ENDSCRIPT";
10824: <script type="text/javascript">
10825: // <![CDATA[
10826: function reorderCats(form,parent,item,idx) {
10827:     var changedVal;
10828: $jstext
10829:     var newpos = 'addcategory_pos';
10830:     if (parent == '') {
10831:         var has_instcode = 0;
10832:         var maxtop = categories[idx].length;
10833:         for (var j=0; j<maxtop; j++) {
10834:             if (categories[idx][j] == 'instcode::0') {
10835:                 has_instcode == 1;
10836:             }
10837:         }
10838:         if (has_instcode == 0) {
10839:             categories[idx][maxtop] = 'instcode_pos';
10840:         }
10841:     } else {
10842:         newpos += '_'+parent;
10843:     }
10844:     var maxh = 1 + categories[idx].length;
10845:     var current = new Array;
10846:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10847:     if (item == newpos) {
10848:         changedVal = newitemVal;
10849:     } else {
10850:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
10851:         current[newitemVal] = newpos;
10852:     }
10853:     for (var i=0; i<categories[idx].length; i++) {
10854:         var elementName = categories[idx][i];
10855:         if (elementName != item) {
10856:             if (form.elements[elementName]) {
10857:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10858:                 current[currVal] = elementName;
10859:             }
10860:         }
10861:     }
10862:     var oldVal;
10863:     for (var j=0; j<maxh; j++) {
10864:         if (current[j] == undefined) {
10865:             oldVal = j;
10866:         }
10867:     }
10868:     if (oldVal < changedVal) {
10869:         for (var k=oldVal+1; k<=changedVal ; k++) {
10870:            var elementName = current[k];
10871:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10872:         }
10873:     } else {
10874:         for (var k=changedVal; k<oldVal; k++) {
10875:             var elementName = current[k];
10876:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10877:         }
10878:     }
10879:     return;
10880: }
10881: 
10882: function categoryCheck(form) {
10883:     if (form.elements['addcategory_name'].value == 'instcode') {
10884:         alert('$instcode_reserved\\n$choose_again');
10885:         return false;
10886:     }
10887:     if (form.elements['addcategory_name'].value == 'communities') {
10888:         alert('$communities_reserved\\n$choose_again');
10889:         return false;
10890:     }
10891:     if (form.elements['addcategory_name'].value == 'placement') {
10892:         alert('$placement_reserved\\n$choose_again');
10893:         return false;
10894:     }
10895:     return true;
10896: }
10897: 
10898: // ]]>
10899: </script>
10900: 
10901: ENDSCRIPT
10902:     return $output;
10903: }
10904: 
10905: sub initialize_categories {
10906:     my ($itemcount) = @_;
10907:     my ($datatable,$css_class,$chgstr);
10908:     my %default_names = &Apache::lonlocal::texthash (
10909:                       instcode    => 'Official courses (with institutional codes)',
10910:                       communities => 'Communities',
10911:                       placement   => 'Placement Tests',
10912:                         );
10913:     my %selnum = (
10914:                    instcode    => '0',
10915:                    communities => '1',
10916:                    placement   => '2',
10917:                  );
10918:     my %selected;
10919:     foreach my $default ('instcode','communities','placement') {
10920:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10921:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
10922:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
10923:         $selected{$selnum{$default}} = ' selected="selected"';
10924:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10925:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
10926:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
10927:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
10928:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
10929:                      .'<option value="3">4</option></select>&nbsp;'
10930:                      .$default_names{$default}
10931:                      .'</span></td><td><span class="LC_nobreak">'
10932:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
10933:                      .&mt('Display').'</label>&nbsp;<label>'
10934:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
10935:                  .'</label></span></td></tr>';
10936:         $itemcount ++;
10937:     }
10938:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10939:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
10940:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10941:                   .'<select name="addcategory_pos"'.$chgstr.'>'
10942:                   .'<option value="0">1</option>'
10943:                   .'<option value="1">2</option>'
10944:                   .'<option value="2">3</option>'
10945:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
10946:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
10947:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
10948:                   .'</td></tr>';
10949:     return $datatable;
10950: }
10951: 
10952: sub build_category_rows {
10953:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
10954:     my ($text,$name,$item,$chgstr);
10955:     if (ref($cats) eq 'ARRAY') {
10956:         my $maxdepth = scalar(@{$cats});
10957:         if (ref($cats->[$depth]) eq 'HASH') {
10958:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10959:                 my $numchildren = @{$cats->[$depth]{$parent}};
10960:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10961:                 $text .= '<td><table class="LC_data_table">';
10962:                 my ($idxnum,$parent_name,$parent_item);
10963:                 my $higher = $depth - 1;
10964:                 if ($higher == 0) {
10965:                     $parent_name = &escape($parent).'::'.$higher;
10966:                 } else {
10967:                     if (ref($path) eq 'ARRAY') {
10968:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
10969:                     }
10970:                 }
10971:                 $parent_item = 'addcategory_pos_'.$parent_name;
10972:                 for (my $j=0; $j<=$numchildren; $j++) {
10973:                     if ($j < $numchildren) {
10974:                         $name = $cats->[$depth]{$parent}[$j];
10975:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
10976:                         $idxnum = $idx->{$item};
10977:                     } else {
10978:                         $name = $parent_name;
10979:                         $item = $parent_item;
10980:                     }
10981:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
10982:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
10983:                     for (my $i=0; $i<=$numchildren; $i++) {
10984:                         my $vpos = $i+1;
10985:                         my $selstr;
10986:                         if ($j == $i) {
10987:                             $selstr = ' selected="selected" ';
10988:                         }
10989:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
10990:                     }
10991:                     $text .= '</select>&nbsp;';
10992:                     if ($j < $numchildren) {
10993:                         my $deeper = $depth+1;
10994:                         $text .= $name.'&nbsp;'
10995:                                  .'<label><input type="checkbox" name="deletecategory" value="'
10996:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
10997:                         if(ref($path) eq 'ARRAY') {
10998:                             push(@{$path},$name);
10999:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
11000:                             pop(@{$path});
11001:                         }
11002:                     } else {
11003:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
11004:                         if ($j == $numchildren) {
11005:                             $text .= $name;
11006:                         } else {
11007:                             $text .= $item;
11008:                         }
11009:                         $text .= '" value="" />';
11010:                     }
11011:                     $text .= '</td></tr>';
11012:                 }
11013:                 $text .= '</table></td>';
11014:             } else {
11015:                 my $higher = $depth-1;
11016:                 if ($higher == 0) {
11017:                     $name = &escape($parent).'::'.$higher;
11018:                 } else {
11019:                     if (ref($path) eq 'ARRAY') {
11020:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11021:                     }
11022:                 }
11023:                 my $colspan;
11024:                 if ($parent ne 'instcode') {
11025:                     $colspan = $maxdepth - $depth - 1;
11026:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
11027:                 }
11028:             }
11029:         }
11030:     }
11031:     return $text;
11032: }
11033: 
11034: sub modifiable_userdata_row {
11035:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
11036:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
11037:     my ($role,$rolename,$statustype);
11038:     $role = $item;
11039:     if ($context eq 'cancreate') {
11040:         if ($item =~ /^(emailusername)_(.+)$/) {
11041:             $role = $1;
11042:             $statustype = $2;
11043:             if (ref($usertypes) eq 'HASH') {
11044:                 if ($usertypes->{$statustype}) {
11045:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
11046:                 } else {
11047:                     $rolename = &mt('Data provided by user');
11048:                 }
11049:             }
11050:         }
11051:     } elsif ($context eq 'selfcreate') {
11052:         if (ref($usertypes) eq 'HASH') {
11053:             $rolename = $usertypes->{$role};
11054:         } else {
11055:             $rolename = $role;
11056:         }
11057:     } elsif ($context eq 'lti') {
11058:         $rolename = &mt('Institutional data used (if available)');
11059:     } elsif ($context eq 'privacy') {
11060:         $rolename = $itemdesc;
11061:     } else {
11062:         if ($role eq 'cr') {
11063:             $rolename = &mt('Custom role');
11064:         } else {
11065:             $rolename = &Apache::lonnet::plaintext($role);
11066:         }
11067:     }
11068:     my (@fields,%fieldtitles);
11069:     if (ref($fieldsref) eq 'ARRAY') {
11070:         @fields = @{$fieldsref};
11071:     } else {
11072:         @fields = ('lastname','firstname','middlename','generation',
11073:                    'permanentemail','id');
11074:     }
11075:     if ((ref($titlesref) eq 'HASH')) {
11076:         %fieldtitles = %{$titlesref};
11077:     } else {
11078:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11079:     }
11080:     my $output;
11081:     my $css_class;
11082:     if ($rowcount%2) {
11083:         $css_class = 'LC_odd_row';
11084:     }
11085:     if ($customcss) {
11086:         $css_class .= " $customcss";
11087:     }
11088:     $css_class =~ s/^\s+//;
11089:     if ($css_class) {
11090:         $css_class = ' class="'.$css_class.'"';
11091:     }
11092:     if ($rowstyle) {
11093:         $css_class .= ' style="'.$rowstyle.'"';
11094:     }
11095:     if ($rowid) {
11096:         $rowid = ' id="'.$rowid.'"';
11097:     }
11098:     $output = '<tr '.$css_class.$rowid.'>'.
11099:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
11100:               '<td class="LC_left_item" colspan="2"><table>';
11101:     my $rem;
11102:     my %checks;
11103:     my %current;
11104:     if (ref($settings) eq 'HASH') {
11105:         my $hashref;
11106:         if ($context eq 'lti') {
11107:             if (ref($settings) eq 'HASH') {
11108:                 $hashref = $settings->{'instdata'};
11109:             }
11110:         } elsif ($context eq 'privacy') {
11111:             my ($key,$inner) = split(/_/,$role);
11112:             if (ref($settings) eq 'HASH') {
11113:                 if (ref($settings->{$key}) eq 'HASH') {
11114:                     $hashref = $settings->{$key}->{$inner};
11115:                 }
11116:             }
11117:         } elsif (ref($settings->{$context}) eq 'HASH') {
11118:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
11119:                 $hashref = $settings->{'lti_instdata'};
11120:             }
11121:             if ($role eq 'emailusername') {
11122:                 if ($statustype) {
11123:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
11124:                         $hashref = $settings->{$context}->{$role}->{$statustype};
11125:                     }
11126:                 }
11127:             }
11128:         }
11129:         if (ref($hashref) eq 'HASH') { 
11130:             foreach my $field (@fields) {
11131:                 if ($hashref->{$field}) {
11132:                     if ($role eq 'emailusername') {
11133:                         $checks{$field} = $hashref->{$field};
11134:                     } else {
11135:                         $checks{$field} = ' checked="checked" ';
11136:                     }
11137:                 }
11138:             }
11139:         }
11140:     }
11141:  
11142:     my $total = scalar(@fields);
11143:     for (my $i=0; $i<$total; $i++) {
11144:         $rem = $i%($numinrow);
11145:         if ($rem == 0) {
11146:             if ($i > 0) {
11147:                 $output .= '</tr>';
11148:             }
11149:             $output .= '<tr>';
11150:         }
11151:         my $check = ' ';
11152:         unless ($role eq 'emailusername') {
11153:             if (exists($checks{$fields[$i]})) {
11154:                 $check = $checks{$fields[$i]};
11155:             } elsif ($context eq 'privacy') {
11156:                 if ($role =~ /^priv_(domain|course)$/) {
11157:                     if (ref($settings) ne 'HASH') {
11158:                         $check = ' checked="checked" ';
11159:                     }
11160:                 } elsif ($role =~ /^priv_(author|community)$/) {
11161:                     if (ref($settings) ne 'HASH') {
11162:                         unless ($fields[$i] eq 'id') {
11163:                             $check = ' checked="checked" ';
11164:                         }
11165:                     }
11166:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
11167:                     if (ref($settings) ne 'HASH') {
11168:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
11169:                             $check = ' checked="checked" ';
11170:                         }
11171:                     }
11172:                 }
11173:             } elsif ($context ne 'lti') {
11174:                 if ($role eq 'st') {
11175:                     if (ref($settings) ne 'HASH') {
11176:                         $check = ' checked="checked" '; 
11177:                     }
11178:                 }
11179:             }
11180:         }
11181:         $output .= '<td class="LC_left_item">'.
11182:                    '<span class="LC_nobreak">';
11183:         my $prefix = 'canmodify';
11184:         if ($role eq 'emailusername') {
11185:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
11186:                 $checks{$fields[$i]} = 'omit';
11187:             }
11188:             foreach my $option ('required','optional','omit') {
11189:                 my $checked='';
11190:                 if ($checks{$fields[$i]} eq $option) {
11191:                     $checked='checked="checked" ';
11192:                 }
11193:                 $output .= '<label>'.
11194:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
11195:                            &mt($option).'</label>'.('&nbsp;' x2);
11196:             }
11197:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
11198:         } else {
11199:             if ($context eq 'lti') {
11200:                 $prefix = 'lti';
11201:             } elsif ($context eq 'privacy') {
11202:                 $prefix = 'privacy';
11203:             }
11204:             $output .= '<label>'.
11205:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
11206:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
11207:                        '</label>';
11208:         }
11209:         $output .= '</span></td>';
11210:     }
11211:     $rem = $total%$numinrow;
11212:     my $colsleft;
11213:     if ($rem) {
11214:         $colsleft = $numinrow - $rem;
11215:     }
11216:     if ($colsleft > 1) {
11217:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
11218:                    '&nbsp;</td>';
11219:     } elsif ($colsleft == 1) {
11220:         $output .= '<td class="LC_left_item">&nbsp;</td>';
11221:     }
11222:     $output .= '</tr></table></td></tr>';
11223:     return $output;
11224: }
11225: 
11226: sub insttypes_row {
11227:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
11228:         $customcss,$rowstyle) = @_;
11229:     my %lt = &Apache::lonlocal::texthash (
11230:                       cansearch => 'Users allowed to search',
11231:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
11232:                       lockablenames => 'User preference to lock name',
11233:                       selfassign    => 'Self-reportable affiliations',
11234:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
11235:              );
11236:     my $showdom;
11237:     if ($context eq 'cansearch') {
11238:         $showdom = ' ('.$dom.')';
11239:     }
11240:     my $class = 'LC_left_item';
11241:     if ($context eq 'statustocreate') {
11242:         $class = 'LC_right_item';
11243:     }
11244:     my $css_class;
11245:     if ($$rowtotal%2) {
11246:         $css_class = 'LC_odd_row';
11247:     }
11248:     if ($customcss) {
11249:         $css_class .= ' '.$customcss;
11250:     }
11251:     $css_class =~ s/^\s+//;
11252:     if ($css_class) {
11253:         $css_class = ' class="'.$css_class.'"';
11254:     }
11255:     if ($rowstyle) {
11256:         $css_class .= ' style="'.$rowstyle.'"';
11257:     }
11258:     if ($onclick) {
11259:         $onclick = 'onclick="'.$onclick.'" ';
11260:     }
11261:     my $output = '<tr'.$css_class.'>'.
11262:                  '<td>'.$lt{$context}.$showdom.
11263:                  '</td><td class="'.$class.'" colspan="2"><table>';
11264:     my $rem;
11265:     if (ref($types) eq 'ARRAY') {
11266:         for (my $i=0; $i<@{$types}; $i++) {
11267:             if (defined($usertypes->{$types->[$i]})) {
11268:                 my $rem = $i%($numinrow);
11269:                 if ($rem == 0) {
11270:                     if ($i > 0) {
11271:                         $output .= '</tr>';
11272:                     }
11273:                     $output .= '<tr>';
11274:                 }
11275:                 my $check = ' ';
11276:                 if (ref($settings) eq 'HASH') {
11277:                     if (ref($settings->{$context}) eq 'ARRAY') {
11278:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
11279:                             $check = ' checked="checked" ';
11280:                         }
11281:                     } elsif (ref($settings->{$context}) eq 'HASH') {
11282:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
11283:                             $check = ' checked="checked" ';
11284:                         }
11285:                     } elsif ($context eq 'statustocreate') {
11286:                         $check = ' checked="checked" ';
11287:                     }
11288:                 }
11289:                 $output .= '<td class="LC_left_item">'.
11290:                            '<span class="LC_nobreak"><label>'.
11291:                            '<input type="checkbox" name="'.$context.'" '.
11292:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
11293:                            $usertypes->{$types->[$i]}.'</label></span></td>';
11294:             }
11295:         }
11296:         $rem = @{$types}%($numinrow);
11297:     }
11298:     my $colsleft = $numinrow - $rem;
11299:     if ($context eq 'overrides') {
11300:         if ($colsleft > 1) {
11301:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11302:         } else {
11303:             $output .= '<td class="LC_left_item">';
11304:         }
11305:         $output .= '&nbsp;';  
11306:     } else {
11307:         if ($rem == 0) {
11308:             $output .= '<tr>';
11309:         }
11310:         if ($colsleft > 1) {
11311:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11312:         } else {
11313:             $output .= '<td class="LC_left_item">';
11314:         }
11315:         my $defcheck = ' ';
11316:         if (ref($settings) eq 'HASH') {  
11317:             if (ref($settings->{$context}) eq 'ARRAY') {
11318:                 if (grep(/^default$/,@{$settings->{$context}})) {
11319:                     $defcheck = ' checked="checked" ';
11320:                 }
11321:             } elsif ($context eq 'statustocreate') {
11322:                 $defcheck = ' checked="checked" ';
11323:             }
11324:         }
11325:         $output .= '<span class="LC_nobreak"><label>'.
11326:                    '<input type="checkbox" name="'.$context.'" '.
11327:                    'value="default"'.$defcheck.$onclick.' />'.
11328:                    $othertitle.'</label></span>';
11329:     }
11330:     $output .= '</td></tr></table></td></tr>';
11331:     return $output;
11332: }
11333: 
11334: sub sorted_searchtitles {
11335:     my %searchtitles = &Apache::lonlocal::texthash(
11336:                          'uname' => 'username',
11337:                          'lastname' => 'last name',
11338:                          'lastfirst' => 'last name, first name',
11339:                      );
11340:     my @titleorder = ('uname','lastname','lastfirst');
11341:     return (\%searchtitles,\@titleorder);
11342: }
11343: 
11344: sub sorted_searchtypes {
11345:     my %srchtypes_desc = (
11346:                            exact    => 'is exact match',
11347:                            contains => 'contains ..',
11348:                            begins   => 'begins with ..',
11349:                          );
11350:     my @srchtypeorder = ('exact','begins','contains');
11351:     return (\%srchtypes_desc,\@srchtypeorder);
11352: }
11353: 
11354: sub usertype_update_row {
11355:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
11356:     my $datatable;
11357:     my $numinrow = 4;
11358:     foreach my $type (@{$types}) {
11359:         if (defined($usertypes->{$type})) {
11360:             $$rownums ++;
11361:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
11362:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
11363:                           '</td><td class="LC_left_item"><table>';
11364:             for (my $i=0; $i<@{$fields}; $i++) {
11365:                 my $rem = $i%($numinrow);
11366:                 if ($rem == 0) {
11367:                     if ($i > 0) {
11368:                         $datatable .= '</tr>';
11369:                     }
11370:                     $datatable .= '<tr>';
11371:                 }
11372:                 my $check = ' ';
11373:                 if (ref($settings) eq 'HASH') {
11374:                     if (ref($settings->{'fields'}) eq 'HASH') {
11375:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
11376:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
11377:                                 $check = ' checked="checked" ';
11378:                             }
11379:                         }
11380:                     }
11381:                 }
11382: 
11383:                 if ($i == @{$fields}-1) {
11384:                     my $colsleft = $numinrow - $rem;
11385:                     if ($colsleft > 1) {
11386:                         $datatable .= '<td colspan="'.$colsleft.'">';
11387:                     } else {
11388:                         $datatable .= '<td>';
11389:                     }
11390:                 } else {
11391:                     $datatable .= '<td>';
11392:                 }
11393:                 $datatable .= '<span class="LC_nobreak"><label>'.
11394:                               '<input type="checkbox" name="updateable_'.$type.
11395:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
11396:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
11397:             }
11398:             $datatable .= '</tr></table></td></tr>';
11399:         }
11400:     }
11401:     return $datatable;
11402: }
11403: 
11404: sub modify_login {
11405:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
11406:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
11407:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
11408:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
11409:     %title = ( coursecatalog => 'Display course catalog',
11410:                adminmail => 'Display administrator E-mail address',
11411:                helpdesk  => 'Display "Contact Helpdesk" link',
11412:                newuser => 'Link for visitors to create a user account',
11413:                loginheader => 'Log-in box header',
11414:                saml => 'Dual SSO and non-SSO login');
11415:     @offon = ('off','on');
11416:     if (ref($domconfig{login}) eq 'HASH') {
11417:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
11418:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
11419:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
11420:             }
11421:         }
11422:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
11423:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
11424:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
11425:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
11426:                     $saml{$lonhost} = 1;
11427:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
11428:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
11429:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
11430:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
11431:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
11432:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
11433:                 }
11434:             }
11435:         }
11436:     }
11437:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
11438:                                            \%domconfig,\%loginhash);
11439:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11440:     foreach my $item (@toggles) {
11441:         $loginhash{login}{$item} = $env{'form.'.$item};
11442:     }
11443:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
11444:     if (ref($colchanges{'login'}) eq 'HASH') {  
11445:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
11446:                                          \%loginhash);
11447:     }
11448: 
11449:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
11450:     my %domservers = &Apache::lonnet::get_servers($dom);
11451:     my @loginvia_attribs = ('serverpath','custompath','exempt');
11452:     if (keys(%servers) > 1) {
11453:         foreach my $lonhost (keys(%servers)) {
11454:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
11455:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
11456:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
11457:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
11458:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
11459:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11460:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11461:                         $changes{'loginvia'}{$lonhost} = 1;
11462:                     } else {
11463:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
11464:                         $changes{'loginvia'}{$lonhost} = 1;
11465:                     }
11466:                 } else {
11467:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11468:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11469:                         $changes{'loginvia'}{$lonhost} = 1;
11470:                     }
11471:                 }
11472:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
11473:                     foreach my $item (@loginvia_attribs) {
11474:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
11475:                     }
11476:                 } else {
11477:                     foreach my $item (@loginvia_attribs) {
11478:                         my $new = $env{'form.'.$lonhost.'_'.$item};
11479:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
11480:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
11481:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
11482:                                 $new = '/';
11483:                             }
11484:                         }
11485:                         if (($item eq 'custompath') && 
11486:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
11487:                             $new = '';
11488:                         }
11489:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
11490:                             $changes{'loginvia'}{$lonhost} = 1;
11491:                         }
11492:                         if ($item eq 'exempt') {
11493:                             $new = &check_exempt_addresses($new);
11494:                         }
11495:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
11496:                     }
11497:                 }
11498:             } else {
11499:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11500:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11501:                     $changes{'loginvia'}{$lonhost} = 1;
11502:                     foreach my $item (@loginvia_attribs) {
11503:                         my $new = $env{'form.'.$lonhost.'_'.$item};
11504:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
11505:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
11506:                                 $new = '/';
11507:                             }
11508:                         }
11509:                         if (($item eq 'custompath') && 
11510:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
11511:                             $new = '';
11512:                         }
11513:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
11514:                     }
11515:                 }
11516:             }
11517:         }
11518:     }
11519: 
11520:     my $servadm = $r->dir_config('lonAdmEMail');
11521:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
11522:     if (ref($domconfig{'login'}) eq 'HASH') {
11523:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
11524:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
11525:                 if ($lang eq 'nolang') {
11526:                     push(@currlangs,$lang);
11527:                 } elsif (defined($langchoices{$lang})) {
11528:                     push(@currlangs,$lang);
11529:                 } else {
11530:                     next;
11531:                 }
11532:             }
11533:         }
11534:     }
11535:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
11536:     if (@currlangs > 0) {
11537:         foreach my $lang (@currlangs) {
11538:             if (grep(/^\Q$lang\E$/,@delurls)) {
11539:                 $changes{'helpurl'}{$lang} = 1;
11540:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
11541:                 $changes{'helpurl'}{$lang} = 1;
11542:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
11543:                 push(@newlangs,$lang);
11544:             } else {
11545:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
11546:             }
11547:         }
11548:     }
11549:     unless (grep(/^nolang$/,@currlangs)) {
11550:         if ($env{'form.loginhelpurl_nolang.filename'}) {
11551:             $changes{'helpurl'}{'nolang'} = 1;
11552:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
11553:             push(@newlangs,'nolang');
11554:         }
11555:     }
11556:     if ($env{'form.loginhelpurl_add_lang'}) {
11557:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
11558:             ($env{'form.loginhelpurl_add_file.filename'})) {
11559:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
11560:             $addedfile = $env{'form.loginhelpurl_add_lang'};
11561:         }
11562:     }
11563:     if ((@newlangs > 0) || ($addedfile)) {
11564:         my $error;
11565:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11566:         if ($configuserok eq 'ok') {
11567:             if ($switchserver) {
11568:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
11569:             } elsif ($author_ok eq 'ok') {
11570:                 my @allnew = @newlangs;
11571:                 if ($addedfile ne '') {
11572:                     push(@allnew,$addedfile);
11573:                 }
11574:                 foreach my $lang (@allnew) {
11575:                     my $formelem = 'loginhelpurl_'.$lang;
11576:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
11577:                         $formelem = 'loginhelpurl_add_file';
11578:                     }
11579:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11580:                                                                "help/$lang",'','',$newfile{$lang});
11581:                     if ($result eq 'ok') {
11582:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
11583:                         $changes{'helpurl'}{$lang} = 1;
11584:                     } else {
11585:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
11586:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11587:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
11588:                             (!grep(/^\Q$lang\E$/,@delurls))) {
11589:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
11590:                         }
11591:                     }
11592:                 }
11593:             } else {
11594:                 $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);
11595:             }
11596:         } else {
11597:             $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);
11598:         }
11599:         if ($error) {
11600:             &Apache::lonnet::logthis($error);
11601:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11602:         }
11603:     }
11604: 
11605:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
11606:     if (ref($domconfig{'login'}) eq 'HASH') {
11607:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
11608:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
11609:                 if ($domservers{$lonhost}) {
11610:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11611:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
11612:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
11613:                     }
11614:                 }
11615:             }
11616:         }
11617:     }
11618:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
11619:     foreach my $lonhost (sort(keys(%domservers))) {
11620:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11621:             $changes{'headtag'}{$lonhost} = 1;
11622:         } else {
11623:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
11624:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
11625:             }
11626:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
11627:                 push(@newhosts,$lonhost);
11628:             } elsif ($currheadtagurls{$lonhost}) {
11629:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
11630:                 if ($currexempt{$lonhost}) {
11631:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
11632:                         $changes{'headtag'}{$lonhost} = 1;
11633:                     }
11634:                 } elsif ($possexempt{$lonhost}) {
11635:                     $changes{'headtag'}{$lonhost} = 1;
11636:                 }
11637:                 if ($possexempt{$lonhost}) {
11638:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
11639:                 }
11640:             }
11641:         }
11642:     }
11643:     if (@newhosts) {
11644:         my $error;
11645:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11646:         if ($configuserok eq 'ok') {
11647:             if ($switchserver) {
11648:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
11649:             } elsif ($author_ok eq 'ok') {
11650:                 foreach my $lonhost (@newhosts) {
11651:                     my $formelem = 'loginheadtag_'.$lonhost;
11652:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11653:                                                                           "login/headtag/$lonhost",'','',
11654:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
11655:                     if ($result eq 'ok') {
11656:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
11657:                         $changes{'headtag'}{$lonhost} = 1;
11658:                         if ($possexempt{$lonhost}) {
11659:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
11660:                         }
11661:                     } else {
11662:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
11663:                                            $newheadtagurls{$lonhost},$result);
11664:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11665:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
11666:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
11667:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
11668:                         }
11669:                     }
11670:                 }
11671:             } else {
11672:                 $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);
11673:             }
11674:         } else {
11675:             $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);
11676:         }
11677:         if ($error) {
11678:             &Apache::lonnet::logthis($error);
11679:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11680:         }
11681:     }
11682:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
11683:     my @newsamlimgs;
11684:     foreach my $lonhost (keys(%domservers)) {
11685:         if ($env{'form.saml_'.$lonhost}) {
11686:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
11687:                 push(@newsamlimgs,$lonhost);
11688:             }
11689:             foreach my $item ('text','alt','url','title','notsso') {
11690:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
11691:             }
11692:             if ($saml{$lonhost}) {
11693:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
11694: #FIXME Need to obsolete published image
11695:                     delete($currsaml{$lonhost}{'img'});
11696:                     $changes{'saml'}{$lonhost} = 1;
11697:                 }
11698:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
11699:                     $changes{'saml'}{$lonhost} = 1;
11700:                 }
11701:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
11702:                     $changes{'saml'}{$lonhost} = 1;
11703:                 }
11704:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
11705:                     $changes{'saml'}{$lonhost} = 1;
11706:                 }
11707:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
11708:                     $changes{'saml'}{$lonhost} = 1;
11709:                 }
11710:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
11711:                     $changes{'saml'}{$lonhost} = 1;
11712:                 }
11713:             } else {
11714:                 $changes{'saml'}{$lonhost} = 1;
11715:             }
11716:             foreach my $item ('text','alt','url','title','notsso') {
11717:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
11718:             }
11719:         } else {
11720:             delete($currsaml{$lonhost});
11721:         }
11722:     }
11723:     foreach my $posshost (keys(%currsaml)) {
11724:         unless (exists($domservers{$posshost})) { 
11725:             delete($currsaml{$posshost}); 
11726:         }
11727:     }
11728:     %{$loginhash{'login'}{'saml'}} = %currsaml;
11729:     if (@newsamlimgs) {
11730:         my $error;
11731:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11732:         if ($configuserok eq 'ok') {
11733:             if ($switchserver) {
11734:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
11735:             } elsif ($author_ok eq 'ok') {
11736:                 foreach my $lonhost (@newsamlimgs) {
11737:                     my $formelem = 'saml_img_'.$lonhost;
11738:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11739:                                                         "login/saml/$lonhost",'','',
11740:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
11741:                     if ($result eq 'ok') {
11742:                         $currsaml{$lonhost}{'img'} = $imgurl;
11743:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
11744:                         $changes{'saml'}{$lonhost} = 1;
11745:                     } else {
11746:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
11747:                                            $lonhost,$result);
11748:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11749:                     }
11750:                 }
11751:             } else {
11752:                 $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);
11753:             }
11754:         } else {
11755:             $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);
11756:         }
11757:         if ($error) {
11758:             &Apache::lonnet::logthis($error);
11759:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11760:         }
11761:     }
11762:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
11763: 
11764:     my $defaulthelpfile = '/adm/loginproblems.html';
11765:     my $defaulttext = &mt('Default in use');
11766: 
11767:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
11768:                                              $dom);
11769:     if ($putresult eq 'ok') {
11770:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11771:         my %defaultchecked = (
11772:                     'coursecatalog' => 'on',
11773:                     'helpdesk'      => 'on',
11774:                     'adminmail'     => 'off',
11775:                     'newuser'       => 'off',
11776:         );
11777:         if (ref($domconfig{'login'}) eq 'HASH') {
11778:             foreach my $item (@toggles) {
11779:                 if ($defaultchecked{$item} eq 'on') { 
11780:                     if (($domconfig{'login'}{$item} eq '0') &&
11781:                         ($env{'form.'.$item} eq '1')) {
11782:                         $changes{$item} = 1;
11783:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11784:                               $domconfig{'login'}{$item} eq '1') &&
11785:                              ($env{'form.'.$item} eq '0')) {
11786:                         $changes{$item} = 1;
11787:                     }
11788:                 } elsif ($defaultchecked{$item} eq 'off') {
11789:                     if (($domconfig{'login'}{$item} eq '1') &&
11790:                         ($env{'form.'.$item} eq '0')) {
11791:                         $changes{$item} = 1;
11792:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11793:                               $domconfig{'login'}{$item} eq '0') &&
11794:                              ($env{'form.'.$item} eq '1')) {
11795:                         $changes{$item} = 1;
11796:                     }
11797:                 }
11798:             }
11799:         }
11800:         if (keys(%changes) > 0 || $colchgtext) {
11801:             &Apache::loncommon::devalidate_domconfig_cache($dom);
11802:             if (exists($changes{'saml'})) {
11803:                 my $hostid_in_use;
11804:                 my @hosts = &Apache::lonnet::current_machine_ids();
11805:                 if (@hosts > 1) {
11806:                     foreach my $hostid (@hosts) {
11807:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
11808:                             $hostid_in_use = $hostid;
11809:                             last;
11810:                         }
11811:                     }
11812:                 } else {
11813:                     $hostid_in_use = $r->dir_config('lonHostID');
11814:                 }
11815:                 if (($hostid_in_use) &&
11816:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
11817:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
11818:                 }
11819:                 if (ref($lastactref) eq 'HASH') {
11820:                     if (ref($changes{'saml'}) eq 'HASH') {
11821:                         my %updates;
11822:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
11823:                         $lastactref->{'samllanding'} = \%updates;
11824:                     }
11825:                 }
11826:             }
11827:             if (ref($lastactref) eq 'HASH') {
11828:                 $lastactref->{'domainconfig'} = 1;
11829:             }
11830:             $resulttext = &mt('Changes made:').'<ul>';
11831:             foreach my $item (sort(keys(%changes))) {
11832:                 if ($item eq 'loginvia') {
11833:                     if (ref($changes{$item}) eq 'HASH') {
11834:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
11835:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11836:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
11837:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
11838:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
11839:                                     $protocol = 'http' if ($protocol ne 'https');
11840:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
11841: 
11842:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
11843:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
11844:                                     } else {
11845:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
11846:                                     }
11847:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
11848:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
11849:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
11850:                                     }
11851:                                     $resulttext .= '</li>';
11852:                                 } else {
11853:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
11854:                                 }
11855:                             } else {
11856:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
11857:                             }
11858:                         }
11859:                         $resulttext .= '</ul></li>';
11860:                     }
11861:                 } elsif ($item eq 'helpurl') {
11862:                     if (ref($changes{$item}) eq 'HASH') {
11863:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
11864:                             if (grep(/^\Q$lang\E$/,@delurls)) {
11865:                                 my ($chg,$link);
11866:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
11867:                                 if ($lang eq 'nolang') {
11868:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
11869:                                 } else {
11870:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
11871:                                 }
11872:                                 $resulttext .= '<li>'.$chg.'</li>';
11873:                             } else {
11874:                                 my $chg;
11875:                                 if ($lang eq 'nolang') {
11876:                                     $chg = &mt('custom log-in help file for no preferred language');
11877:                                 } else {
11878:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
11879:                                 }
11880:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
11881:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
11882:                                                       '?inhibitmenu=yes',$chg,600,500).
11883:                                                '</li>';
11884:                             }
11885:                         }
11886:                     }
11887:                 } elsif ($item eq 'headtag') {
11888:                     if (ref($changes{$item}) eq 'HASH') {
11889:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11890:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11891:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
11892:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11893:                                 $resulttext .= '<li><a href="'.
11894:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
11895:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
11896:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
11897:                                 if ($possexempt{$lonhost}) {
11898:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
11899:                                 } else {
11900:                                     $resulttext .= &mt('included for any client IP');
11901:                                 }
11902:                                 $resulttext .= '</li>';
11903:                             }
11904:                         }
11905:                     }
11906:                 } elsif ($item eq 'saml') {
11907:                     if (ref($changes{$item}) eq 'HASH') {
11908:                         my %notlt = (
11909:                                        text   => 'Text for log-in by SSO',
11910:                                        img    => 'SSO button image',
11911:                                        alt    => 'Alt text for button image',
11912:                                        url    => 'SSO URL',
11913:                                        title  => 'Tooltip for SSO link',
11914:                                        notsso => 'Text for non-SSO log-in',
11915:                                     );
11916:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11917:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
11918:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
11919:                                                '<ul>';
11920:                                 foreach my $key ('text','img','alt','url','title','notsso') {
11921:                                     if ($currsaml{$lonhost}{$key} eq '') {
11922:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
11923:                                     } else {
11924:                                         my $value = "'$currsaml{$lonhost}{$key}'";
11925:                                         if ($key eq 'img') {
11926:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
11927:                                         }
11928:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
11929:                                                                   $value).'</li>';
11930:                                     }
11931:                                 }
11932:                                 $resulttext .= '</ul></li>';
11933:                             } else {
11934:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
11935:                             }
11936:                         }
11937:                     }
11938:                 } elsif ($item eq 'captcha') {
11939:                     if (ref($loginhash{'login'}) eq 'HASH') {
11940:                         my $chgtxt;
11941:                         if ($loginhash{'login'}{$item} eq 'notused') {
11942:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
11943:                         } else {
11944:                             my %captchas = &captcha_phrases();
11945:                             if ($captchas{$loginhash{'login'}{$item}}) {
11946:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
11947:                             } else {
11948:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
11949:                             }
11950:                         }
11951:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11952:                     }
11953:                 } elsif ($item eq 'recaptchakeys') {
11954:                     if (ref($loginhash{'login'}) eq 'HASH') {
11955:                         my ($privkey,$pubkey);
11956:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
11957:                             $pubkey = $loginhash{'login'}{$item}{'public'};
11958:                             $privkey = $loginhash{'login'}{$item}{'private'};
11959:                         }
11960:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
11961:                         if (!$pubkey) {
11962:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
11963:                         } else {
11964:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
11965:                         }
11966:                         if (!$privkey) {
11967:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
11968:                         } else {
11969:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
11970:                         }
11971:                         $chgtxt .= '</ul>';
11972:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11973:                     }
11974:                 } elsif ($item eq 'recaptchaversion') {
11975:                     if (ref($loginhash{'login'}) eq 'HASH') {
11976:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
11977:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
11978:                                            '</li>';
11979:                         }
11980:                     }
11981:                 } else {
11982:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
11983:                 }
11984:             }
11985:             $resulttext .= $colchgtext.'</ul>';
11986:         } else {
11987:             $resulttext = &mt('No changes made to log-in page settings');
11988:         }
11989:     } else {
11990:         $resulttext = '<span class="LC_error">'.
11991: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11992:     }
11993:     if ($errors) {
11994:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
11995:                        $errors.'</ul>';
11996:     }
11997:     return $resulttext;
11998: }
11999: 
12000: sub check_exempt_addresses {
12001:     my ($iplist) = @_;
12002:     $iplist =~ s/^\s+//;
12003:     $iplist =~ s/\s+$//;
12004:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
12005:     my (@okips,$new);
12006:     foreach my $ip (@poss_ips) {
12007:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
12008:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
12009:                 push(@okips,$ip);
12010:             }
12011:         }
12012:     }
12013:     if (@okips > 0) {
12014:         $new = join(',',@okips);
12015:     } else {
12016:         $new = '';
12017:     }
12018:     return $new;
12019: }
12020: 
12021: sub color_font_choices {
12022:     my %choices =
12023:         &Apache::lonlocal::texthash (
12024:             img => "Header",
12025:             bgs => "Background colors",
12026:             links => "Link colors",
12027:             images => "Images",
12028:             font => "Font color",
12029:             fontmenu => "Font menu",
12030:             pgbg => "Page",
12031:             tabbg => "Header",
12032:             sidebg => "Border",
12033:             link => "Link",
12034:             alink => "Active link",
12035:             vlink => "Visited link",
12036:         );
12037:     return %choices;
12038: }
12039: 
12040: sub modify_rolecolors {
12041:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
12042:     my ($resulttext,%rolehash);
12043:     $rolehash{'rolecolors'} = {};
12044:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
12045:         if ($domconfig{'rolecolors'} eq '') {
12046:             $domconfig{'rolecolors'} = {};
12047:         }
12048:     }
12049:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
12050:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
12051:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
12052:                                              $dom);
12053:     if ($putresult eq 'ok') {
12054:         if (keys(%changes) > 0) {
12055:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12056:             if (ref($lastactref) eq 'HASH') {
12057:                 $lastactref->{'domainconfig'} = 1;
12058:             }
12059:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
12060:                                              $rolehash{'rolecolors'});
12061:         } else {
12062:             $resulttext = &mt('No changes made to default color schemes');
12063:         }
12064:     } else {
12065:         $resulttext = '<span class="LC_error">'.
12066: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12067:     }
12068:     if ($errors) {
12069:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
12070:                        $errors.'</ul>';
12071:     }
12072:     return $resulttext;
12073: }
12074: 
12075: sub modify_colors {
12076:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
12077:     my (%changes,%choices);
12078:     my @bgs;
12079:     my @links = ('link','alink','vlink');
12080:     my @logintext;
12081:     my @images;
12082:     my $servadm = $r->dir_config('lonAdmEMail');
12083:     my $errors;
12084:     my %defaults;
12085:     foreach my $role (@{$roles}) {
12086:         if ($role eq 'login') {
12087:             %choices = &login_choices();
12088:             @logintext = ('textcol','bgcol');
12089:         } else {
12090:             %choices = &color_font_choices();
12091:         }
12092:         if ($role eq 'login') {
12093:             @images = ('img','logo','domlogo','login');
12094:             @bgs = ('pgbg','mainbg','sidebg');
12095:         } else {
12096:             @images = ('img');
12097:             @bgs = ('pgbg','tabbg','sidebg');
12098:         }
12099:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
12100:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
12101:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
12102:         }
12103:         if ($role eq 'login') {
12104:             foreach my $item (@logintext) {
12105:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
12106:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
12107:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
12108:                 }
12109:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
12110:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
12111:                 }
12112:             }
12113:         } else {
12114:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
12115:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
12116:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
12117:             }
12118:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
12119:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
12120:             }
12121:         }
12122:         foreach my $item (@bgs) {
12123:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
12124:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
12125:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
12126:             }
12127:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
12128:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
12129:             }
12130:         }
12131:         foreach my $item (@links) {
12132:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
12133:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
12134:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
12135:             }
12136:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
12137:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
12138:             }
12139:         }
12140:         my ($configuserok,$author_ok,$switchserver) = 
12141:             &config_check($dom,$confname,$servadm);
12142:         my ($width,$height) = &thumb_dimensions();
12143:         if (ref($domconfig->{$role}) ne 'HASH') {
12144:             $domconfig->{$role} = {};
12145:         }
12146:         foreach my $img (@images) {
12147:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
12148:                 if (defined($env{'form.login_showlogo_'.$img})) {
12149:                     $confhash->{$role}{'showlogo'}{$img} = 1;
12150:                 } else { 
12151:                     $confhash->{$role}{'showlogo'}{$img} = 0;
12152:                 }
12153:             } 
12154: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
12155: 		 && !defined($domconfig->{$role}{$img})
12156: 		 && !$env{'form.'.$role.'_del_'.$img}
12157: 		 && $env{'form.'.$role.'_import_'.$img}) {
12158: 		# import the old configured image from the .tab setting
12159: 		# if they haven't provided a new one 
12160: 		$domconfig->{$role}{$img} = 
12161: 		    $env{'form.'.$role.'_import_'.$img};
12162: 	    }
12163:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
12164:                 my $error;
12165:                 if ($configuserok eq 'ok') {
12166:                     if ($switchserver) {
12167:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
12168:                     } else {
12169:                         if ($author_ok eq 'ok') {
12170:                             my ($result,$logourl) = 
12171:                                 &publishlogo($r,'upload',$role.'_'.$img,
12172:                                            $dom,$confname,$img,$width,$height);
12173:                             if ($result eq 'ok') {
12174:                                 $confhash->{$role}{$img} = $logourl;
12175:                                 $changes{$role}{'images'}{$img} = 1;
12176:                             } else {
12177:                                 $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);
12178:                             }
12179:                         } else {
12180:                             $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);
12181:                         }
12182:                     }
12183:                 } else {
12184:                     $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);
12185:                 }
12186:                 if ($error) {
12187:                     &Apache::lonnet::logthis($error);
12188:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12189:                 }
12190:             } elsif ($domconfig->{$role}{$img} ne '') {
12191:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
12192:                     my $error;
12193:                     if ($configuserok eq 'ok') {
12194: # is confname an author?
12195:                         if ($switchserver eq '') {
12196:                             if ($author_ok eq 'ok') {
12197:                                 my ($result,$logourl) = 
12198:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
12199:                                             $dom,$confname,$img,$width,$height);
12200:                                 if ($result eq 'ok') {
12201:                                     $confhash->{$role}{$img} = $logourl;
12202: 				    $changes{$role}{'images'}{$img} = 1;
12203:                                 }
12204:                             }
12205:                         }
12206:                     }
12207:                 }
12208:             }
12209:         }
12210:         if (ref($domconfig) eq 'HASH') {
12211:             if (ref($domconfig->{$role}) eq 'HASH') {
12212:                 foreach my $img (@images) {
12213:                     if ($domconfig->{$role}{$img} ne '') {
12214:                         if ($env{'form.'.$role.'_del_'.$img}) {
12215:                             $confhash->{$role}{$img} = '';
12216:                             $changes{$role}{'images'}{$img} = 1;
12217:                         } else {
12218:                             if ($confhash->{$role}{$img} eq '') {
12219:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
12220:                             }
12221:                         }
12222:                     } else {
12223:                         if ($env{'form.'.$role.'_del_'.$img}) {
12224:                             $confhash->{$role}{$img} = '';
12225:                             $changes{$role}{'images'}{$img} = 1;
12226:                         } 
12227:                     }
12228:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
12229:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
12230:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
12231:                                 $domconfig->{$role}{'showlogo'}{$img}) {
12232:                                 $changes{$role}{'showlogo'}{$img} = 1; 
12233:                             }
12234:                         } else {
12235:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
12236:                                 $changes{$role}{'showlogo'}{$img} = 1;
12237:                             }
12238:                         }
12239:                     }
12240:                 }
12241:                 if ($domconfig->{$role}{'font'} ne '') {
12242:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
12243:                         $changes{$role}{'font'} = 1;
12244:                     }
12245:                 } else {
12246:                     if ($confhash->{$role}{'font'}) {
12247:                         $changes{$role}{'font'} = 1;
12248:                     }
12249:                 }
12250:                 if ($role ne 'login') {
12251:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
12252:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
12253:                             $changes{$role}{'fontmenu'} = 1;
12254:                         }
12255:                     } else {
12256:                         if ($confhash->{$role}{'fontmenu'}) {
12257:                             $changes{$role}{'fontmenu'} = 1;
12258:                         }
12259:                     }
12260:                 }
12261:                 foreach my $item (@bgs) {
12262:                     if ($domconfig->{$role}{$item} ne '') {
12263:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
12264:                             $changes{$role}{'bgs'}{$item} = 1;
12265:                         } 
12266:                     } else {
12267:                         if ($confhash->{$role}{$item}) {
12268:                             $changes{$role}{'bgs'}{$item} = 1;
12269:                         }
12270:                     }
12271:                 }
12272:                 foreach my $item (@links) {
12273:                     if ($domconfig->{$role}{$item} ne '') {
12274:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
12275:                             $changes{$role}{'links'}{$item} = 1;
12276:                         }
12277:                     } else {
12278:                         if ($confhash->{$role}{$item}) {
12279:                             $changes{$role}{'links'}{$item} = 1;
12280:                         }
12281:                     }
12282:                 }
12283:                 foreach my $item (@logintext) {
12284:                     if ($domconfig->{$role}{$item} ne '') {
12285:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
12286:                             $changes{$role}{'logintext'}{$item} = 1;
12287:                         }
12288:                     } else {
12289:                         if ($confhash->{$role}{$item}) {
12290:                             $changes{$role}{'logintext'}{$item} = 1;
12291:                         }
12292:                     }
12293:                 }
12294:             } else {
12295:                 &default_change_checker($role,\@images,\@links,\@bgs,
12296:                                         \@logintext,$confhash,\%changes); 
12297:             }
12298:         } else {
12299:             &default_change_checker($role,\@images,\@links,\@bgs,
12300:                                     \@logintext,$confhash,\%changes); 
12301:         }
12302:     }
12303:     return ($errors,%changes);
12304: }
12305: 
12306: sub config_check {
12307:     my ($dom,$confname,$servadm) = @_;
12308:     my ($configuserok,$author_ok,$switchserver,%currroles);
12309:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
12310:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
12311:                                                    $confname,$servadm);
12312:     if ($configuserok eq 'ok') {
12313:         $switchserver = &check_switchserver($dom,$confname);
12314:         if ($switchserver eq '') {
12315:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
12316:         }
12317:     }
12318:     return ($configuserok,$author_ok,$switchserver);
12319: }
12320: 
12321: sub default_change_checker {
12322:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
12323:     foreach my $item (@{$links}) {
12324:         if ($confhash->{$role}{$item}) {
12325:             $changes->{$role}{'links'}{$item} = 1;
12326:         }
12327:     }
12328:     foreach my $item (@{$bgs}) {
12329:         if ($confhash->{$role}{$item}) {
12330:             $changes->{$role}{'bgs'}{$item} = 1;
12331:         }
12332:     }
12333:     foreach my $item (@{$logintext}) {
12334:         if ($confhash->{$role}{$item}) {
12335:             $changes->{$role}{'logintext'}{$item} = 1;
12336:         }
12337:     }
12338:     foreach my $img (@{$images}) {
12339:         if ($env{'form.'.$role.'_del_'.$img}) {
12340:             $confhash->{$role}{$img} = '';
12341:             $changes->{$role}{'images'}{$img} = 1;
12342:         }
12343:         if ($role eq 'login') {
12344:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
12345:                 $changes->{$role}{'showlogo'}{$img} = 1;
12346:             }
12347:         }
12348:     }
12349:     if ($confhash->{$role}{'font'}) {
12350:         $changes->{$role}{'font'} = 1;
12351:     }
12352: }
12353: 
12354: sub display_colorchgs {
12355:     my ($dom,$changes,$roles,$confhash) = @_;
12356:     my (%choices,$resulttext);
12357:     if (!grep(/^login$/,@{$roles})) {
12358:         $resulttext = &mt('Changes made:').'<br />';
12359:     }
12360:     foreach my $role (@{$roles}) {
12361:         if ($role eq 'login') {
12362:             %choices = &login_choices();
12363:         } else {
12364:             %choices = &color_font_choices();
12365:         }
12366:         if (ref($changes->{$role}) eq 'HASH') {
12367:             if ($role ne 'login') {
12368:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
12369:             }
12370:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
12371:                 if ($role ne 'login') {
12372:                     $resulttext .= '<ul>';
12373:                 }
12374:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
12375:                     if ($role ne 'login') {
12376:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
12377:                     }
12378:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
12379:                         if (($role eq 'login') && ($key eq 'showlogo')) {
12380:                             if ($confhash->{$role}{$key}{$item}) {
12381:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
12382:                             } else {
12383:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
12384:                             }
12385:                         } elsif ($confhash->{$role}{$item} eq '') {
12386:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
12387:                         } else {
12388:                             my $newitem = $confhash->{$role}{$item};
12389:                             if ($key eq 'images') {
12390:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
12391:                             }
12392:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
12393:                         }
12394:                     }
12395:                     if ($role ne 'login') {
12396:                         $resulttext .= '</ul></li>';
12397:                     }
12398:                 } else {
12399:                     if ($confhash->{$role}{$key} eq '') {
12400:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
12401:                     } else {
12402:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
12403:                     }
12404:                 }
12405:                 if ($role ne 'login') {
12406:                     $resulttext .= '</ul>';
12407:                 }
12408:             }
12409:         }
12410:     }
12411:     return $resulttext;
12412: }
12413: 
12414: sub thumb_dimensions {
12415:     return ('200','50');
12416: }
12417: 
12418: sub check_dimensions {
12419:     my ($inputfile) = @_;
12420:     my ($fullwidth,$fullheight);
12421:     if ($inputfile =~ m|^[/\w.\-]+$|) {
12422:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
12423:             my $imageinfo = <PIPE>;
12424:             if (!close(PIPE)) {
12425:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
12426:             }
12427:             chomp($imageinfo);
12428:             my ($fullsize) = 
12429:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
12430:             if ($fullsize) {
12431:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
12432:             }
12433:         }
12434:     }
12435:     return ($fullwidth,$fullheight);
12436: }
12437: 
12438: sub check_configuser {
12439:     my ($uhome,$dom,$confname,$servadm) = @_;
12440:     my ($configuserok,%currroles);
12441:     if ($uhome eq 'no_host') {
12442:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
12443:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
12444:         $configuserok = 
12445:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
12446:                              $configpass,'','','','','',undef,$servadm);
12447:     } else {
12448:         $configuserok = 'ok';
12449:         %currroles = 
12450:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
12451:     }
12452:     return ($configuserok,%currroles);
12453: }
12454: 
12455: sub check_authorstatus {
12456:     my ($dom,$confname,%currroles) = @_;
12457:     my $author_ok;
12458:     if (!$currroles{':'.$dom.':au'}) {
12459:         my $start = time;
12460:         my $end = 0;
12461:         $author_ok = 
12462:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
12463:                                         'au',$end,$start,'','','domconfig');
12464:     } else {
12465:         $author_ok = 'ok';
12466:     }
12467:     return $author_ok;
12468: }
12469: 
12470: sub publishlogo {
12471:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
12472:     my ($output,$fname,$logourl,$madethumb);
12473:     if ($action eq 'upload') {
12474:         $fname=$env{'form.'.$formname.'.filename'};
12475:         chop($env{'form.'.$formname});
12476:     } else {
12477:         ($fname) = ($formname =~ /([^\/]+)$/);
12478:     }
12479:     if ($savefileas ne '') {
12480:         $fname = $savefileas;
12481:     }
12482:     $fname=&Apache::lonnet::clean_filename($fname);
12483: # See if there is anything left
12484:     unless ($fname) { return ('error: no uploaded file'); }
12485:     $fname="$subdir/$fname";
12486:     my $docroot=$r->dir_config('lonDocRoot');
12487:     my $filepath="$docroot/priv";
12488:     my $relpath = "$dom/$confname";
12489:     my ($fnamepath,$file,$fetchthumb);
12490:     $file=$fname;
12491:     if ($fname=~m|/|) {
12492:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
12493:     }
12494:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
12495:     my $count;
12496:     for ($count=5;$count<=$#parts;$count++) {
12497:         $filepath.="/$parts[$count]";
12498:         if ((-e $filepath)!=1) {
12499:             mkdir($filepath,02770);
12500:         }
12501:     }
12502:     # Check for bad extension and disallow upload
12503:     if ($file=~/\.(\w+)$/ &&
12504:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12505:         $output = 
12506:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
12507:     } elsif ($file=~/\.(\w+)$/ &&
12508:         !defined(&Apache::loncommon::fileembstyle($1))) {
12509:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
12510:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
12511:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
12512:     } elsif (-d "$filepath/$file") {
12513:         $output = &mt('Filename is a directory name - rename the file and re-upload');
12514:     } else {
12515:         my $source = $filepath.'/'.$file;
12516:         my $logfile;
12517:         if (!open($logfile,">>",$source.'.log')) {
12518:             return (&mt('No write permission to Authoring Space'));
12519:         }
12520:         print $logfile
12521: "\n================= Publish ".localtime()." ================\n".
12522: $env{'user.name'}.':'.$env{'user.domain'}."\n";
12523: # Save the file
12524:         if (!open(FH,">",$source)) {
12525:             &Apache::lonnet::logthis('Failed to create '.$source);
12526:             return (&mt('Failed to create file'));
12527:         }
12528:         if ($action eq 'upload') {
12529:             if (!print FH ($env{'form.'.$formname})) {
12530:                 &Apache::lonnet::logthis('Failed to write to '.$source);
12531:                 return (&mt('Failed to write file'));
12532:             }
12533:         } else {
12534:             my $original = &Apache::lonnet::filelocation('',$formname);
12535:             if(!copy($original,$source)) {
12536:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
12537:                 return (&mt('Failed to write file'));
12538:             }
12539:         }
12540:         close(FH);
12541:         chmod(0660, $source); # Permissions to rw-rw---.
12542: 
12543:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
12544:         my $copyfile=$targetdir.'/'.$file;
12545: 
12546:         my @parts=split(/\//,$targetdir);
12547:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
12548:         for (my $count=5;$count<=$#parts;$count++) {
12549:             $path.="/$parts[$count]";
12550:             if (!-e $path) {
12551:                 print $logfile "\nCreating directory ".$path;
12552:                 mkdir($path,02770);
12553:             }
12554:         }
12555:         my $versionresult;
12556:         if (-e $copyfile) {
12557:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
12558:         } else {
12559:             $versionresult = 'ok';
12560:         }
12561:         if ($versionresult eq 'ok') {
12562:             if (copy($source,$copyfile)) {
12563:                 print $logfile "\nCopied original source to ".$copyfile."\n";
12564:                 $output = 'ok';
12565:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
12566:                 push(@{$modified_urls},[$copyfile,$source]);
12567:                 my $metaoutput = 
12568:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
12569:                 unless ($registered_cleanup) {
12570:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
12571:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12572:                     $registered_cleanup=1;
12573:                 }
12574:             } else {
12575:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
12576:                 $output = &mt('Failed to copy file to RES space').", $!";
12577:             }
12578:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
12579:                 my $inputfile = $filepath.'/'.$file;
12580:                 my $outfile = $filepath.'/'.'tn-'.$file;
12581:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
12582:                 if ($fullwidth ne '' && $fullheight ne '') { 
12583:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
12584:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
12585:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
12586:                         system({$args[0]} @args);
12587:                         chmod(0660, $filepath.'/tn-'.$file);
12588:                         if (-e $outfile) {
12589:                             my $copyfile=$targetdir.'/tn-'.$file;
12590:                             if (copy($outfile,$copyfile)) {
12591:                                 print $logfile "\nCopied source to ".$copyfile."\n";
12592:                                 my $thumb_metaoutput = 
12593:                                     &write_metadata($dom,$confname,$formname,
12594:                                                     $targetdir,'tn-'.$file,$logfile);
12595:                                 push(@{$modified_urls},[$copyfile,$outfile]);
12596:                                 unless ($registered_cleanup) {
12597:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
12598:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12599:                                     $registered_cleanup=1;
12600:                                 }
12601:                                 $madethumb = 1;
12602:                             } else {
12603:                                 print $logfile "\nUnable to write ".$copyfile.
12604:                                                ':'.$!."\n";
12605:                             }
12606:                         }
12607:                     }
12608:                 }
12609:             }
12610:         } else {
12611:             $output = $versionresult;
12612:         }
12613:     }
12614:     return ($output,$logourl,$madethumb);
12615: }
12616: 
12617: sub logo_versioning {
12618:     my ($targetdir,$file,$logfile) = @_;
12619:     my $target = $targetdir.'/'.$file;
12620:     my ($maxversion,$fn,$extn,$output);
12621:     $maxversion = 0;
12622:     if ($file =~ /^(.+)\.(\w+)$/) {
12623:         $fn=$1;
12624:         $extn=$2;
12625:     }
12626:     opendir(DIR,$targetdir);
12627:     while (my $filename=readdir(DIR)) {
12628:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
12629:             $maxversion=($1>$maxversion)?$1:$maxversion;
12630:         }
12631:     }
12632:     $maxversion++;
12633:     print $logfile "\nCreating old version ".$maxversion."\n";
12634:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
12635:     if (copy($target,$copyfile)) {
12636:         print $logfile "Copied old target to ".$copyfile."\n";
12637:         $copyfile=$copyfile.'.meta';
12638:         if (copy($target.'.meta',$copyfile)) {
12639:             print $logfile "Copied old target metadata to ".$copyfile."\n";
12640:             $output = 'ok';
12641:         } else {
12642:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
12643:             $output = &mt('Failed to copy old meta').", $!, ";
12644:         }
12645:     } else {
12646:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
12647:         $output = &mt('Failed to copy old target').", $!, ";
12648:     }
12649:     return $output;
12650: }
12651: 
12652: sub write_metadata {
12653:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
12654:     my (%metadatafields,%metadatakeys,$output);
12655:     $metadatafields{'title'}=$formname;
12656:     $metadatafields{'creationdate'}=time;
12657:     $metadatafields{'lastrevisiondate'}=time;
12658:     $metadatafields{'copyright'}='public';
12659:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
12660:                                          $env{'user.domain'};
12661:     $metadatafields{'authorspace'}=$confname.':'.$dom;
12662:     $metadatafields{'domain'}=$dom;
12663:     {
12664:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
12665:         my $mfh;
12666:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
12667:             foreach (sort(keys(%metadatafields))) {
12668:                 unless ($_=~/\./) {
12669:                     my $unikey=$_;
12670:                     $unikey=~/^([A-Za-z]+)/;
12671:                     my $tag=$1;
12672:                     $tag=~tr/A-Z/a-z/;
12673:                     print $mfh "\n\<$tag";
12674:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
12675:                         my $value=$metadatafields{$unikey.'.'.$_};
12676:                         $value=~s/\"/\'\'/g;
12677:                         print $mfh ' '.$_.'="'.$value.'"';
12678:                     }
12679:                     print $mfh '>'.
12680:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
12681:                             .'</'.$tag.'>';
12682:                 }
12683:             }
12684:             $output = 'ok';
12685:             print $logfile "\nWrote metadata";
12686:             close($mfh);
12687:         } else {
12688:             print $logfile "\nFailed to open metadata file";
12689:             $output = &mt('Could not write metadata');
12690:         }
12691:     }
12692:     return $output;
12693: }
12694: 
12695: sub notifysubscribed {
12696:     foreach my $targetsource (@{$modified_urls}){
12697:         next unless (ref($targetsource) eq 'ARRAY');
12698:         my ($target,$source)=@{$targetsource};
12699:         if ($source ne '') {
12700:             if (open(my $logfh,">>",$source.'.log')) {
12701:                 print $logfh "\nCleanup phase: Notifications\n";
12702:                 my @subscribed=&subscribed_hosts($target);
12703:                 foreach my $subhost (@subscribed) {
12704:                     print $logfh "\nNotifying host ".$subhost.':';
12705:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
12706:                     print $logfh $reply;
12707:                 }
12708:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
12709:                 foreach my $subhost (@subscribedmeta) {
12710:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
12711:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
12712:                                                         $subhost);
12713:                     print $logfh $reply;
12714:                 }
12715:                 print $logfh "\n============ Done ============\n";
12716:                 close($logfh);
12717:             }
12718:         }
12719:     }
12720:     return OK;
12721: }
12722: 
12723: sub subscribed_hosts {
12724:     my ($target) = @_;
12725:     my @subscribed;
12726:     if (open(my $fh,"<","$target.subscription")) {
12727:         while (my $subline=<$fh>) {
12728:             if ($subline =~ /^($match_lonid):/) {
12729:                 my $host = $1;
12730:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
12731:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
12732:                         push(@subscribed,$host);
12733:                     }
12734:                 }
12735:             }
12736:         }
12737:     }
12738:     return @subscribed;
12739: }
12740: 
12741: sub check_switchserver {
12742:     my ($dom,$confname) = @_;
12743:     my ($allowed,$switchserver);
12744:     my $home = &Apache::lonnet::homeserver($confname,$dom);
12745:     if ($home eq 'no_host') {
12746:         $home = &Apache::lonnet::domain($dom,'primary');
12747:     }
12748:     my @ids=&Apache::lonnet::current_machine_ids();
12749:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
12750:     if (!$allowed) {
12751: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
12752:     }
12753:     return $switchserver;
12754: }
12755: 
12756: sub modify_quotas {
12757:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12758:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
12759:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
12760:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
12761:         $validationfieldsref);
12762:     if ($action eq 'quotas') {
12763:         $context = 'tools'; 
12764:     } else {
12765:         $context = $action;
12766:     }
12767:     if ($context eq 'requestcourses') {
12768:         @usertools = ('official','unofficial','community','textbook','placement','lti');
12769:         @options =('norequest','approval','validate','autolimit');
12770:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
12771:         %titles = &courserequest_titles();
12772:         $toolregexp = join('|',@usertools);
12773:         %conditions = &courserequest_conditions();
12774:         $confname = $dom.'-domainconfig';
12775:         my $servadm = $r->dir_config('lonAdmEMail');
12776:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12777:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
12778:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
12779:     } elsif ($context eq 'requestauthor') {
12780:         @usertools = ('author');
12781:         %titles = &authorrequest_titles();
12782:     } else {
12783:         @usertools = ('aboutme','blog','webdav','portfolio');
12784:         %titles = &tool_titles();
12785:     }
12786:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12787:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12788:     foreach my $key (keys(%env)) {
12789:         if ($context eq 'requestcourses') {
12790:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
12791:                 my $item = $1;
12792:                 my $type = $2;
12793:                 if ($type =~ /^limit_(.+)/) {
12794:                     $limithash{$item}{$1} = $env{$key};
12795:                 } else {
12796:                     $confhash{$item}{$type} = $env{$key};
12797:                 }
12798:             }
12799:         } elsif ($context eq 'requestauthor') {
12800:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
12801:                 $confhash{$1} = $env{$key};
12802:             }
12803:         } else {
12804:             if ($key =~ /^form\.quota_(.+)$/) {
12805:                 $confhash{'defaultquota'}{$1} = $env{$key};
12806:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
12807:                 $confhash{'authorquota'}{$1} = $env{$key};
12808:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
12809:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
12810:             }
12811:         }
12812:     }
12813:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12814:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
12815:         @approvalnotify = sort(@approvalnotify);
12816:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
12817:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
12818:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
12819:         foreach my $type (@hasuniquecode) {
12820:             if (grep(/^\Q$type\E$/,@crstypes)) {
12821:                 $confhash{'uniquecode'}{$type} = 1;
12822:             }
12823:         }
12824:         my (%newbook,%allpos);
12825:         if ($context eq 'requestcourses') {
12826:             foreach my $type ('textbooks','templates') {
12827:                 @{$allpos{$type}} = (); 
12828:                 my $invalid;
12829:                 if ($type eq 'textbooks') {
12830:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
12831:                 } else {
12832:                     $invalid = &mt('Invalid LON-CAPA course for template');
12833:                 }
12834:                 if ($env{'form.'.$type.'_addbook'}) {
12835:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
12836:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
12837:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
12838:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
12839:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12840:                         } else {
12841:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
12842:                             my $position = $env{'form.'.$type.'_addbook_pos'};
12843:                             $position =~ s/\D+//g;
12844:                             if ($position ne '') {
12845:                                 $allpos{$type}[$position] = $newbook{$type};
12846:                             }
12847:                         }
12848:                     } else {
12849:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12850:                     }
12851:                 }
12852:             } 
12853:         }
12854:         if (ref($domconfig{$action}) eq 'HASH') {
12855:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
12856:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
12857:                     $changes{'notify'}{'approval'} = 1;
12858:                 }
12859:             } else {
12860:                 if ($confhash{'notify'}{'approval'}) {
12861:                     $changes{'notify'}{'approval'} = 1;
12862:                 }
12863:             }
12864:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
12865:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
12866:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
12867:                         unless ($confhash{'uniquecode'}{$crstype}) {
12868:                             $changes{'uniquecode'} = 1;
12869:                         }
12870:                     }
12871:                     unless ($changes{'uniquecode'}) {
12872:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
12873:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
12874:                                 $changes{'uniquecode'} = 1;
12875:                             }
12876:                         }
12877:                     }
12878:                } else {
12879:                    $changes{'uniquecode'} = 1;
12880:                }
12881:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
12882:                 $changes{'uniquecode'} = 1;
12883:             }
12884:             if ($context eq 'requestcourses') {
12885:                 foreach my $type ('textbooks','templates') {
12886:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
12887:                         my %deletions;
12888:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
12889:                         if (@todelete) {
12890:                             map { $deletions{$_} = 1; } @todelete;
12891:                         }
12892:                         my %imgdeletions;
12893:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
12894:                         if (@todeleteimages) {
12895:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
12896:                         }
12897:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
12898:                         for (my $i=0; $i<=$maxnum; $i++) {
12899:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
12900:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
12901:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
12902:                                 if ($deletions{$key}) {
12903:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
12904:                                         #FIXME need to obsolete item in RES space
12905:                                     }
12906:                                     next;
12907:                                 } else {
12908:                                     my $newpos = $env{'form.'.$itemid};
12909:                                     $newpos =~ s/\D+//g;
12910:                                     foreach my $item ('subject','title','publisher','author') {
12911:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12912:                                                  ($type eq 'templates'));
12913:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
12914:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
12915:                                             $changes{$type}{$key} = 1;
12916:                                         }
12917:                                     }
12918:                                     $allpos{$type}[$newpos] = $key;
12919:                                 }
12920:                                 if ($imgdeletions{$key}) {
12921:                                     $changes{$type}{$key} = 1;
12922:                                     #FIXME need to obsolete item in RES space
12923:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
12924:                                     my ($cdom,$cnum) = split(/_/,$key);
12925:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12926:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12927:                                     } else {
12928:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
12929:                                                                                       $cdom,$cnum,$type,$configuserok,
12930:                                                                                       $switchserver,$author_ok);
12931:                                         if ($imgurl) {
12932:                                             $confhash{$type}{$key}{'image'} = $imgurl;
12933:                                             $changes{$type}{$key} = 1; 
12934:                                         }
12935:                                         if ($error) {
12936:                                             &Apache::lonnet::logthis($error);
12937:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12938:                                         }
12939:                                     }
12940:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
12941:                                     $confhash{$type}{$key}{'image'} = 
12942:                                         $domconfig{$action}{$type}{$key}{'image'};
12943:                                 }
12944:                             }
12945:                         }
12946:                     }
12947:                 }
12948:             }
12949:         } else {
12950:             if ($confhash{'notify'}{'approval'}) {
12951:                 $changes{'notify'}{'approval'} = 1;
12952:             }
12953:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
12954:                 $changes{'uniquecode'} = 1;
12955:             }
12956:         }
12957:         if ($context eq 'requestcourses') {
12958:             foreach my $type ('textbooks','templates') {
12959:                 if ($newbook{$type}) {
12960:                     $changes{$type}{$newbook{$type}} = 1;
12961:                     foreach my $item ('subject','title','publisher','author') {
12962:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12963:                                  ($type eq 'template'));
12964:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
12965:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
12966:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
12967:                         }
12968:                     }
12969:                     if ($type eq 'textbooks') {
12970:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
12971:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
12972:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12973:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12974:                             } else {
12975:                                 my ($imageurl,$error) =
12976:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
12977:                                                             $configuserok,$switchserver,$author_ok);
12978:                                 if ($imageurl) {
12979:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
12980:                                 }
12981:                                 if ($error) {
12982:                                     &Apache::lonnet::logthis($error);
12983:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12984:                                 }
12985:                             }
12986:                         }
12987:                     }
12988:                 }
12989:                 if (@{$allpos{$type}} > 0) {
12990:                     my $idx = 0;
12991:                     foreach my $item (@{$allpos{$type}}) {
12992:                         if ($item ne '') {
12993:                             $confhash{$type}{$item}{'order'} = $idx;
12994:                             if (ref($domconfig{$action}) eq 'HASH') {
12995:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
12996:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
12997:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
12998:                                             $changes{$type}{$item} = 1;
12999:                                         }
13000:                                     }
13001:                                 }
13002:                             }
13003:                             $idx ++;
13004:                         }
13005:                     }
13006:                 }
13007:             }
13008:             if (ref($validationitemsref) eq 'ARRAY') {
13009:                 foreach my $item (@{$validationitemsref}) {
13010:                     if ($item eq 'fields') {
13011:                         my @changed;
13012:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
13013:                         if (@{$confhash{'validation'}{$item}} > 0) {
13014:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
13015:                         }
13016:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13017:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13018:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
13019:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
13020:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
13021:                                 } else {
13022:                                     @changed = @{$confhash{'validation'}{$item}};
13023:                                 }
13024:                             } else {
13025:                                 @changed = @{$confhash{'validation'}{$item}};
13026:                             }
13027:                         } else {
13028:                             @changed = @{$confhash{'validation'}{$item}};
13029:                         }
13030:                         if (@changed) {
13031:                             if ($confhash{'validation'}{$item}) {
13032:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
13033:                             } else {
13034:                                 $changes{'validation'}{$item} = &mt('None');
13035:                             }
13036:                         }
13037:                     } else {
13038:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
13039:                         if ($item eq 'markup') {
13040:                             if ($env{'form.requestcourses_validation_'.$item}) {
13041:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
13042:                             }
13043:                         }
13044:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13045:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13046:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
13047:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13048:                                 }
13049:                             } else {
13050:                                 if ($confhash{'validation'}{$item} ne '') {
13051:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13052:                                 }
13053:                             }
13054:                         } else {
13055:                             if ($confhash{'validation'}{$item} ne '') {
13056:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13057:                             }
13058:                         }
13059:                     }
13060:                 }
13061:             }
13062:             if ($env{'form.validationdc'}) {
13063:                 my $newval = $env{'form.validationdc'};
13064:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
13065:                 if (exists($domcoords{$newval})) {
13066:                     $confhash{'validation'}{'dc'} = $newval;
13067:                 }
13068:             }
13069:             if (ref($confhash{'validation'}) eq 'HASH') {
13070:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13071:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13072:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
13073:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
13074:                                 if ($confhash{'validation'}{'dc'} eq '') {
13075:                                     $changes{'validation'}{'dc'} = &mt('None');
13076:                                 } else {
13077:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13078:                                 }
13079:                             }
13080:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
13081:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13082:                         }
13083:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
13084:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13085:                     }
13086:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
13087:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13088:                 }
13089:             } else {
13090:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13091:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13092:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
13093:                             $changes{'validation'}{'dc'} = &mt('None');
13094:                         }
13095:                     }
13096:                 }
13097:             }
13098:         }
13099:     } else {
13100:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
13101:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
13102:     }
13103:     foreach my $item (@usertools) {
13104:         foreach my $type (@{$types},'default','_LC_adv') {
13105:             my $unset; 
13106:             if ($context eq 'requestcourses') {
13107:                 $unset = '0';
13108:                 if ($type eq '_LC_adv') {
13109:                     $unset = '';
13110:                 }
13111:                 if ($confhash{$item}{$type} eq 'autolimit') {
13112:                     $confhash{$item}{$type} .= '=';
13113:                     unless ($limithash{$item}{$type} =~ /\D/) {
13114:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
13115:                     }
13116:                 }
13117:             } elsif ($context eq 'requestauthor') {
13118:                 $unset = '0';
13119:                 if ($type eq '_LC_adv') {
13120:                     $unset = '';
13121:                 }
13122:             } else {
13123:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
13124:                     $confhash{$item}{$type} = 1;
13125:                 } else {
13126:                     $confhash{$item}{$type} = 0;
13127:                 }
13128:             }
13129:             if (ref($domconfig{$action}) eq 'HASH') {
13130:                 if ($action eq 'requestauthor') {
13131:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
13132:                         $changes{$type} = 1;
13133:                     }
13134:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
13135:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
13136:                         $changes{$item}{$type} = 1;
13137:                     }
13138:                 } else {
13139:                     if ($context eq 'requestcourses') {
13140:                         if ($confhash{$item}{$type} ne $unset) {
13141:                             $changes{$item}{$type} = 1;
13142:                         }
13143:                     } else {
13144:                         if (!$confhash{$item}{$type}) {
13145:                             $changes{$item}{$type} = 1;
13146:                         }
13147:                     }
13148:                 }
13149:             } else {
13150:                 if ($context eq 'requestcourses') {
13151:                     if ($confhash{$item}{$type} ne $unset) {
13152:                         $changes{$item}{$type} = 1;
13153:                     }
13154:                 } elsif ($context eq 'requestauthor') {
13155:                     if ($confhash{$type} ne $unset) {
13156:                         $changes{$type} = 1;
13157:                     }
13158:                 } else {
13159:                     if (!$confhash{$item}{$type}) {
13160:                         $changes{$item}{$type} = 1;
13161:                     }
13162:                 }
13163:             }
13164:         }
13165:     }
13166:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
13167:         if (ref($domconfig{'quotas'}) eq 'HASH') {
13168:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
13169:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
13170:                     if (exists($confhash{'defaultquota'}{$key})) {
13171:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
13172:                             $changes{'defaultquota'}{$key} = 1;
13173:                         }
13174:                     } else {
13175:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
13176:                     }
13177:                 }
13178:             } else {
13179:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
13180:                     if (exists($confhash{'defaultquota'}{$key})) {
13181:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
13182:                             $changes{'defaultquota'}{$key} = 1;
13183:                         }
13184:                     } else {
13185:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
13186:                     }
13187:                 }
13188:             }
13189:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
13190:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
13191:                     if (exists($confhash{'authorquota'}{$key})) {
13192:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
13193:                             $changes{'authorquota'}{$key} = 1;
13194:                         }
13195:                     } else {
13196:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
13197:                     }
13198:                 }
13199:             }
13200:         }
13201:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
13202:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
13203:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
13204:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
13205:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
13206:                             $changes{'defaultquota'}{$key} = 1;
13207:                         }
13208:                     } else {
13209:                         if (!exists($domconfig{'quotas'}{$key})) {
13210:                             $changes{'defaultquota'}{$key} = 1;
13211:                         }
13212:                     }
13213:                 } else {
13214:                     $changes{'defaultquota'}{$key} = 1;
13215:                 }
13216:             }
13217:         }
13218:         if (ref($confhash{'authorquota'}) eq 'HASH') {
13219:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
13220:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
13221:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
13222:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
13223:                             $changes{'authorquota'}{$key} = 1;
13224:                         }
13225:                     } else {
13226:                         $changes{'authorquota'}{$key} = 1;
13227:                     }
13228:                 } else {
13229:                     $changes{'authorquota'}{$key} = 1;
13230:                 }
13231:             }
13232:         }
13233:     }
13234: 
13235:     if ($context eq 'requestauthor') {
13236:         $domdefaults{'requestauthor'} = \%confhash;
13237:     } else {
13238:         foreach my $key (keys(%confhash)) {
13239:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
13240:                 $domdefaults{$key} = $confhash{$key};
13241:             }
13242:         }
13243:     }
13244: 
13245:     my %quotahash = (
13246:                       $action => { %confhash }
13247:                     );
13248:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
13249:                                              $dom);
13250:     if ($putresult eq 'ok') {
13251:         if (keys(%changes) > 0) {
13252:             my $cachetime = 24*60*60;
13253:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13254:             if (ref($lastactref) eq 'HASH') {
13255:                 $lastactref->{'domdefaults'} = 1;
13256:             }
13257:             $resulttext = &mt('Changes made:').'<ul>';
13258:             unless (($context eq 'requestcourses') ||
13259:                     ($context eq 'requestauthor')) {
13260:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
13261:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
13262:                     foreach my $type (@{$types},'default') {
13263:                         if (defined($changes{'defaultquota'}{$type})) {
13264:                             my $typetitle = $usertypes->{$type};
13265:                             if ($type eq 'default') {
13266:                                 $typetitle = $othertitle;
13267:                             }
13268:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
13269:                         }
13270:                     }
13271:                     $resulttext .= '</ul></li>';
13272:                 }
13273:                 if (ref($changes{'authorquota'}) eq 'HASH') {
13274:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
13275:                     foreach my $type (@{$types},'default') {
13276:                         if (defined($changes{'authorquota'}{$type})) {
13277:                             my $typetitle = $usertypes->{$type};
13278:                             if ($type eq 'default') {
13279:                                 $typetitle = $othertitle;
13280:                             }
13281:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
13282:                         }
13283:                     }
13284:                     $resulttext .= '</ul></li>';
13285:                 }
13286:             }
13287:             my %newenv;
13288:             foreach my $item (@usertools) {
13289:                 my (%haschgs,%inconf);
13290:                 if ($context eq 'requestauthor') {
13291:                     %haschgs = %changes;
13292:                     %inconf = %confhash;
13293:                 } else {
13294:                     if (ref($changes{$item}) eq 'HASH') {
13295:                         %haschgs = %{$changes{$item}};
13296:                     }
13297:                     if (ref($confhash{$item}) eq 'HASH') {
13298:                         %inconf = %{$confhash{$item}};
13299:                     }
13300:                 }
13301:                 if (keys(%haschgs) > 0) {
13302:                     my $newacc = 
13303:                         &Apache::lonnet::usertools_access($env{'user.name'},
13304:                                                           $env{'user.domain'},
13305:                                                           $item,'reload',$context);
13306:                     if (($context eq 'requestcourses') ||
13307:                         ($context eq 'requestauthor')) {
13308:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
13309:                             $newenv{'environment.canrequest.'.$item} = $newacc;
13310:                         }
13311:                     } else {
13312:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
13313:                             $newenv{'environment.availabletools.'.$item} = $newacc;
13314:                         }
13315:                     }
13316:                     unless ($context eq 'requestauthor') {
13317:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
13318:                     }
13319:                     foreach my $type (@{$types},'default','_LC_adv') {
13320:                         if ($haschgs{$type}) {
13321:                             my $typetitle = $usertypes->{$type};
13322:                             if ($type eq 'default') {
13323:                                 $typetitle = $othertitle;
13324:                             } elsif ($type eq '_LC_adv') {
13325:                                 $typetitle = 'LON-CAPA Advanced Users'; 
13326:                             }
13327:                             if ($inconf{$type}) {
13328:                                 if ($context eq 'requestcourses') {
13329:                                     my $cond;
13330:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
13331:                                         if ($1 eq '') {
13332:                                             $cond = &mt('(Automatic processing of any request).');
13333:                                         } else {
13334:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
13335:                                         }
13336:                                     } else { 
13337:                                         $cond = $conditions{$inconf{$type}};
13338:                                     }
13339:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
13340:                                 } elsif ($context eq 'requestauthor') {
13341:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
13342:                                                              $titles{$inconf{$type}},$typetitle);
13343: 
13344:                                 } else {
13345:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
13346:                                 }
13347:                             } else {
13348:                                 if ($type eq '_LC_adv') {
13349:                                     if ($inconf{$type} eq '0') {
13350:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
13351:                                     } else { 
13352:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
13353:                                     }
13354:                                 } else {
13355:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
13356:                                 }
13357:                             }
13358:                         }
13359:                     }
13360:                     unless ($context eq 'requestauthor') {
13361:                         $resulttext .= '</ul></li>';
13362:                     }
13363:                 }
13364:             }
13365:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
13366:                 if (ref($changes{'notify'}) eq 'HASH') {
13367:                     if ($changes{'notify'}{'approval'}) {
13368:                         if (ref($confhash{'notify'}) eq 'HASH') {
13369:                             if ($confhash{'notify'}{'approval'}) {
13370:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
13371:                             } else {
13372:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
13373:                             }
13374:                         }
13375:                     }
13376:                 }
13377:             }
13378:             if ($action eq 'requestcourses') {
13379:                 my @offon = ('off','on');
13380:                 if ($changes{'uniquecode'}) {
13381:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
13382:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
13383:                         $resulttext .= '<li>'.
13384:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
13385:                                        '</li>';
13386:                     } else {
13387:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
13388:                                        '</li>';
13389:                     }
13390:                 }
13391:                 foreach my $type ('textbooks','templates') {
13392:                     if (ref($changes{$type}) eq 'HASH') {
13393:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
13394:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
13395:                             my %coursehash = &Apache::lonnet::coursedescription($key);
13396:                             my $coursetitle = $coursehash{'description'};
13397:                             my $position = $confhash{$type}{$key}{'order'} + 1;
13398:                             $resulttext .= '<li>';
13399:                             foreach my $item ('subject','title','publisher','author') {
13400:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
13401:                                          ($type eq 'templates'));
13402:                                 my $name = $item.':';
13403:                                 $name =~ s/^(\w)/\U$1/;
13404:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
13405:                             }
13406:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
13407:                             if ($type eq 'textbooks') {
13408:                                 if ($confhash{$type}{$key}{'image'}) {
13409:                                     $resulttext .= ' '.&mt('Image: [_1]',
13410:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
13411:                                                    ' alt="Textbook cover" />').'<br />';
13412:                                 }
13413:                             }
13414:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
13415:                         }
13416:                         $resulttext .= '</ul></li>';
13417:                     }
13418:                 }
13419:                 if (ref($changes{'validation'}) eq 'HASH') {
13420:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
13421:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
13422:                         foreach my $item (@{$validationitemsref}) {
13423:                             if (exists($changes{'validation'}{$item})) {
13424:                                 if ($item eq 'markup') {
13425:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
13426:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
13427:                                 } else {
13428:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
13429:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
13430:                                 }
13431:                             }
13432:                         }
13433:                         if (exists($changes{'validation'}{'dc'})) {
13434:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
13435:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
13436:                         }
13437:                     }
13438:                 }
13439:             }
13440:             $resulttext .= '</ul>';
13441:             if (keys(%newenv)) {
13442:                 &Apache::lonnet::appenv(\%newenv);
13443:             }
13444:         } else {
13445:             if ($context eq 'requestcourses') {
13446:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
13447:             } elsif ($context eq 'requestauthor') {
13448:                 $resulttext = &mt('No changes made to rights to request author space.');
13449:             } else {
13450:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
13451:             }
13452:         }
13453:     } else {
13454:         $resulttext = '<span class="LC_error">'.
13455: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13456:     }
13457:     if ($errors) {
13458:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
13459:                        '<ul>'.$errors.'</ul></p>';
13460:     }
13461:     return $resulttext;
13462: }
13463: 
13464: sub process_textbook_image {
13465:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
13466:     my $filename = $env{'form.'.$caller.'.filename'};
13467:     my ($error,$url);
13468:     my ($width,$height) = (50,50);
13469:     if ($configuserok eq 'ok') {
13470:         if ($switchserver) {
13471:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
13472:                          $switchserver);
13473:         } elsif ($author_ok eq 'ok') {
13474:             my ($result,$imageurl) =
13475:                 &publishlogo($r,'upload',$caller,$dom,$confname,
13476:                              "$type/$cdom/$cnum/cover",$width,$height);
13477:             if ($result eq 'ok') {
13478:                 $url = $imageurl;
13479:             } else {
13480:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
13481:             }
13482:         } else {
13483:             $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);
13484:         }
13485:     } else {
13486:         $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);
13487:     }
13488:     return ($url,$error);
13489: }
13490: 
13491: sub modify_ltitools {
13492:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13493:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13494:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
13495:     my $confname = $dom.'-domainconfig';
13496:     my $servadm = $r->dir_config('lonAdmEMail');
13497:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13498:     my (%posslti,%possfield);
13499:     my @courseroles = ('cc','in','ta','ep','st');
13500:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
13501:     map { $posslti{$_} = 1; } @ltiroles;
13502:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
13503:     map { $possfield{$_} = 1; } @allfields;
13504:     my %lt = &ltitools_names(); 
13505:     if ($env{'form.ltitools_add'}) {
13506:         my $title = $env{'form.ltitools_add_title'};
13507:         $title =~ s/(`)/'/g;
13508:         ($newid,my $error) = &get_ltitools_id($dom,$title);
13509:         if ($newid) {
13510:             my $position = $env{'form.ltitools_add_pos'};
13511:             $position =~ s/\D+//g;
13512:             if ($position ne '') {
13513:                 $allpos[$position] = $newid;
13514:             }
13515:             $changes{$newid} = 1;
13516:             foreach my $item ('title','url','key','secret','lifetime') {
13517:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
13518:                 if ($item eq 'lifetime') {
13519:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
13520:                 }
13521:                 if ($env{'form.ltitools_add_'.$item}) {
13522:                     if (($item eq 'key') || ($item eq 'secret')) {
13523:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
13524:                     } else {
13525:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
13526:                     }
13527:                 }
13528:             }
13529:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
13530:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
13531:             }
13532:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
13533:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
13534:             }
13535:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
13536:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
13537:             } else {
13538:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
13539:             }
13540:             foreach my $item ('width','height','linktext','explanation') {
13541:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
13542:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
13543:                 if (($item eq 'width') || ($item eq 'height')) {
13544:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
13545:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
13546:                     }
13547:                 } else {
13548:                     if ($env{'form.ltitools_add_'.$item} ne '') {
13549:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
13550:                     }
13551:                 }
13552:             }
13553:             if ($env{'form.ltitools_add_target'} eq 'window') {
13554:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
13555:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
13556:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
13557:             } else {
13558:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
13559:             }
13560:             foreach my $item ('passback','roster') {
13561:                 if ($env{'form.ltitools_'.$item.'_add'}) {
13562:                     $confhash{$newid}{$item} = 1;
13563:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
13564:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
13565:                         $lifetime =~ s/^\s+|\s+$//g;
13566:                         if ($lifetime =~ /^\d+\.?\d*$/) {
13567:                             $confhash{$newid}{$item.'valid'} = $lifetime;
13568:                         }
13569:                     }
13570:                 }
13571:             }
13572:             if ($env{'form.ltitools_add_image.filename'} ne '') {
13573:                 my ($imageurl,$error) =
13574:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
13575:                                             $configuserok,$switchserver,$author_ok);
13576:                 if ($imageurl) {
13577:                     $confhash{$newid}{'image'} = $imageurl;
13578:                 }
13579:                 if ($error) {
13580:                     &Apache::lonnet::logthis($error);
13581:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13582:                 }
13583:             }
13584:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
13585:             foreach my $field (@fields) {
13586:                 if ($possfield{$field}) {
13587:                     if ($field eq 'roles') {
13588:                         foreach my $role (@courseroles) {
13589:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
13590:                             if (($choice ne '') && ($posslti{$choice})) {
13591:                                 $confhash{$newid}{'roles'}{$role} = $choice;
13592:                                 if ($role eq 'cc') {
13593:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
13594:                                 }
13595:                             }
13596:                         }
13597:                     } else {
13598:                         $confhash{$newid}{'fields'}{$field} = 1;
13599:                     }
13600:                 }
13601:             }
13602:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
13603:                 if ($confhash{$newid}{'fields'}{'user'}) {
13604:                     if ($env{'form.ltitools_userincdom_add'}) {
13605:                         $confhash{$newid}{'incdom'} = 1;
13606:                     }
13607:                 }
13608:             }
13609:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
13610:             foreach my $item (@courseconfig) {
13611:                 $confhash{$newid}{'crsconf'}{$item} = 1;
13612:             }
13613:             if ($env{'form.ltitools_add_custom'}) {
13614:                 my $name = $env{'form.ltitools_add_custom_name'};
13615:                 my $value = $env{'form.ltitools_add_custom_value'};
13616:                 $value =~ s/(`)/'/g;
13617:                 $name =~ s/(`)/'/g;
13618:                 $confhash{$newid}{'custom'}{$name} = $value;
13619:             }
13620:         } else {
13621:             my $error = &mt('Failed to acquire unique ID for new external tool');   
13622:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13623:         }
13624:     }
13625:     if (ref($domconfig{$action}) eq 'HASH') {
13626:         my %deletions;
13627:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
13628:         if (@todelete) {
13629:             map { $deletions{$_} = 1; } @todelete;
13630:         }
13631:         my %customadds;
13632:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
13633:         if (@newcustom) {
13634:             map { $customadds{$_} = 1; } @newcustom;
13635:         } 
13636:         my %imgdeletions;
13637:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
13638:         if (@todeleteimages) {
13639:             map { $imgdeletions{$_} = 1; } @todeleteimages;
13640:         }
13641:         my $maxnum = $env{'form.ltitools_maxnum'};
13642:         for (my $i=0; $i<=$maxnum; $i++) {
13643:             my $itemid = $env{'form.ltitools_id_'.$i};
13644:             $itemid =~ s/\D+//g;
13645:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13646:                 if ($deletions{$itemid}) {
13647:                     if ($domconfig{$action}{$itemid}{'image'}) {
13648:                         #FIXME need to obsolete item in RES space
13649:                     }
13650:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
13651:                     next;
13652:                 } else {
13653:                     my $newpos = $env{'form.ltitools_'.$itemid};
13654:                     $newpos =~ s/\D+//g;
13655:                     foreach my $item ('title','url','lifetime') {
13656:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13657:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
13658:                             $changes{$itemid} = 1;
13659:                         }
13660:                     }
13661:                     foreach my $item ('key','secret') {
13662:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13663:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
13664:                             $changes{$itemid} = 1;
13665:                         }
13666:                     }
13667:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
13668:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
13669:                     }
13670:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
13671:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
13672:                     }
13673:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
13674:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
13675:                     } else {
13676:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
13677:                     }
13678:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
13679:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
13680:                             $changes{$itemid} = 1;
13681:                         }
13682:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
13683:                         $changes{$itemid} = 1;
13684:                     }
13685:                     foreach my $size ('width','height') {
13686:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
13687:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
13688:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
13689:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
13690:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13691:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
13692:                                     $changes{$itemid} = 1;
13693:                                 }
13694:                             } else {
13695:                                 $changes{$itemid} = 1;
13696:                             }
13697:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13698:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
13699:                                 $changes{$itemid} = 1;
13700:                             }
13701:                         }
13702:                     }
13703:                     foreach my $item ('linktext','explanation') {
13704:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
13705:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
13706:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
13707:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13708:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13709:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
13710:                                     $changes{$itemid} = 1;
13711:                                 }
13712:                             } else {
13713:                                 $changes{$itemid} = 1;
13714:                             }
13715:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13716:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
13717:                                 $changes{$itemid} = 1;
13718:                             }
13719:                         }
13720:                     }
13721:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
13722:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
13723:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
13724:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
13725:                     } else {
13726:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
13727:                     }
13728:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13729:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
13730:                             $changes{$itemid} = 1;
13731:                         }
13732:                     } else {
13733:                         $changes{$itemid} = 1;
13734:                     }
13735:                     foreach my $extra ('passback','roster') {
13736:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
13737:                             $confhash{$itemid}{$extra} = 1;
13738:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
13739:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
13740:                                 $lifetime =~ s/^\s+|\s+$//g;
13741:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
13742:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
13743:                                 }
13744:                             }
13745:                         }
13746:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
13747:                             $changes{$itemid} = 1;
13748:                         }
13749:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
13750:                             $changes{$itemid} = 1;
13751:                         }
13752:                     }
13753:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
13754:                     foreach my $item ('label','title','target','linktext','explanation','append') {
13755:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
13756:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
13757:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
13758:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
13759:                                     $changes{$itemid} = 1;
13760:                                 }
13761:                             } else {
13762:                                 $changes{$itemid} = 1;
13763:                             }
13764:                         }
13765:                     }
13766:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
13767:                     foreach my $field (@fields) {
13768:                         if ($possfield{$field}) {
13769:                             if ($field eq 'roles') {
13770:                                 foreach my $role (@courseroles) {
13771:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
13772:                                     if (($choice ne '') && ($posslti{$choice})) {
13773:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
13774:                                         if ($role eq 'cc') {
13775:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
13776:                                         }
13777:                                     }
13778:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
13779:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
13780:                                             $changes{$itemid} = 1;
13781:                                         }
13782:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
13783:                                         $changes{$itemid} = 1;
13784:                                     }
13785:                                 }
13786:                             } else {
13787:                                 $confhash{$itemid}{'fields'}{$field} = 1;
13788:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
13789:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
13790:                                         $changes{$itemid} = 1;
13791:                                     }
13792:                                 } else {
13793:                                     $changes{$itemid} = 1;
13794:                                 }
13795:                             }
13796:                         }
13797:                     }
13798:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
13799:                         if ($confhash{$itemid}{'fields'}{'user'}) {
13800:                             if ($env{'form.ltitools_userincdom_'.$i}) {
13801:                                 $confhash{$itemid}{'incdom'} = 1;
13802:                             }
13803:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
13804:                                 $changes{$itemid} = 1;
13805:                             }
13806:                         }
13807:                     }
13808:                     $allpos[$newpos] = $itemid;
13809:                 }
13810:                 if ($imgdeletions{$itemid}) {
13811:                     $changes{$itemid} = 1;
13812:                     #FIXME need to obsolete item in RES space
13813:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
13814:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
13815:                                                                  $itemid,$configuserok,$switchserver,
13816:                                                                  $author_ok);
13817:                     if ($imgurl) {
13818:                         $confhash{$itemid}{'image'} = $imgurl;
13819:                         $changes{$itemid} = 1;
13820:                     }
13821:                     if ($error) {
13822:                         &Apache::lonnet::logthis($error);
13823:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13824:                     }
13825:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
13826:                     $confhash{$itemid}{'image'} =
13827:                        $domconfig{$action}{$itemid}{'image'};
13828:                 }
13829:                 if ($customadds{$i}) {
13830:                     my $name = $env{'form.ltitools_custom_name_'.$i};
13831:                     $name =~ s/(`)/'/g;
13832:                     $name =~ s/^\s+//;
13833:                     $name =~ s/\s+$//;
13834:                     my $value = $env{'form.ltitools_custom_value_'.$i};
13835:                     $value =~ s/(`)/'/g;
13836:                     $value =~ s/^\s+//;
13837:                     $value =~ s/\s+$//;
13838:                     if ($name ne '') {
13839:                         $confhash{$itemid}{'custom'}{$name} = $value;
13840:                         $changes{$itemid} = 1;
13841:                     }
13842:                 }
13843:                 my %customdels;
13844:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
13845:                 if (@customdeletions) {
13846:                     $changes{$itemid} = 1;
13847:                 }
13848:                 map { $customdels{$_} = 1; } @customdeletions;
13849:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
13850:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
13851:                         unless ($customdels{$key}) {
13852:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
13853:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
13854:                             }
13855:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
13856:                                 $changes{$itemid} = 1;
13857:                             }
13858:                         }
13859:                     }
13860:                 }
13861:                 unless ($changes{$itemid}) {
13862:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
13863:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
13864:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
13865:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
13866:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
13867:                                         $changes{$itemid} = 1;
13868:                                         last;
13869:                                     }
13870:                                 }
13871:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
13872:                                 $changes{$itemid} = 1;
13873:                             }
13874:                         }
13875:                         last if ($changes{$itemid});
13876:                     }
13877:                 }
13878:             }
13879:         }
13880:     }
13881:     if (@allpos > 0) {
13882:         my $idx = 0;
13883:         foreach my $itemid (@allpos) {
13884:             if ($itemid ne '') {
13885:                 $confhash{$itemid}{'order'} = $idx;
13886:                 if (ref($domconfig{$action}) eq 'HASH') {
13887:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13888:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
13889:                             $changes{$itemid} = 1;
13890:                         }
13891:                     }
13892:                 }
13893:                 $idx ++;
13894:             }
13895:         }
13896:     }
13897:     my %ltitoolshash = (
13898:                           $action => { %confhash }
13899:                        );
13900:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
13901:                                              $dom);
13902:     if ($putresult eq 'ok') {
13903:         my %ltienchash = (
13904:                              $action => { %encconfig }
13905:                          );
13906:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
13907:         if (keys(%changes) > 0) {
13908:             my $cachetime = 24*60*60;
13909:             my %ltiall = %confhash;
13910:             foreach my $id (keys(%ltiall)) {
13911:                 if (ref($encconfig{$id}) eq 'HASH') {
13912:                     foreach my $item ('key','secret') {
13913:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
13914:                     }
13915:                 }
13916:             }
13917:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
13918:             if (ref($lastactref) eq 'HASH') {
13919:                 $lastactref->{'ltitools'} = 1;
13920:             }
13921:             $resulttext = &mt('Changes made:').'<ul>';
13922:             my %bynum;
13923:             foreach my $itemid (sort(keys(%changes))) {
13924:                 my $position = $confhash{$itemid}{'order'};
13925:                 $bynum{$position} = $itemid;
13926:             }
13927:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13928:                 my $itemid = $bynum{$pos}; 
13929:                 if (ref($confhash{$itemid}) ne 'HASH') {
13930:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13931:                 } else {
13932:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
13933:                     if ($confhash{$itemid}{'image'}) {
13934:                         $resulttext .= '&nbsp;'.
13935:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
13936:                                        ' alt="'.&mt('Tool Provider icon').'" />';
13937:                     }
13938:                     $resulttext .= '</li><ul>';
13939:                     my $position = $pos + 1;
13940:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13941:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
13942:                         if ($confhash{$itemid}{$item} ne '') {
13943:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
13944:                         }
13945:                     }
13946:                     if ($encconfig{$itemid}{'key'} ne '') {
13947:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
13948:                     }
13949:                     if ($encconfig{$itemid}{'secret'} ne '') {
13950:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
13951:                         my $num = length($encconfig{$itemid}{'secret'});
13952:                         $resulttext .= ('*'x$num).'</li>';
13953:                     }
13954:                     $resulttext .= '<li>'.&mt('Configurable in course:');
13955:                     my @possconfig = ('label','title','target','linktext','explanation','append');
13956:                     my $numconfig = 0; 
13957:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
13958:                         foreach my $item (@possconfig) {
13959:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
13960:                                 $numconfig ++;
13961:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
13962:                             }
13963:                         }
13964:                     }
13965:                     if (!$numconfig) {
13966:                         $resulttext .= '&nbsp;'.&mt('None');
13967:                     }
13968:                     $resulttext .= '</li>';
13969:                     foreach my $item ('passback','roster') {
13970:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
13971:                         if ($confhash{$itemid}{$item}) {
13972:                             $resulttext .= &mt('Yes');
13973:                             if ($confhash{$itemid}{$item.'valid'}) {
13974:                                 if ($item eq 'passback') {
13975:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
13976:                                                            $confhash{$itemid}{$item.'valid'});
13977:                                 } else {
13978:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
13979:                                                            $confhash{$itemid}{$item.'valid'});
13980:                                 }
13981:                             }
13982:                         } else {
13983:                             $resulttext .= &mt('No');
13984:                         }
13985:                         $resulttext .= '</li>';
13986:                     }
13987:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
13988:                         my $displaylist;
13989:                         if ($confhash{$itemid}{'display'}{'target'}) {
13990:                             $displaylist = &mt('Display target').':&nbsp;'.
13991:                                            $confhash{$itemid}{'display'}{'target'}.',';
13992:                         }
13993:                         foreach my $size ('width','height') { 
13994:                             if ($confhash{$itemid}{'display'}{$size}) {
13995:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
13996:                                                 $confhash{$itemid}{'display'}{$size}.',';
13997:                             }
13998:                         }
13999:                         if ($displaylist) {
14000:                             $displaylist =~ s/,$//;
14001:                             $resulttext .= '<li>'.$displaylist.'</li>';
14002:                         }
14003:                         foreach my $item ('linktext','explanation') {
14004:                             if ($confhash{$itemid}{'display'}{$item}) {
14005:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
14006:                             }
14007:                         }
14008:                     }
14009:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
14010:                         my $fieldlist;
14011:                         foreach my $field (@allfields) {
14012:                             if ($confhash{$itemid}{'fields'}{$field}) {
14013:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
14014:                             }
14015:                         }
14016:                         if ($fieldlist) {
14017:                             $fieldlist =~ s/,$//;
14018:                             if ($confhash{$itemid}{'fields'}{'user'}) {
14019:                                 if ($confhash{$itemid}{'incdom'}) {
14020:                                     $fieldlist .= ' ('.&mt('username:domain').')';
14021:                                 } else {
14022:                                     $fieldlist .= ' ('.&mt('username').')';
14023:                                 }
14024:                             }
14025:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
14026:                         }
14027:                     }
14028:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
14029:                         my $rolemaps;
14030:                         foreach my $role (@courseroles) {
14031:                             if ($confhash{$itemid}{'roles'}{$role}) {
14032:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
14033:                                              $confhash{$itemid}{'roles'}{$role}.',';
14034:                             }
14035:                         }
14036:                         if ($rolemaps) {
14037:                             $rolemaps =~ s/,$//; 
14038:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
14039:                         }
14040:                     }
14041:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
14042:                         my $customlist;
14043:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
14044:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
14045:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
14046:                             } 
14047:                         }
14048:                         if ($customlist) {
14049:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
14050:                         }
14051:                     } 
14052:                     $resulttext .= '</ul></li>';
14053:                 }
14054:             }
14055:             $resulttext .= '</ul>';
14056:         } else {
14057:             $resulttext = &mt('No changes made.');
14058:         }
14059:     } else {
14060:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14061:     }
14062:     if ($errors) {
14063:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14064:                        $errors.'</ul>';
14065:     }
14066:     return $resulttext;
14067: }
14068: 
14069: sub process_ltitools_image {
14070:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
14071:     my $filename = $env{'form.'.$caller.'.filename'};
14072:     my ($error,$url);
14073:     my ($width,$height) = (21,21);
14074:     if ($configuserok eq 'ok') {
14075:         if ($switchserver) {
14076:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
14077:                          $switchserver);
14078:         } elsif ($author_ok eq 'ok') {
14079:             my ($result,$imageurl,$madethumb) =
14080:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14081:                              "ltitools/$itemid/icon",$width,$height);
14082:             if ($result eq 'ok') {
14083:                 if ($madethumb) {
14084:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
14085:                     my $imagethumb = "$path/tn-".$imagefile;
14086:                     $url = $imagethumb;
14087:                 } else {
14088:                     $url = $imageurl;
14089:                 }
14090:             } else {
14091:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14092:             }
14093:         } else {
14094:             $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);
14095:         }
14096:     } else {
14097:         $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);
14098:     }
14099:     return ($url,$error);
14100: }
14101: 
14102: sub get_ltitools_id {
14103:     my ($cdom,$title) = @_;
14104:     # get lock on ltitools db
14105:     my $lockhash = {
14106:                       lock => $env{'user.name'}.
14107:                               ':'.$env{'user.domain'},
14108:                    };
14109:     my $tries = 0;
14110:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
14111:     my ($id,$error);
14112:  
14113:     while (($gotlock ne 'ok') && ($tries<10)) {
14114:         $tries ++;
14115:         sleep (0.1);
14116:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
14117:     }
14118:     if ($gotlock eq 'ok') {
14119:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
14120:         if ($currids{'lock'}) {
14121:             delete($currids{'lock'});
14122:             if (keys(%currids)) {
14123:                 my @curr = sort { $a <=> $b } keys(%currids);
14124:                 if ($curr[-1] =~ /^\d+$/) {
14125:                     $id = 1 + $curr[-1];
14126:                 }
14127:             } else {
14128:                 $id = 1;
14129:             }
14130:             if ($id) {
14131:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
14132:                     $error = 'nostore';
14133:                 }
14134:             } else {
14135:                 $error = 'nonumber';
14136:             }
14137:         }
14138:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
14139:     } else {
14140:         $error = 'nolock';
14141:     }
14142:     return ($id,$error);
14143: }
14144: 
14145: sub modify_proctoring {
14146:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14147:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14148:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
14149:     my $confname = $dom.'-domainconfig';
14150:     my $servadm = $r->dir_config('lonAdmEMail');
14151:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14152:     my %providernames = &proctoring_providernames();
14153:     my $maxnum = scalar(keys(%providernames));
14154: 
14155:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
14156:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
14157:     if (ref($requref) eq 'HASH') {
14158:         %requserfields = %{$requref};
14159:     }
14160:     if (ref($opturef) eq 'HASH') {
14161:         %optuserfields = %{$opturef};
14162:     }
14163:     if (ref($defref) eq 'HASH') {
14164:         %defaults = %{$defref};
14165:     }
14166:     if (ref($extref) eq 'HASH') {
14167:         %extended = %{$extref};
14168:     }
14169:     if (ref($crsref) eq 'HASH') {
14170:         %crsconf = %{$crsref};
14171:     }
14172:     if (ref($rolesref) eq 'ARRAY') {
14173:         @courseroles = @{$rolesref};
14174:     }
14175:     if (ref($ltiref) eq 'ARRAY') {
14176:         @ltiroles = @{$ltiref};
14177:     }
14178: 
14179:     if (ref($domconfig{$action}) eq 'HASH') {
14180:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
14181:         if (@todeleteimages) {
14182:             map { $imgdeletions{$_} = 1; } @todeleteimages;
14183:         }
14184:     }
14185:     my %customadds;
14186:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
14187:     if (@newcustom) {
14188:         map { $customadds{$_} = 1; } @newcustom;
14189:     }
14190:     foreach my $provider (sort(keys(%providernames))) {
14191:         $confhash{$provider} = {};
14192:         my $pos = $env{'form.proctoring_pos_'.$provider};
14193:         $pos =~ s/\D+//g;
14194:         $allpos[$pos] = $provider;
14195:         my (%current,%currentenc);
14196:         my $showroles = 0;
14197:         if (ref($domconfig{$action}) eq 'HASH') {
14198:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
14199:                 %current = %{$domconfig{$action}{$provider}};
14200:                 foreach my $item ('key','secret') { 
14201:                     $currentenc{$item} = $current{$item};
14202:                     delete($current{$item});
14203:                 }
14204:             }
14205:         }
14206:         if ($env{'form.proctoring_available_'.$provider}) {
14207:             $confhash{$provider}{'available'} = 1;
14208:             unless ($current{'available'}) {
14209:                 $changes{$provider} = 1;
14210:             }
14211:         } else {
14212:             %{$confhash{$provider}} = %current;
14213:             %{$encconfhash{$provider}} = %currentenc;
14214:             $confhash{$provider}{'available'} = 0;
14215:             if ($current{'available'}) {
14216:                 $changes{$provider} = 1;
14217:             }
14218:         }
14219:         if ($confhash{$provider}{'available'}) {
14220:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
14221:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
14222:                 if ($field eq 'lifetime') {
14223:                     if ($possval =~ /^\d+$/) {
14224:                         $confhash{$provider}{$field} = $possval;
14225:                     }
14226:                 } elsif ($field eq 'version') {
14227:                     if ($possval =~ /^\d+\.\d+$/) {
14228:                         $confhash{$provider}{$field} = $possval;
14229:                     }
14230:                 } elsif ($field eq 'sigmethod') {
14231:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
14232:                         $confhash{$provider}{$field} = $possval;
14233:                     }
14234:                 } elsif ($field eq 'url') {
14235:                     $confhash{$provider}{$field} = $possval;
14236:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
14237:                     $encconfhash{$provider}{$field} = $possval;
14238:                     unless ($currentenc{$field} eq $possval) {
14239:                         $changes{$provider} = 1;
14240:                     }
14241:                 }
14242:                 unless (($field eq 'key') || ($field eq 'secret')) {
14243:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
14244:                         $changes{$provider} = 1;
14245:                     }
14246:                 }
14247:             }
14248:             if ($imgdeletions{$provider}) {
14249:                 $changes{$provider} = 1;
14250:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
14251:                 my ($imageurl,$error) =
14252:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
14253:                                               $configuserok,$switchserver,$author_ok);
14254:                 if ($imageurl) {
14255:                     $confhash{$provider}{'image'} = $imageurl;
14256:                     $changes{$provider} = 1; 
14257:                 }
14258:                 if ($error) {
14259:                     &Apache::lonnet::logthis($error);
14260:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14261:                 }
14262:             } elsif (exists($current{'image'})) {
14263:                 $confhash{$provider}{'image'} = $current{'image'};
14264:             }
14265:             if (ref($requserfields{$provider}) eq 'ARRAY') {
14266:                 if (@{$requserfields{$provider}} > 0) {
14267:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
14268:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
14269:                             $confhash{$provider}{'incdom'} = 1;
14270:                         }
14271:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
14272:                             $changes{$provider} = 1;
14273:                         }
14274:                     }
14275:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
14276:                         $showroles = 1;
14277:                     }
14278:                 }
14279:             }
14280:             $confhash{$provider}{'fields'} = [];
14281:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
14282:                 if (@{$optuserfields{$provider}} > 0) {
14283:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
14284:                     foreach my $field (@{$optuserfields{$provider}}) {
14285:                         if (grep(/^\Q$field\E$/,@optfields)) {
14286:                             push(@{$confhash{$provider}{'fields'}},$field);
14287:                         }
14288:                     }
14289:                 }
14290:                 if (ref($current{'fields'}) eq 'ARRAY') {
14291:                     unless ($changes{$provider}) {
14292:                         my @new = sort(@{$confhash{$provider}{'fields'}});
14293:                         my @old = sort(@{$current{'fields'}}); 
14294:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14295:                         if (@diffs) {
14296:                             $changes{$provider} = 1;
14297:                         }
14298:                     }
14299:                 } elsif (@{$confhash{$provider}{'fields'}}) {
14300:                     $changes{$provider} = 1;
14301:                 }
14302:             }
14303:             if (ref($defaults{$provider}) eq 'ARRAY') {  
14304:                 if (@{$defaults{$provider}} > 0) {
14305:                     my %options;
14306:                     if (ref($extended{$provider}) eq 'HASH') {
14307:                         %options = %{$extended{$provider}};
14308:                     }
14309:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
14310:                     foreach my $field (@{$defaults{$provider}}) {
14311:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
14312:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
14313:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
14314:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
14315:                             }
14316:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
14317:                             foreach my $inner (keys(%{$options{$field}})) {
14318:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
14319:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
14320:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
14321:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
14322:                                     }
14323:                                 } else {
14324:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
14325:                                 }
14326:                             }
14327:                         } else {
14328:                             if (grep(/^\Q$field\E$/,@checked)) {
14329:                                 push(@{$confhash{$provider}{'defaults'}},$field);
14330:                             }
14331:                         }
14332:                     }
14333:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
14334:                         if (ref($current{'defaults'}) eq 'ARRAY') {
14335:                             unless ($changes{$provider}) {
14336:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
14337:                                 my @old = sort(@{$current{'defaults'}});
14338:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14339:                                 if (@diffs) {
14340:                                     $changes{$provider} = 1; 
14341:                                 }
14342:                             }
14343:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
14344:                             if (@{$current{'defaults'}}) {
14345:                                 $changes{$provider} = 1;
14346:                             }
14347:                         }
14348:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
14349:                         if (ref($current{'defaults'}) eq 'HASH') {
14350:                             unless ($changes{$provider}) {
14351:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
14352:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
14353:                                         $changes{$provider} = 1;
14354:                                         last;
14355:                                     }
14356:                                 }
14357:                             }
14358:                             unless ($changes{$provider}) {
14359:                                 foreach my $key (keys(%{$current{'defaults'}})) {
14360:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
14361:                                         $changes{$provider} = 1;
14362:                                         last;
14363:                                     }
14364:                                 }
14365:                             }
14366:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
14367:                             $changes{$provider} = 1;
14368:                         }
14369:                     }
14370:                 }
14371:             }
14372:             if (ref($crsconf{$provider}) eq 'ARRAY') {
14373:                 if (@{$crsconf{$provider}} > 0) {
14374:                     $confhash{$provider}{'crsconf'} = [];
14375:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
14376:                     foreach my $crsfield (@{$crsconf{$provider}}) {
14377:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
14378:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
14379:                         }
14380:                     }
14381:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
14382:                         unless ($changes{$provider}) {  
14383:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
14384:                             my @old = sort(@{$current{'crsconf'}});
14385:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14386:                             if (@diffs) {
14387:                                 $changes{$provider} = 1;
14388:                             }
14389:                         }
14390:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
14391:                         $changes{$provider} = 1;
14392:                     }
14393:                 }
14394:             }
14395:             if ($showroles) {
14396:                 $confhash{$provider}{'roles'} = {};
14397:                 foreach my $role (@courseroles) {
14398:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
14399:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
14400:                         $confhash{$provider}{'roles'}{$role} = $poss;
14401:                     }
14402:                 }
14403:                 unless ($changes{$provider}) {
14404:                     if (ref($current{'roles'}) eq 'HASH') {
14405:                         foreach my $role (keys(%{$current{'roles'}})) {
14406:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
14407:                                 $changes{$provider} = 1;
14408:                                 last
14409:                             }
14410:                         }
14411:                         unless ($changes{$provider}) {
14412:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
14413:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
14414:                                     $changes{$provider} = 1;
14415:                                     last;
14416:                                 }
14417:                             }
14418:                         }
14419:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
14420:                         $changes{$provider} = 1;
14421:                     }
14422:                 }
14423:             }
14424:             if (ref($current{'custom'}) eq 'HASH') {
14425:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
14426:                 foreach my $key (keys(%{$current{'custom'}})) {
14427:                     if (grep(/^\Q$key\E$/,@customdels)) {
14428:                         $changes{$provider} = 1;
14429:                     } else {
14430:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
14431:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
14432:                             $changes{$provider} = 1;
14433:                         }
14434:                     }
14435:                 }
14436:             }
14437:             if ($customadds{$provider}) {
14438:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
14439:                 $name =~ s/(`)/'/g;
14440:                 $name =~ s/^\s+//;
14441:                 $name =~ s/\s+$//;
14442:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
14443:                 $value =~ s/(`)/'/g;
14444:                 $value =~ s/^\s+//;
14445:                 $value =~ s/\s+$//;
14446:                 if ($name ne '') {
14447:                     $confhash{$provider}{'custom'}{$name} = $value;
14448:                     $changes{$provider} = 1;
14449:                 }
14450:             }
14451:         }
14452:     }
14453:     if (@allpos > 0) {
14454:         my $idx = 0;
14455:         foreach my $provider (@allpos) {
14456:             if ($provider ne '') {
14457:                 $confhash{$provider}{'order'} = $idx;
14458:                 unless ($changes{$provider}) {
14459:                     if (ref($domconfig{$action}) eq 'HASH') {
14460:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
14461:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
14462:                                 $changes{$provider} = 1;
14463:                             }
14464:                         }
14465:                     }
14466:                 }
14467:                 $idx ++;
14468:             }
14469:         }
14470:     }
14471:     my %proc_hash = (
14472:                           $action => { %confhash }
14473:                        );
14474:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
14475:                                              $dom);
14476:     if ($putresult eq 'ok') {
14477:         my %proc_enchash = (
14478:                              $action => { %encconfhash }
14479:                          );
14480:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom,undef,1);
14481:         if (keys(%changes) > 0) {
14482:             my $cachetime = 24*60*60;
14483:             my %procall = %confhash;
14484:             foreach my $provider (keys(%procall)) {
14485:                 if (ref($encconfhash{$provider}) eq 'HASH') {
14486:                     foreach my $key ('key','secret') {
14487:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
14488:                     }
14489:                 }
14490:             }
14491:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
14492:             if (ref($lastactref) eq 'HASH') {
14493:                 $lastactref->{'proctoring'} = 1;
14494:             }
14495:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
14496:             my %bynum;
14497:             foreach my $provider (sort(keys(%changes))) {
14498:                 my $position = $confhash{$provider}{'order'};
14499:                 $bynum{$position} = $provider;
14500:             }
14501:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
14502:                 my $provider = $bynum{$pos};
14503:                 my %lt = &proctoring_titles($provider);
14504:                 my %fieldtitles = &proctoring_fieldtitles($provider);
14505:                 if (!$confhash{$provider}{'available'}) {
14506:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
14507:                 } else {
14508:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
14509:                     if ($confhash{$provider}{'image'}) {
14510:                         $resulttext .= '&nbsp;'.
14511:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
14512:                                        ' alt="'.&mt('Proctoring icon').'" />';
14513:                     }
14514:                     $resulttext .= '<ul>';
14515:                     my $position = $pos + 1;
14516:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
14517:                     foreach my $key ('version','sigmethod','url','lifetime') {
14518:                         if ($confhash{$provider}{$key} ne '') {
14519:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
14520:                         }
14521:                     }
14522:                     if ($encconfhash{$provider}{'key'} ne '') {
14523:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
14524:                     }
14525:                     if ($encconfhash{$provider}{'secret'} ne '') {
14526:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
14527:                         my $num = length($encconfhash{$provider}{'secret'});
14528:                         $resulttext .= ('*'x$num).'</li>';
14529:                     }
14530:                     my (@fields,$showroles);
14531:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14532:                         push(@fields,@{$requserfields{$provider}});
14533:                     }
14534:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
14535:                         push(@fields,@{$confhash{$provider}{'fields'}});
14536:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
14537:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
14538:                     }
14539:                     if (@fields) {
14540:                         if (grep(/^roles$/,@fields)) {
14541:                             $showroles = 1;
14542:                         }
14543:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
14544:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
14545:                     }
14546:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14547:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
14548:                             if ($confhash{$provider}{'incdom'}) {
14549:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
14550:                             } else { 
14551:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
14552:                             }
14553:                         }
14554:                     }
14555:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
14556:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
14557:                             $resulttext .= '<li>'.$lt{'defa'};
14558:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
14559:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
14560:                             }
14561:                             $resulttext =~ s/,$//;
14562:                             $resulttext .= '</li>';
14563:                         }
14564:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
14565:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
14566:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
14567:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
14568:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
14569:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
14570:                                 }
14571:                             }
14572:                             $resulttext .= '</ul></li>';
14573:                         }
14574:                     }
14575:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
14576:                         if (@{$crsconf{$provider}} > 0) {
14577:                             $resulttext .= '<li>'.&mt('Configurable in course:');
14578:                             my $numconfig = 0;
14579:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
14580:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
14581:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
14582:                                         $numconfig ++;
14583:                                         if ($provider eq 'examity') {
14584:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
14585:                                         } else {
14586:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
14587:                                         }
14588:                                     }
14589:                                     $resulttext =~ s/,$//;
14590:                                 }
14591:                             }
14592:                             if (!$numconfig) {
14593:                                 $resulttext .= '&nbsp;'.&mt('None');
14594:                             }
14595:                             $resulttext .= '</li>';
14596:                         }
14597:                     }
14598:                     if ($showroles) {
14599:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
14600:                             my $rolemaps;
14601:                             foreach my $role (@courseroles) {
14602:                                 if ($confhash{$provider}{'roles'}{$role}) {
14603:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
14604:                                                  $confhash{$provider}{'roles'}{$role}.',';
14605:                                 }
14606:                             }
14607:                             if ($rolemaps) {
14608:                                 $rolemaps =~ s/,$//;
14609:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
14610:                             }
14611:                         }
14612:                     }
14613:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
14614:                         my $customlist;
14615:                         if (keys(%{$confhash{$provider}{'custom'}})) {
14616:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
14617:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
14618:                             }
14619:                             $customlist =~ s/,$//;
14620:                         }
14621:                         if ($customlist) {
14622:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
14623:                         }
14624:                     } 
14625:                     $resulttext .= '</ul></li>';
14626:                 }
14627:             }
14628:             $resulttext .= '</ul>';
14629:         } else {
14630:             $resulttext = &mt('No changes made.');
14631:         }
14632:     } else {
14633:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14634:     }
14635:     if ($errors) {
14636:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14637:                        $errors.'</ul>';
14638:     }
14639:     return $resulttext;
14640: }
14641: 
14642: sub process_proctoring_image {
14643:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
14644:     my $filename = $env{'form.'.$caller.'.filename'};
14645:     my ($error,$url);
14646:     my ($width,$height) = (21,21);
14647:     if ($configuserok eq 'ok') {
14648:         if ($switchserver) {
14649:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
14650:                          $switchserver);
14651:         } elsif ($author_ok eq 'ok') {
14652:             my ($result,$imageurl,$madethumb) =
14653:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14654:                              "proctoring/$provider/icon",$width,$height);
14655:             if ($result eq 'ok') {
14656:                 if ($madethumb) {
14657:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
14658:                     my $imagethumb = "$path/tn-".$imagefile;
14659:                     $url = $imagethumb;
14660:                 } else {
14661:                     $url = $imageurl;
14662:                 }
14663:             } else {
14664:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14665:             }
14666:         } else {
14667:             $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);
14668:         }
14669:     } else {
14670:         $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);
14671:     }
14672:     return ($url,$error);
14673: }
14674: 
14675: sub modify_lti {
14676:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14677:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14678:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14679:     my (%posslti,%posslticrs,%posscrstype);
14680:     my @courseroles = ('cc','in','ta','ep','st');
14681:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
14682:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
14683:     my @coursetypes = ('official','unofficial','community','textbook','placement');
14684:     my %coursetypetitles = &Apache::lonlocal::texthash (
14685:                                official   => 'Official',
14686:                                unofficial => 'Unofficial',
14687:                                community  => 'Community',
14688:                                textbook   => 'Textbook',
14689:                                placement  => 'Placement Test',
14690:     );
14691:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14692:     my %lt = &lti_names();
14693:     map { $posslti{$_} = 1; } @ltiroles;
14694:     map { $posslticrs{$_} = 1; } @lticourseroles;
14695:     map { $posscrstype{$_} = 1; } @coursetypes;
14696: 
14697:     my %menutitles = &ltimenu_titles();
14698: 
14699:     my (@items,%deletions,%itemids);
14700:     if ($env{'form.lti_add'}) {
14701:         my $consumer = $env{'form.lti_consumer_add'};
14702:         $consumer =~ s/(`)/'/g;
14703:         ($newid,my $error) = &get_lti_id($dom,$consumer);
14704:         if ($newid) {
14705:             $itemids{'add'} = $newid;
14706:             push(@items,'add');
14707:             $changes{$newid} = 1;
14708:         } else {
14709:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
14710:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14711:         }
14712:     }
14713:     if (ref($domconfig{$action}) eq 'HASH') {
14714:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
14715:         if (@todelete) {
14716:             map { $deletions{$_} = 1; } @todelete;
14717:         }
14718:         my $maxnum = $env{'form.lti_maxnum'};
14719:         for (my $i=0; $i<=$maxnum; $i++) {
14720:             my $itemid = $env{'form.lti_id_'.$i};
14721:             $itemid =~ s/\D+//g;
14722:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14723:                 if ($deletions{$itemid}) {
14724:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
14725:                 } else {
14726:                    push(@items,$i);
14727:                    $itemids{$i} = $itemid;
14728:                 }
14729:             }
14730:         }
14731:     }
14732:     foreach my $idx (@items) {
14733:         my $itemid = $itemids{$idx};
14734:         next unless ($itemid);
14735:         my $position = $env{'form.lti_pos_'.$idx};
14736:         $position =~ s/\D+//g;
14737:         if ($position ne '') {
14738:             $allpos[$position] = $itemid;
14739:         }
14740:         foreach my $item ('consumer','key','secret','lifetime','requser') {
14741:             my $formitem = 'form.lti_'.$item.'_'.$idx;
14742:             $env{$formitem} =~ s/(`)/'/g;
14743:             if ($item eq 'lifetime') {
14744:                 $env{$formitem} =~ s/[^\d.]//g;
14745:             }
14746:             if ($env{$formitem} ne '') {
14747:                 if (($item eq 'key') || ($item eq 'secret')) {
14748:                     $encconfig{$itemid}{$item} = $env{$formitem};
14749:                 } else {
14750:                     $confhash{$itemid}{$item} = $env{$formitem};
14751:                     unless (($idx eq 'add') || ($changes{$itemid})) {
14752:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14753:                             $changes{$itemid} = 1;
14754:                         }
14755:                     }
14756:                 }
14757:             }
14758:         }
14759:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
14760:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
14761:         }
14762:         if ($confhash{$itemid}{'requser'}) {
14763:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
14764:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid'; 
14765:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
14766:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
14767:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
14768:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
14769:                 $mapuser =~ s/(`)/'/g;
14770:                 $mapuser =~ s/^\s+|\s+$//g; 
14771:                 $confhash{$itemid}{'mapuser'} = $mapuser; 
14772:             }
14773:             foreach my $ltirole (@lticourseroles) {
14774:                 my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
14775:                 if (grep(/^\Q$possrole\E$/,@courseroles)) {
14776:                     $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
14777:                 }
14778:             }
14779:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
14780:             my @makeuser;
14781:             foreach my $ltirole (sort(@possmakeuser)) {
14782:                 if ($posslti{$ltirole}) {
14783:                     push(@makeuser,$ltirole);
14784:                 }
14785:             }
14786:             $confhash{$itemid}{'makeuser'} = \@makeuser;
14787:             if (@makeuser) {
14788:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
14789:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
14790:                     $confhash{$itemid}{'lcauth'} = $lcauth;
14791:                     if ($lcauth ne 'internal') {
14792:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
14793:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
14794:                         $lcauthparm =~ s/`//g;
14795:                         if ($lcauthparm ne '') {
14796:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
14797:                         }
14798:                     }
14799:                 } else {
14800:                     $confhash{$itemid}{'lcauth'} = 'lti';
14801:                 }
14802:             }
14803:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
14804:             if (@possinstdata) {
14805:                 foreach my $field (@possinstdata) {
14806:                     if (exists($fieldtitles{$field})) {
14807:                         push(@{$confhash{$itemid}{'instdata'}});
14808:                     }
14809:                 }
14810:             }
14811:             if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
14812:                 ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
14813:                 $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
14814:             } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
14815:                 my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
14816:                 $mapcrs =~ s/(`)/'/g;
14817:                 $mapcrs =~ s/^\s+|\s+$//g;
14818:                 $confhash{$itemid}{'mapcrs'} = $mapcrs;
14819:             }
14820:             my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
14821:             my @crstypes;
14822:             foreach my $type (sort(@posstypes)) {
14823:                 if ($posscrstype{$type}) {
14824:                     push(@crstypes,$type);
14825:                 }
14826:             }
14827:             $confhash{$itemid}{'mapcrstype'} = \@crstypes;
14828:             if ($env{'form.lti_makecrs_'.$idx}) {
14829:                 $confhash{$itemid}{'makecrs'} = 1;
14830:             }
14831:             my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
14832:             my @selfenroll;
14833:             foreach my $type (sort(@possenroll)) {
14834:                 if ($posslticrs{$type}) {
14835:                     push(@selfenroll,$type);
14836:                 }
14837:             }
14838:             $confhash{$itemid}{'selfenroll'} = \@selfenroll;
14839:             if ($env{'form.lti_crssec_'.$idx}) {
14840:                 if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
14841:                     $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
14842:                 } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
14843:                     my $section = $env{'form.lti_customsection_'.$idx};
14844:                     $section =~ s/(`)/'/g;
14845:                     $section =~ s/^\s+|\s+$//g;
14846:                     if ($section ne '') {
14847:                         $confhash{$itemid}{'section'} = $section;
14848:                     }
14849:                 }
14850:             }
14851:             if ($env{'form.lti_callback_'.$idx}) {
14852:                 if ($env{'form.lti_callbackparam_'.$idx}) {
14853:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
14854:                     $callback =~ s/^\s+|\s+$//g;
14855:                     $confhash{$itemid}{'callback'} = $callback;
14856:                 }
14857:             }
14858:             foreach my $field ('passback','roster','topmenu','inlinemenu') {
14859:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
14860:                     $confhash{$itemid}{$field} = 1;
14861:                 }
14862:             }
14863:             if ($env{'form.lti_passback_'.$idx}) {
14864:                 if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
14865:                     $confhash{$itemid}{'passbackformat'} = '1.0';
14866:                 } else {
14867:                     $confhash{$itemid}{'passbackformat'} = '1.1';
14868:                 }
14869:             }
14870:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
14871:                 $confhash{$itemid}{lcmenu} = [];
14872:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
14873:                 foreach my $field (@possmenu) {
14874:                     if (exists($menutitles{$field})) {
14875:                         if ($field eq 'grades') {
14876:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
14877:                         }
14878:                         push(@{$confhash{$itemid}{lcmenu}},$field);
14879:                     }
14880:                 }
14881:             }
14882:             unless (($idx eq 'add') || ($changes{$itemid})) {
14883:                 foreach my $field ('mapuser','mapcrs','makecrs','section','passback','roster','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
14884:                     if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
14885:                         $changes{$itemid} = 1;
14886:                     }
14887:                 }
14888:                 unless ($changes{$itemid}) {
14889:                     if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
14890:                         if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
14891:                             $changes{$itemid} = 1;
14892:                         }
14893:                     }
14894:                 }
14895:                 foreach my $field ('makeuser','mapcrstype','selfenroll','instdata','lcmenu') {
14896:                     unless ($changes{$itemid}) {
14897:                         if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
14898:                             if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
14899:                                 my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
14900:                                                                                $confhash{$itemid}{$field});
14901:                                 if (@diffs) {
14902:                                     $changes{$itemid} = 1;
14903:                                 }
14904:                             } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
14905:                                 $changes{$itemid} = 1;
14906:                             }
14907:                         } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
14908:                             if (@{$confhash{$itemid}{$field}} > 0) {
14909:                                 $changes{$itemid} = 1;
14910:                             }
14911:                         }
14912:                     }
14913:                 }
14914:                 unless ($changes{$itemid}) {
14915:                     if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
14916:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14917:                             foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
14918:                                 if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
14919:                                     $confhash{$itemid}{'maproles'}{$ltirole}) {
14920:                                     $changes{$itemid} = 1;
14921:                                     last;
14922:                                 }
14923:                             }
14924:                             unless ($changes{$itemid}) {
14925:                                 foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
14926:                                     if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
14927:                                         $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
14928:                                         $changes{$itemid} = 1;
14929:                                         last;
14930:                                     }
14931:                                 }
14932:                             }
14933:                         } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
14934:                             $changes{$itemid} = 1;
14935:                         }
14936:                     } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14937:                         unless ($changes{$itemid}) {
14938:                             if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
14939:                                 $changes{$itemid} = 1;
14940:                             }
14941:                         }
14942:                     }
14943:                 }
14944:             }
14945:         }
14946:     }
14947:     if (@allpos > 0) {
14948:         my $idx = 0;
14949:         foreach my $itemid (@allpos) {
14950:             if ($itemid ne '') {
14951:                 $confhash{$itemid}{'order'} = $idx;
14952:                 if (ref($domconfig{$action}) eq 'HASH') {
14953:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14954:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
14955:                             $changes{$itemid} = 1;
14956:                         }
14957:                     }
14958:                 }
14959:                 $idx ++;
14960:             }
14961:         }
14962:     }
14963:     my %ltihash = (
14964:                           $action => { %confhash }
14965:                        );
14966:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,
14967:                                              $dom);
14968:     if ($putresult eq 'ok') {
14969:         my %ltienchash = (
14970:                              $action => { %encconfig }
14971:                          );
14972:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
14973:         if (keys(%changes) > 0) {
14974:             my $cachetime = 24*60*60;
14975:             my %ltiall = %confhash;
14976:             foreach my $id (keys(%ltiall)) {
14977:                 if (ref($encconfig{$id}) eq 'HASH') {
14978:                     foreach my $item ('key','secret') {
14979:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
14980:                     }
14981:                 }
14982:             }
14983:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
14984:             if (ref($lastactref) eq 'HASH') {
14985:                 $lastactref->{'lti'} = 1;
14986:             }
14987:             $resulttext = &mt('Changes made:').'<ul>';
14988:             my %bynum;
14989:             foreach my $itemid (sort(keys(%changes))) {
14990:                 my $position = $confhash{$itemid}{'order'};
14991:                 $bynum{$position} = $itemid;
14992:             }
14993:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
14994:                 my $itemid = $bynum{$pos};
14995:                 if (ref($confhash{$itemid}) ne 'HASH') {
14996:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
14997:                 } else {
14998:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b></li><ul>';
14999:                     my $position = $pos + 1;
15000:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15001:                     foreach my $item ('version','lifetime') {
15002:                         if ($confhash{$itemid}{$item} ne '') {
15003:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
15004:                         }
15005:                     }
15006:                     if ($encconfig{$itemid}{'key'} ne '') {
15007:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
15008:                     }
15009:                     if ($encconfig{$itemid}{'secret'} ne '') {
15010:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15011:                         my $num = length($encconfig{$itemid}{'secret'});
15012:                         $resulttext .= ('*'x$num).'</li>';
15013:                     }
15014:                     if ($confhash{$itemid}{'requser'}) {
15015:                         if ($confhash{$itemid}{'mapuser'}) {
15016:                             my $shownmapuser;
15017:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
15018:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
15019:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
15020:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
15021:                             } else {
15022:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
15023:                             }
15024:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
15025:                         }
15026:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
15027:                             my $rolemaps;
15028:                             foreach my $role (@ltiroles) {
15029:                                 if ($confhash{$itemid}{'maproles'}{$role}) {
15030:                                     $rolemaps .= ('&nbsp;'x2).$role.'='.
15031:                                                  &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
15032:                                                                             'Course').',';
15033:                                 }
15034:                             }
15035:                             if ($rolemaps) {
15036:                                 $rolemaps =~ s/,$//;
15037:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15038:                             }
15039:                         }
15040:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
15041:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
15042:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
15043:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
15044:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
15045:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
15046:                                 } else {
15047:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
15048:                                                        $confhash{$itemid}{'lcauth'});
15049:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
15050:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
15051:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
15052:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
15053:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
15054:                                         }
15055:                                     } else {
15056:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
15057:                                     }
15058:                                 }
15059:                                 $resulttext .= '</li>';
15060:                             } else {
15061:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
15062:                             }
15063:                         }
15064:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
15065:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
15066:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
15067:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
15068:                             } else {
15069:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
15070:                             }
15071:                         }
15072:                         if ($confhash{$itemid}{'mapcrs'}) {
15073:                             $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
15074:                         }
15075:                         if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
15076:                             if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
15077:                                 $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
15078:                                                join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
15079:                                                '</li>';
15080:                             } else {
15081:                                 $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
15082:                             }
15083:                         }
15084:                         if ($confhash{$itemid}{'makecrs'}) {
15085:                             $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
15086:                         } else {
15087:                             $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
15088:                         }
15089:                         if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
15090:                             if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
15091:                                 $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
15092:                                                           join(', ',@{$confhash{$itemid}{'selfenroll'}})).
15093:                                                '</li>';
15094:                             } else {
15095:                                 $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
15096:                             }
15097:                         }
15098:                         if ($confhash{$itemid}{'section'}) {
15099:                             if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
15100:                                 $resulttext .= '<li>'.&mt('User section from standard field:').
15101:                                                      ' (course_section_sourcedid)'.'</li>';  
15102:                             } else {
15103:                                 $resulttext .= '<li>'.&mt('User section from:').' '.
15104:                                                       $confhash{$itemid}{'section'}.'</li>';
15105:                             }
15106:                         } else {
15107:                             $resulttext .= '<li>'.&mt('No section assignment').'</li>';
15108:                         }
15109:                         if ($confhash{$itemid}{'callback'}) {
15110:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
15111:                         } else {
15112:                             $resulttext .= '<li>'.&mt('No callback to logout LON-CAPA session when user logs out of Comsumer');
15113:                         }
15114:                         foreach my $item ('passback','roster','topmenu','inlinemenu') {
15115:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
15116:                             if ($confhash{$itemid}{$item}) {
15117:                                 $resulttext .= &mt('Yes');
15118:                                 if ($item eq 'passback') {
15119:                                     if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
15120:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
15121:                                     } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
15122:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
15123:                                     }
15124:                                 }
15125:                             } else {
15126:                                 $resulttext .= &mt('No');
15127:                             }
15128:                             $resulttext .= '</li>';
15129:                         }
15130:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
15131:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
15132:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
15133:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
15134:                             } else {
15135:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
15136:                             }
15137:                         }
15138:                     }
15139:                     $resulttext .= '</ul></li>';
15140:                 }
15141:             }
15142:             $resulttext .= '</ul>';
15143:         } else {
15144:             $resulttext = &mt('No changes made.');
15145:         }
15146:     } else {
15147:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15148:     }
15149:     if ($errors) {
15150:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15151:                        $errors.'</ul>';
15152:     }
15153:     return $resulttext;
15154: }
15155: 
15156: sub get_lti_id {
15157:     my ($domain,$consumer) = @_;
15158:     # get lock on lti db
15159:     my $lockhash = {
15160:                       lock => $env{'user.name'}.
15161:                               ':'.$env{'user.domain'},
15162:                    };
15163:     my $tries = 0;
15164:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
15165:     my ($id,$error);
15166: 
15167:     while (($gotlock ne 'ok') && ($tries<10)) {
15168:         $tries ++;
15169:         sleep (0.1);
15170:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
15171:     }
15172:     if ($gotlock eq 'ok') {
15173:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
15174:         if ($currids{'lock'}) {
15175:             delete($currids{'lock'});
15176:             if (keys(%currids)) {
15177:                 my @curr = sort { $a <=> $b } keys(%currids);
15178:                 if ($curr[-1] =~ /^\d+$/) {
15179:                     $id = 1 + $curr[-1];
15180:                 }
15181:             } else {
15182:                 $id = 1;
15183:             }
15184:             if ($id) {
15185:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
15186:                     $error = 'nostore';
15187:                 }
15188:             } else {
15189:                 $error = 'nonumber';
15190:             }
15191:         }
15192:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
15193:     } else {
15194:         $error = 'nolock';
15195:     }
15196:     return ($id,$error);
15197: }
15198: 
15199: sub modify_autoenroll {
15200:     my ($dom,$lastactref,%domconfig) = @_;
15201:     my ($resulttext,%changes);
15202:     my %currautoenroll;
15203:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
15204:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
15205:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
15206:         }
15207:     }
15208:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
15209:     my %title = ( run => 'Auto-enrollment active',
15210:                   sender => 'Sender for notification messages',
15211:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
15212:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
15213:     my @offon = ('off','on');
15214:     my $sender_uname = $env{'form.sender_uname'};
15215:     my $sender_domain = $env{'form.sender_domain'};
15216:     if ($sender_domain eq '') {
15217:         $sender_uname = '';
15218:     } elsif ($sender_uname eq '') {
15219:         $sender_domain = '';
15220:     }
15221:     my $coowners = $env{'form.autoassign_coowners'};
15222:     my $failsafe = $env{'form.autoenroll_failsafe'};
15223:     $failsafe =~ s{^\s+|\s+$}{}g;
15224:     if ($failsafe =~ /\D/) {
15225:         undef($failsafe);
15226:     }
15227:     my %autoenrollhash =  (
15228:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
15229:                                        'sender_uname' => $sender_uname,
15230:                                        'sender_domain' => $sender_domain,
15231:                                        'co-owners' => $coowners,
15232:                                        'autofailsafe' => $failsafe,
15233:                                 }
15234:                      );
15235:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
15236:                                              $dom);
15237:     if ($putresult eq 'ok') {
15238:         if (exists($currautoenroll{'run'})) {
15239:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
15240:                  $changes{'run'} = 1;
15241:              }
15242:         } elsif ($autorun) {
15243:             if ($env{'form.autoenroll_run'} ne '1') {
15244:                  $changes{'run'} = 1;
15245:             }
15246:         }
15247:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
15248:             $changes{'sender'} = 1;
15249:         }
15250:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
15251:             $changes{'sender'} = 1;
15252:         }
15253:         if ($currautoenroll{'co-owners'} ne '') {
15254:             if ($currautoenroll{'co-owners'} ne $coowners) {
15255:                 $changes{'coowners'} = 1;
15256:             }
15257:         } elsif ($coowners) {
15258:             $changes{'coowners'} = 1;
15259:         }
15260:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
15261:             $changes{'autofailsafe'} = 1;
15262:         }
15263:         if (keys(%changes) > 0) {
15264:             $resulttext = &mt('Changes made:').'<ul>';
15265:             if ($changes{'run'}) {
15266:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
15267:             }
15268:             if ($changes{'sender'}) {
15269:                 if ($sender_uname eq '' || $sender_domain eq '') {
15270:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
15271:                 } else {
15272:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
15273:                 }
15274:             }
15275:             if ($changes{'coowners'}) {
15276:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
15277:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
15278:                 if (ref($lastactref) eq 'HASH') {
15279:                     $lastactref->{'domainconfig'} = 1;
15280:                 }
15281:             }
15282:             if ($changes{'autofailsafe'}) {
15283:                 if ($failsafe ne '') {
15284:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';
15285:                 } else {
15286:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');
15287:                 }
15288:                 &Apache::lonnet::get_domain_defaults($dom,1);
15289:                 if (ref($lastactref) eq 'HASH') {
15290:                     $lastactref->{'domdefaults'} = 1;
15291:                 }
15292:             }
15293:             $resulttext .= '</ul>';
15294:         } else {
15295:             $resulttext = &mt('No changes made to auto-enrollment settings');
15296:         }
15297:     } else {
15298:         $resulttext = '<span class="LC_error">'.
15299: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
15300:     }
15301:     return $resulttext;
15302: }
15303: 
15304: sub modify_autoupdate {
15305:     my ($dom,%domconfig) = @_;
15306:     my ($resulttext,%currautoupdate,%fields,%changes);
15307:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
15308:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
15309:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
15310:         }
15311:     }
15312:     my @offon = ('off','on');
15313:     my %title = &Apache::lonlocal::texthash (
15314:                     run        => 'Auto-update:',
15315:                     classlists => 'Updates to user information in classlists?',
15316:                     unexpired  => 'Skip updates for users without active or future roles?',
15317:                     lastactive => 'Skip updates for inactive users?',
15318:                 );
15319:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15320:     my %fieldtitles = &Apache::lonlocal::texthash (
15321:                         id => 'Student/Employee ID',
15322:                         permanentemail => 'E-mail address',
15323:                         lastname => 'Last Name',
15324:                         firstname => 'First Name',
15325:                         middlename => 'Middle Name',
15326:                         generation => 'Generation',
15327:                       );
15328:     $othertitle = &mt('All users');
15329:     if (keys(%{$usertypes}) >  0) {
15330:         $othertitle = &mt('Other users');
15331:     }
15332:     foreach my $key (keys(%env)) {
15333:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
15334:             my ($usertype,$item) = ($1,$2);
15335:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
15336:                 if ($usertype eq 'default') {   
15337:                     push(@{$fields{$1}},$2);
15338:                 } elsif (ref($types) eq 'ARRAY') {
15339:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
15340:                         push(@{$fields{$1}},$2);
15341:                     }
15342:                 }
15343:             }
15344:         }
15345:     }
15346:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
15347:     @lockablenames = sort(@lockablenames);
15348:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
15349:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
15350:         if (@changed) {
15351:             $changes{'lockablenames'} = 1;
15352:         }
15353:     } else {
15354:         if (@lockablenames) {
15355:             $changes{'lockablenames'} = 1;
15356:         }
15357:     }
15358:     my %updatehash = (
15359:                       autoupdate => { run => $env{'form.autoupdate_run'},
15360:                                       classlists => $env{'form.classlists'},
15361:                                       unexpired  => $env{'form.unexpired'},
15362:                                       fields => {%fields},
15363:                                       lockablenames => \@lockablenames,
15364:                                     }
15365:                      );
15366:     my $lastactivedays;
15367:     if ($env{'form.lastactive'}) {
15368:         $lastactivedays = $env{'form.lastactivedays'};
15369:         $lastactivedays =~ s/^\s+|\s+$//g;
15370:         unless ($lastactivedays =~ /^\d+$/) {
15371:             undef($lastactivedays);
15372:             $env{'form.lastactive'} = 0;
15373:         }
15374:     }
15375:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
15376:     foreach my $key (keys(%currautoupdate)) {
15377:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
15378:             if (exists($updatehash{autoupdate}{$key})) {
15379:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
15380:                     $changes{$key} = 1;
15381:                 }
15382:             }
15383:         } elsif ($key eq 'fields') {
15384:             if (ref($currautoupdate{$key}) eq 'HASH') {
15385:                 foreach my $item (@{$types},'default') {
15386:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
15387:                         my $change = 0;
15388:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
15389:                             if (!exists($fields{$item})) {
15390:                                 $change = 1;
15391:                                 last;
15392:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
15393:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
15394:                                     $change = 1;
15395:                                     last;
15396:                                 }
15397:                             }
15398:                         }
15399:                         if ($change) {
15400:                             push(@{$changes{$key}},$item);
15401:                         }
15402:                     } 
15403:                 }
15404:             }
15405:         } elsif ($key eq 'lockablenames') {
15406:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
15407:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
15408:                 if (@changed) {
15409:                     $changes{'lockablenames'} = 1;
15410:                 }
15411:             } else {
15412:                 if (@lockablenames) {
15413:                     $changes{'lockablenames'} = 1;
15414:                 }
15415:             }
15416:         }
15417:     }
15418:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
15419:         if (@lockablenames) {
15420:             $changes{'lockablenames'} = 1;
15421:         }
15422:     }
15423:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
15424:         if ($updatehash{'autoupdate'}{'unexpired'}) {
15425:             $changes{'unexpired'} = 1;
15426:         }
15427:     }
15428:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
15429:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
15430:             $changes{'lastactive'} = 1;
15431:         }
15432:     }
15433:     foreach my $item (@{$types},'default') {
15434:         if (defined($fields{$item})) {
15435:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
15436:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
15437:                     my $change = 0;
15438:                     if (ref($fields{$item}) eq 'ARRAY') {
15439:                         foreach my $type (@{$fields{$item}}) {
15440:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
15441:                                 $change = 1;
15442:                                 last;
15443:                             }
15444:                         }
15445:                     }
15446:                     if ($change) {
15447:                         push(@{$changes{'fields'}},$item);
15448:                     }
15449:                 } else {
15450:                     push(@{$changes{'fields'}},$item);
15451:                 }
15452:             } else {
15453:                 push(@{$changes{'fields'}},$item);
15454:             }
15455:         }
15456:     }
15457:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
15458:                                              $dom);
15459:     if ($putresult eq 'ok') {
15460:         if (keys(%changes) > 0) {
15461:             $resulttext = &mt('Changes made:').'<ul>';
15462:             foreach my $key (sort(keys(%changes))) {
15463:                 if ($key eq 'lockablenames') {
15464:                     $resulttext .= '<li>';
15465:                     if (@lockablenames) {
15466:                         $usertypes->{'default'} = $othertitle;
15467:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
15468:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
15469:                     } else {
15470:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
15471:                     }
15472:                     $resulttext .= '</li>';
15473:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
15474:                     foreach my $item (@{$changes{$key}}) {
15475:                         my @newvalues;
15476:                         foreach my $type (@{$fields{$item}}) {
15477:                             push(@newvalues,$fieldtitles{$type});
15478:                         }
15479:                         my $newvaluestr;
15480:                         if (@newvalues > 0) {
15481:                             $newvaluestr = join(', ',@newvalues);
15482:                         } else {
15483:                             $newvaluestr = &mt('none');
15484:                         }
15485:                         if ($item eq 'default') {
15486:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
15487:                         } else {
15488:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
15489:                         }
15490:                     }
15491:                 } else {
15492:                     my $newvalue;
15493:                     if ($key eq 'run') {
15494:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
15495:                     } elsif ($key eq 'lastactive') {
15496:                         $newvalue = $offon[$env{'form.lastactive'}];
15497:                         unless ($lastactivedays eq '') {
15498:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
15499:                         }
15500:                     } else {
15501:                         $newvalue = $offon[$env{'form.'.$key}];
15502:                     }
15503:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
15504:                 }
15505:             }
15506:             $resulttext .= '</ul>';
15507:         } else {
15508:             $resulttext = &mt('No changes made to autoupdates');
15509:         }
15510:     } else {
15511:         $resulttext = '<span class="LC_error">'.
15512: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
15513:     }
15514:     return $resulttext;
15515: }
15516: 
15517: sub modify_autocreate {
15518:     my ($dom,%domconfig) = @_;
15519:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
15520:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
15521:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
15522:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
15523:         }
15524:     }
15525:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
15526:                  req => 'Auto-creation of validated requests for official courses',
15527:                  xmldc => 'Identity of course creator of courses from XML files',
15528:                );
15529:     my @types = ('xml','req');
15530:     foreach my $item (@types) {
15531:         $newvals{$item} = $env{'form.autocreate_'.$item};
15532:         $newvals{$item} =~ s/\D//g;
15533:         $newvals{$item} = 0 if ($newvals{$item} eq '');
15534:     }
15535:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
15536:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
15537:     unless (exists($domcoords{$newvals{'xmldc'}})) {
15538:         $newvals{'xmldc'} = '';
15539:     } 
15540:     %autocreatehash =  (
15541:                         autocreate => { xml => $newvals{'xml'},
15542:                                         req => $newvals{'req'},
15543:                                       }
15544:                        );
15545:     if ($newvals{'xmldc'} ne '') {
15546:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
15547:     }
15548:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
15549:                                              $dom);
15550:     if ($putresult eq 'ok') {
15551:         my @items = @types;
15552:         if ($newvals{'xml'}) {
15553:             push(@items,'xmldc');
15554:         }
15555:         foreach my $item (@items) {
15556:             if (exists($currautocreate{$item})) {
15557:                 if ($currautocreate{$item} ne $newvals{$item}) {
15558:                     $changes{$item} = 1;
15559:                 }
15560:             } elsif ($newvals{$item}) {
15561:                 $changes{$item} = 1;
15562:             }
15563:         }
15564:         if (keys(%changes) > 0) {
15565:             my @offon = ('off','on'); 
15566:             $resulttext = &mt('Changes made:').'<ul>';
15567:             foreach my $item (@types) {
15568:                 if ($changes{$item}) {
15569:                     my $newtxt = $offon[$newvals{$item}];
15570:                     $resulttext .= '<li>'.
15571:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
15572:                                        '<b>','</b>').
15573:                                    '</li>';
15574:                 }
15575:             }
15576:             if ($changes{'xmldc'}) {
15577:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
15578:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
15579:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
15580:             }
15581:             $resulttext .= '</ul>';
15582:         } else {
15583:             $resulttext = &mt('No changes made to auto-creation settings');
15584:         }
15585:     } else {
15586:         $resulttext = '<span class="LC_error">'.
15587:             &mt('An error occurred: [_1]',$putresult).'</span>';
15588:     }
15589:     return $resulttext;
15590: }
15591: 
15592: sub modify_directorysrch {
15593:     my ($dom,$lastactref,%domconfig) = @_;
15594:     my ($resulttext,%changes);
15595:     my %currdirsrch;
15596:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
15597:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
15598:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
15599:         }
15600:     }
15601:     my %title = ( available => 'Institutional directory search available',
15602:                   localonly => 'Other domains can search institution',
15603:                   lcavailable => 'LON-CAPA directory search available',
15604:                   lclocalonly => 'Other domains can search LON-CAPA domain',
15605:                   searchby => 'Search types',
15606:                   searchtypes => 'Search latitude');
15607:     my @offon = ('off','on');
15608:     my @otherdoms = ('Yes','No');
15609: 
15610:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
15611:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
15612:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
15613: 
15614:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15615:     if (keys(%{$usertypes}) == 0) {
15616:         @cansearch = ('default');
15617:     } else {
15618:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
15619:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
15620:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
15621:                     push(@{$changes{'cansearch'}},$type);
15622:                 }
15623:             }
15624:             foreach my $type (@cansearch) {
15625:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
15626:                     push(@{$changes{'cansearch'}},$type);
15627:                 }
15628:             }
15629:         } else {
15630:             push(@{$changes{'cansearch'}},@cansearch);
15631:         }
15632:     }
15633: 
15634:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
15635:         foreach my $by (@{$currdirsrch{'searchby'}}) {
15636:             if (!grep(/^\Q$by\E$/,@searchby)) {
15637:                 push(@{$changes{'searchby'}},$by);
15638:             }
15639:         }
15640:         foreach my $by (@searchby) {
15641:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
15642:                 push(@{$changes{'searchby'}},$by);
15643:             }
15644:         }
15645:     } else {
15646:         push(@{$changes{'searchby'}},@searchby);
15647:     }
15648: 
15649:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
15650:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
15651:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
15652:                 push(@{$changes{'searchtypes'}},$type);
15653:             }
15654:         }
15655:         foreach my $type (@searchtypes) {
15656:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
15657:                 push(@{$changes{'searchtypes'}},$type);
15658:             }
15659:         }
15660:     } else {
15661:         if (exists($currdirsrch{'searchtypes'})) {
15662:             foreach my $type (@searchtypes) {  
15663:                 if ($type ne $currdirsrch{'searchtypes'}) { 
15664:                     push(@{$changes{'searchtypes'}},$type);
15665:                 }
15666:             }
15667:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
15668:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
15669:             }   
15670:         } else {
15671:             push(@{$changes{'searchtypes'}},@searchtypes); 
15672:         }
15673:     }
15674: 
15675:     my %dirsrch_hash =  (
15676:             directorysrch => { available => $env{'form.dirsrch_available'},
15677:                                cansearch => \@cansearch,
15678:                                localonly => $env{'form.dirsrch_instlocalonly'},
15679:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
15680:                                lcavailable => $env{'form.dirsrch_domavailable'},
15681:                                searchby => \@searchby,
15682:                                searchtypes => \@searchtypes,
15683:                              }
15684:             );
15685:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
15686:                                              $dom);
15687:     if ($putresult eq 'ok') {
15688:         if (exists($currdirsrch{'available'})) {
15689:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
15690:                  $changes{'available'} = 1;
15691:              }
15692:         } else {
15693:             if ($env{'form.dirsrch_available'} eq '1') {
15694:                 $changes{'available'} = 1;
15695:             }
15696:         }
15697:         if (exists($currdirsrch{'lcavailable'})) {
15698:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
15699:                 $changes{'lcavailable'} = 1;
15700:             }
15701:         } else {
15702:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
15703:                 $changes{'lcavailable'} = 1;
15704:             }
15705:         }
15706:         if (exists($currdirsrch{'localonly'})) {
15707:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
15708:                 $changes{'localonly'} = 1;
15709:             }
15710:         } else {
15711:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
15712:                 $changes{'localonly'} = 1;
15713:             }
15714:         }
15715:         if (exists($currdirsrch{'lclocalonly'})) {
15716:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
15717:                 $changes{'lclocalonly'} = 1;
15718:             }
15719:         } else {
15720:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
15721:                 $changes{'lclocalonly'} = 1;
15722:             }
15723:         }
15724:         if (keys(%changes) > 0) {
15725:             $resulttext = &mt('Changes made:').'<ul>';
15726:             if ($changes{'available'}) {
15727:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
15728:             }
15729:             if ($changes{'lcavailable'}) {
15730:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
15731:             }
15732:             if ($changes{'localonly'}) {
15733:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
15734:             }
15735:             if ($changes{'lclocalonly'}) {
15736:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
15737:             }
15738:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
15739:                 my $chgtext;
15740:                 if (ref($usertypes) eq 'HASH') {
15741:                     if (keys(%{$usertypes}) > 0) {
15742:                         foreach my $type (@{$types}) {
15743:                             if (grep(/^\Q$type\E$/,@cansearch)) {
15744:                                 $chgtext .= $usertypes->{$type}.'; ';
15745:                             }
15746:                         }
15747:                         if (grep(/^default$/,@cansearch)) {
15748:                             $chgtext .= $othertitle;
15749:                         } else {
15750:                             $chgtext =~ s/\; $//;
15751:                         }
15752:                         $resulttext .=
15753:                             '<li>'.
15754:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
15755:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
15756:                             '</li>';
15757:                     }
15758:                 }
15759:             }
15760:             if (ref($changes{'searchby'}) eq 'ARRAY') {
15761:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
15762:                 my $chgtext;
15763:                 foreach my $type (@{$titleorder}) {
15764:                     if (grep(/^\Q$type\E$/,@searchby)) {
15765:                         if (defined($searchtitles->{$type})) {
15766:                             $chgtext .= $searchtitles->{$type}.'; ';
15767:                         }
15768:                     }
15769:                 }
15770:                 $chgtext =~ s/\; $//;
15771:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
15772:             }
15773:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
15774:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
15775:                 my $chgtext;
15776:                 foreach my $type (@{$srchtypeorder}) {
15777:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
15778:                         if (defined($srchtypes_desc->{$type})) {
15779:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
15780:                         }
15781:                     }
15782:                 }
15783:                 $chgtext =~ s/\; $//;
15784:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
15785:             }
15786:             $resulttext .= '</ul>';
15787:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
15788:             if (ref($lastactref) eq 'HASH') {
15789:                 $lastactref->{'directorysrch'} = 1;
15790:             }
15791:         } else {
15792:             $resulttext = &mt('No changes made to directory search settings');
15793:         }
15794:     } else {
15795:         $resulttext = '<span class="LC_error">'.
15796:                       &mt('An error occurred: [_1]',$putresult).'</span>';
15797:     }
15798:     return $resulttext;
15799: }
15800: 
15801: sub modify_contacts {
15802:     my ($dom,$lastactref,%domconfig) = @_;
15803:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
15804:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15805:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
15806:             $currsetting{$key} = $domconfig{'contacts'}{$key};
15807:         }
15808:     }
15809:     my (%others,%to,%bcc,%includestr,%includeloc);
15810:     my @contacts = ('supportemail','adminemail');
15811:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
15812:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
15813:     my @toggles = ('reporterrors','reportupdates','reportstatus');
15814:     my @lonstatus = ('threshold','sysmail','weights','excluded');
15815:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
15816:     foreach my $type (@mailings) {
15817:         @{$newsetting{$type}} = 
15818:             &Apache::loncommon::get_env_multiple('form.'.$type);
15819:         foreach my $item (@contacts) {
15820:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
15821:                 $contacts_hash{contacts}{$type}{$item} = 1;
15822:             } else {
15823:                 $contacts_hash{contacts}{$type}{$item} = 0;
15824:             }
15825:         }
15826:         $others{$type} = $env{'form.'.$type.'_others'};
15827:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
15828:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15829:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
15830:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
15831:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
15832:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
15833:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
15834:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
15835:             }
15836:         }
15837:     }
15838:     foreach my $item (@contacts) {
15839:         $to{$item} = $env{'form.'.$item};
15840:         $contacts_hash{'contacts'}{$item} = $to{$item};
15841:     }
15842:     foreach my $item (@toggles) {
15843:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
15844:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
15845:         }
15846:     }
15847:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
15848:     foreach my $item (@lonstatus) {
15849:         if ($item eq 'excluded') {
15850:             my (%serverhomes,@excluded);
15851:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
15852:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
15853:             if (@possexcluded) {
15854:                 foreach my $id (sort(@possexcluded)) {
15855:                     if ($serverhomes{$id}) {
15856:                         push(@excluded,$id);
15857:                     }
15858:                 }
15859:             }
15860:             if (@excluded) {
15861:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
15862:             }
15863:         } elsif ($item eq 'weights') {
15864:             foreach my $type ('E','W','N','U') {
15865:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
15866:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
15867:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
15868:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
15869:                             $env{'form.error'.$item.'_'.$type};
15870:                     }
15871:                 }
15872:             }
15873:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
15874:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
15875:             if ($env{'form.error'.$item} =~ /^\d+$/) {
15876:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
15877:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
15878:                 }
15879:             }
15880:         }
15881:     }
15882:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
15883:         foreach my $field (@{$fields}) {
15884:             if (ref($possoptions->{$field}) eq 'ARRAY') {
15885:                 my $value = $env{'form.helpform_'.$field};
15886:                 $value =~ s/^\s+|\s+$//g;
15887:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
15888:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
15889:                     if ($field eq 'screenshot') {
15890:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
15891:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
15892:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
15893:                         }
15894:                     }
15895:                 }
15896:             }
15897:         }
15898:     }
15899:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15900:     my (@statuses,%usertypeshash,@overrides);
15901:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
15902:         @statuses = @{$types};
15903:         if (ref($usertypes) eq 'HASH') {
15904:             %usertypeshash = %{$usertypes};
15905:         }
15906:     }
15907:     if (@statuses) {
15908:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
15909:         foreach my $type (@possoverrides) {
15910:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
15911:                 push(@overrides,$type);
15912:             }
15913:         }
15914:         if (@overrides) {
15915:             foreach my $type (@overrides) {
15916:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
15917:                 foreach my $item (@contacts) {
15918:                     if (grep(/^\Q$item\E$/,@standard)) {
15919:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
15920:                         $newsetting{'override_'.$type}{$item} = 1;
15921:                     } else {
15922:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
15923:                         $newsetting{'override_'.$type}{$item} = 0;
15924:                     }
15925:                 }
15926:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
15927:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
15928:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
15929:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
15930:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
15931:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
15932:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
15933:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
15934:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
15935:                 }
15936:             }     
15937:         }
15938:     }
15939:     if (keys(%currsetting) > 0) {
15940:         foreach my $item (@contacts) {
15941:             if ($to{$item} ne $currsetting{$item}) {
15942:                 $changes{$item} = 1;
15943:             }
15944:         }
15945:         foreach my $type (@mailings) {
15946:             foreach my $item (@contacts) {
15947:                 if (ref($currsetting{$type}) eq 'HASH') {
15948:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
15949:                         push(@{$changes{$type}},$item);
15950:                     }
15951:                 } else {
15952:                     push(@{$changes{$type}},@{$newsetting{$type}});
15953:                 }
15954:             }
15955:             if ($others{$type} ne $currsetting{$type}{'others'}) {
15956:                 push(@{$changes{$type}},'others');
15957:             }
15958:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15959:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
15960:                     push(@{$changes{$type}},'bcc'); 
15961:                 }
15962:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
15963:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
15964:                     push(@{$changes{$type}},'include');
15965:                 }
15966:             }
15967:         }
15968:         if (ref($fields) eq 'ARRAY') {
15969:             if (ref($currsetting{'helpform'}) eq 'HASH') {
15970:                 foreach my $field (@{$fields}) {
15971:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
15972:                         push(@{$changes{'helpform'}},$field);
15973:                     }
15974:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
15975:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
15976:                             push(@{$changes{'helpform'}},'maxsize');
15977:                         }
15978:                     }
15979:                 }
15980:             } else {
15981:                 foreach my $field (@{$fields}) {
15982:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
15983:                         push(@{$changes{'helpform'}},$field);
15984:                     }
15985:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
15986:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
15987:                             push(@{$changes{'helpform'}},'maxsize');
15988:                         }
15989:                     }
15990:                 }
15991:             }
15992:         }
15993:         if (@statuses) {
15994:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
15995:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
15996:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
15997:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
15998:                             foreach my $item (@contacts,'bcc','others','include') {
15999:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
16000:                                     push(@{$changes{'overrides'}},$key);
16001:                                     last;
16002:                                 }
16003:                             }
16004:                         } else {
16005:                             push(@{$changes{'overrides'}},$key);
16006:                         }
16007:                     }
16008:                 }
16009:                 foreach my $key (@overrides) {
16010:                     unless (exists($currsetting{'overrides'}{$key})) {
16011:                         push(@{$changes{'overrides'}},$key);
16012:                     }
16013:                 }
16014:             } else {
16015:                 foreach my $key (@overrides) {
16016:                     push(@{$changes{'overrides'}},$key); 
16017:                 }
16018:             }
16019:         }
16020:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
16021:             foreach my $key ('excluded','weights','threshold','sysmail') {
16022:                 if ($key eq 'excluded') {
16023:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
16024:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
16025:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
16026:                             (@{$currsetting{'lonstatus'}{$key}})) {
16027:                             my @diffs =
16028:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
16029:                                                                    $currsetting{'lonstatus'}{$key});
16030:                             if (@diffs) {
16031:                                 push(@{$changes{'lonstatus'}},$key);
16032:                             }
16033:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
16034:                             push(@{$changes{'lonstatus'}},$key);
16035:                         }
16036:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
16037:                              (@{$currsetting{'lonstatus'}{$key}})) {
16038:                         push(@{$changes{'lonstatus'}},$key);
16039:                     }
16040:                 } elsif ($key eq 'weights') {
16041:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
16042:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
16043:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
16044:                             foreach my $type ('E','W','N','U') {
16045:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
16046:                                         $currsetting{'lonstatus'}{$key}{$type}) {
16047:                                     push(@{$changes{'lonstatus'}},$key);
16048:                                     last;
16049:                                 }
16050:                             }
16051:                         } else {
16052:                             foreach my $type ('E','W','N','U') {
16053:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
16054:                                     push(@{$changes{'lonstatus'}},$key);
16055:                                     last;
16056:                                 }
16057:                             }
16058:                         }
16059:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
16060:                         foreach my $type ('E','W','N','U') {
16061:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
16062:                                 push(@{$changes{'lonstatus'}},$key);
16063:                                 last;
16064:                             }
16065:                         }
16066:                     }
16067:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
16068:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16069:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
16070:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
16071:                                 push(@{$changes{'lonstatus'}},$key);
16072:                             }
16073:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
16074:                             push(@{$changes{'lonstatus'}},$key);
16075:                         }
16076:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
16077:                         push(@{$changes{'lonstatus'}},$key);
16078:                     }
16079:                 }
16080:             }
16081:         } else {
16082:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16083:                 foreach my $key ('excluded','weights','threshold','sysmail') {
16084:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
16085:                         push(@{$changes{'lonstatus'}},$key);
16086:                     }
16087:                 }
16088:             }
16089:         }
16090:     } else {
16091:         my %default;
16092:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
16093:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
16094:         $default{'errormail'} = 'adminemail';
16095:         $default{'packagesmail'} = 'adminemail';
16096:         $default{'helpdeskmail'} = 'supportemail';
16097:         $default{'otherdomsmail'} = 'supportemail';
16098:         $default{'lonstatusmail'} = 'adminemail';
16099:         $default{'requestsmail'} = 'adminemail';
16100:         $default{'updatesmail'} = 'adminemail';
16101:         $default{'hostipmail'} = 'adminemail';
16102:         foreach my $item (@contacts) {
16103:            if ($to{$item} ne $default{$item}) {
16104:                $changes{$item} = 1;
16105:            }
16106:         }
16107:         foreach my $type (@mailings) {
16108:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
16109:                 push(@{$changes{$type}},@{$newsetting{$type}});
16110:             }
16111:             if ($others{$type} ne '') {
16112:                 push(@{$changes{$type}},'others');
16113:             }
16114:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16115:                 if ($bcc{$type} ne '') {
16116:                     push(@{$changes{$type}},'bcc');
16117:                 }
16118:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
16119:                     push(@{$changes{$type}},'include');
16120:                 }
16121:             }
16122:         }
16123:         if (ref($fields) eq 'ARRAY') {
16124:             foreach my $field (@{$fields}) {
16125:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
16126:                     push(@{$changes{'helpform'}},$field);
16127:                 }
16128:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
16129:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
16130:                         push(@{$changes{'helpform'}},'maxsize');
16131:                     }
16132:                 }
16133:             }
16134:         }
16135:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16136:             foreach my $key ('excluded','weights','threshold','sysmail') {
16137:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
16138:                     push(@{$changes{'lonstatus'}},$key);
16139:                 }
16140:             }
16141:         }
16142:     }
16143:     foreach my $item (@toggles) {
16144:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
16145:             $changes{$item} = 1;
16146:         } elsif ((!$env{'form.'.$item}) &&
16147:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
16148:             $changes{$item} = 1;
16149:         }
16150:     }
16151:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
16152:                                              $dom);
16153:     if ($putresult eq 'ok') {
16154:         if (keys(%changes) > 0) {
16155:             &Apache::loncommon::devalidate_domconfig_cache($dom);
16156:             if (ref($lastactref) eq 'HASH') {
16157:                 $lastactref->{'domainconfig'} = 1;
16158:             }
16159:             my ($titles,$short_titles)  = &contact_titles();
16160:             $resulttext = &mt('Changes made:').'<ul>';
16161:             foreach my $item (@contacts) {
16162:                 if ($changes{$item}) {
16163:                     $resulttext .= '<li>'.$titles->{$item}.
16164:                                     &mt(' set to: ').
16165:                                     '<span class="LC_cusr_emph">'.
16166:                                     $to{$item}.'</span></li>';
16167:                 }
16168:             }
16169:             foreach my $type (@mailings) {
16170:                 if (ref($changes{$type}) eq 'ARRAY') {
16171:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16172:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
16173:                     } else {
16174:                         $resulttext .= '<li>'.$titles->{$type}.': ';
16175:                     }
16176:                     my @text;
16177:                     foreach my $item (@{$newsetting{$type}}) {
16178:                         push(@text,$short_titles->{$item});
16179:                     }
16180:                     if ($others{$type} ne '') {
16181:                         push(@text,$others{$type});
16182:                     }
16183:                     if (@text) {
16184:                         $resulttext .= '<span class="LC_cusr_emph">'.
16185:                                        join(', ',@text).'</span>';
16186:                     }
16187:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16188:                         if ($bcc{$type} ne '') {
16189:                             my $bcctext;
16190:                             if (@text) {
16191:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
16192:                             } else {
16193:                                 $bcctext = '(Bcc)';
16194:                             }
16195:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
16196:                         } elsif (!@text) {
16197:                             $resulttext .= &mt('No one');
16198:                         }   
16199:                         if ($includestr{$type} ne '') {
16200:                             if ($includeloc{$type} eq 'b') {
16201:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
16202:                             } elsif ($includeloc{$type} eq 's') {
16203:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
16204:                             }
16205:                         }
16206:                     } elsif (!@text) {
16207:                         $resulttext .= &mt('No recipients');
16208:                     }
16209:                     $resulttext .= '</li>';
16210:                 }
16211:             }
16212:             if (ref($changes{'overrides'}) eq 'ARRAY') {
16213:                 my @deletions;
16214:                 foreach my $type (@{$changes{'overrides'}}) {
16215:                     if ($usertypeshash{$type}) {
16216:                         if (grep(/^\Q$type\E/,@overrides)) {
16217:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
16218:                                                       $usertypeshash{$type}).'<ul><li>';
16219:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
16220:                                 my @text;
16221:                                 foreach my $item (@contacts) {
16222:                                     if ($newsetting{'override_'.$type}{$item}) { 
16223:                                         push(@text,$short_titles->{$item});
16224:                                     }
16225:                                 }
16226:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
16227:                                     push(@text,$newsetting{'override_'.$type}{'others'});
16228:                                 }
16229:   
16230:                                 if (@text) {
16231:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
16232:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
16233:                                 }
16234:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
16235:                                     my $bcctext;
16236:                                     if (@text) {
16237:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
16238:                                     } else {
16239:                                         $bcctext = '(Bcc)';
16240:                                     }
16241:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
16242:                                 } elsif (!@text) {
16243:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
16244:                                 }
16245:                                 $resulttext .= '</li>';
16246:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
16247:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
16248:                                     if ($loc eq 'b') {
16249:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
16250:                                     } elsif ($loc eq 's') {
16251:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
16252:                                     }
16253:                                 }
16254:                             }
16255:                             $resulttext .= '</li></ul></li>';
16256:                         } else {
16257:                             push(@deletions,$usertypeshash{$type});
16258:                         }
16259:                     }
16260:                 }
16261:                 if (@deletions) {
16262:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
16263:                                               join(', ',@deletions)).'</li>';
16264:                 }
16265:             }
16266:             my @offon = ('off','on');
16267:             my $corelink = &core_link_msu();
16268:             if ($changes{'reporterrors'}) {
16269:                 $resulttext .= '<li>'.
16270:                                &mt('E-mail error reports to [_1] set to "'.
16271:                                    $offon[$env{'form.reporterrors'}].'".',
16272:                                    $corelink).
16273:                                '</li>';
16274:             }
16275:             if ($changes{'reportupdates'}) {
16276:                 $resulttext .= '<li>'.
16277:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
16278:                                     $offon[$env{'form.reportupdates'}].'".',
16279:                                     $corelink).
16280:                                 '</li>';
16281:             }
16282:             if ($changes{'reportstatus'}) {
16283:                 $resulttext .= '<li>'.
16284:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
16285:                                     $offon[$env{'form.reportstatus'}].'".',
16286:                                     $corelink).
16287:                                 '</li>';
16288:             }
16289:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
16290:                 $resulttext .= '<li>'.
16291:                                &mt('Nightly status check e-mail settings').':<ul>';
16292:                 my (%defval,%use_def,%shown);
16293:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
16294:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
16295:                 $defval{'weights'} =
16296:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
16297:                 $defval{'excluded'} = &mt('None');
16298:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
16299:                     foreach my $item ('threshold','sysmail','weights','excluded') {
16300:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
16301:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
16302:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
16303:                             } elsif ($item eq 'weights') {
16304:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
16305:                                     foreach my $type ('E','W','N','U') {
16306:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
16307:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
16308:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
16309:                                         } else {
16310:                                             $shown{$item} .= $lonstatus_defs->{$type};
16311:                                         }
16312:                                         $shown{$item} .= ', ';
16313:                                     }
16314:                                     $shown{$item} =~ s/, $//;
16315:                                 } else {
16316:                                     $shown{$item} = $defval{$item};
16317:                                 }
16318:                             } elsif ($item eq 'excluded') {
16319:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
16320:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
16321:                                 } else {
16322:                                     $shown{$item} = $defval{$item};
16323:                                 }
16324:                             }
16325:                         } else {
16326:                             $shown{$item} = $defval{$item};
16327:                         }
16328:                     }
16329:                 } else {
16330:                     foreach my $item ('threshold','weights','excluded','sysmail') {
16331:                         $shown{$item} = $defval{$item};
16332:                     }
16333:                 }
16334:                 foreach my $item ('threshold','weights','excluded','sysmail') {
16335:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
16336:                                           $shown{$item}).'</li>';
16337:                 }
16338:                 $resulttext .= '</ul></li>';
16339:             }
16340:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
16341:                 my (@optional,@required,@unused,$maxsizechg);
16342:                 foreach my $field (@{$changes{'helpform'}}) {
16343:                     if ($field eq 'maxsize') {
16344:                         $maxsizechg = 1;
16345:                         next;
16346:                     }
16347:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
16348:                         push(@optional,$field);
16349:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
16350:                         push(@unused,$field);
16351:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
16352:                         push(@required,$field);
16353:                     }
16354:                 }
16355:                 if (@optional) {
16356:                     $resulttext .= '<li>'.
16357:                                    &mt('Help form fields changed to "Optional": [_1].',
16358:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
16359:                                    '</li>';
16360:                 }
16361:                 if (@required) {
16362:                     $resulttext .= '<li>'.
16363:                                    &mt('Help form fields changed to "Required": [_1].',
16364:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
16365:                                    '</li>';
16366:                 }
16367:                 if (@unused) {
16368:                     $resulttext .= '<li>'.
16369:                                    &mt('Help form fields changed to "Not shown": [_1].',
16370:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
16371:                                    '</li>';
16372:                 }
16373:                 if ($maxsizechg) {
16374:                     $resulttext .= '<li>'.
16375:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
16376:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
16377:                                    '</li>';
16378:                 }
16379:             }
16380:             $resulttext .= '</ul>';
16381:         } else {
16382:             $resulttext = &mt('No changes made to contacts and form settings');
16383:         }
16384:     } else {
16385:         $resulttext = '<span class="LC_error">'.
16386:             &mt('An error occurred: [_1].',$putresult).'</span>';
16387:     }
16388:     return $resulttext;
16389: }
16390: 
16391: sub modify_privacy {
16392:     my ($dom,%domconfig) = @_;
16393:     my ($resulttext,%current,%changes);
16394:     if (ref($domconfig{'privacy'}) eq 'HASH') {
16395:         %current = %{$domconfig{'privacy'}};
16396:     }
16397:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
16398:     my @items = ('domain','author','course','community');
16399:     my %names = &Apache::lonlocal::texthash (
16400:                    domain => 'Assigned domain role(s)',
16401:                    author => 'Assigned co-author role(s)',
16402:                    course => 'Assigned course role(s)',
16403:                    community => 'Assigned community role',
16404:                 );
16405:     my %roles = &Apache::lonlocal::texthash (
16406:                    domain => 'Domain role',
16407:                    author => 'Co-author role',
16408:                    course => 'Course role',
16409:                    community => 'Community role',
16410:                 );
16411:     my %titles = &Apache::lonlocal::texthash (
16412:                   approval => 'Approval for role in different domain',
16413:                   othdom   => 'User information available in other domain',
16414:                   priv     => 'Information viewable by privileged user in same domain',
16415:                   unpriv   => 'Information viewable by unprivileged user in same domain',
16416:                   instdom  => 'Other domain shares institution/provider',
16417:                   extdom   => 'Other domain has different institution/provider',
16418:                   none     => 'Not allowed',
16419:                   user     => 'User authorizes',
16420:                   domain   => 'Domain Coordinator authorizes',
16421:                   auto     => 'Unrestricted',
16422:     );
16423:     my %fieldnames = &Apache::lonlocal::texthash (
16424:                         id => 'Student/Employee ID',
16425:                         permanentemail => 'E-mail address',
16426:                         lastname => 'Last Name',
16427:                         firstname => 'First Name',
16428:                         middlename => 'Middle Name',
16429:                         generation => 'Generation',
16430:     );
16431:     my ($othertitle,$usertypes,$types) =
16432:         &Apache::loncommon::sorted_inst_types($dom);
16433:     my (%by_ip,%by_location,@intdoms,@instdoms);
16434:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
16435: 
16436:     my %privacyhash = (
16437:                        'approval' => {
16438:                                        instdom => {},
16439:                                        extdom  => {},
16440:                                      },
16441:                        'othdom'   => {},
16442:                        'priv'     => {},
16443:                        'unpriv'   => {},
16444:                       );
16445:     foreach my $item (@items) {
16446:         if (@instdoms > 1) {
16447:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
16448:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
16449:             }
16450:             if (ref($current{'approval'}) eq 'HASH') {
16451:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
16452:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
16453:                         $changes{'approval'} = 1;
16454:                     }
16455:                 }
16456:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
16457:                 $changes{'approval'} = 1;
16458:             }
16459:         }
16460:         if (keys(%by_location) > 0) {
16461:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
16462:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
16463:             }
16464:             if (ref($current{'approval'}) eq 'HASH') {
16465:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
16466:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
16467:                         $changes{'approval'} = 1;
16468:                     }
16469:                 }
16470:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
16471:                 $changes{'approval'} = 1;
16472:             }
16473:         }
16474:         foreach my $status ('priv','unpriv') {
16475:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
16476:             my @newvalues;
16477:             foreach my $field (@possibles) {
16478:                 if (grep(/^\Q$field\E$/,@fields)) {
16479:                     $privacyhash{$status}{$item}{$field} = 1;
16480:                     push(@newvalues,$field);
16481:                 }
16482:             }
16483:             @newvalues = sort(@newvalues);
16484:             if (ref($current{$status}) eq 'HASH') {
16485:                 if (ref($current{$status}{$item}) eq 'HASH') {
16486:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
16487:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
16488:                     if (@diffs > 0) {
16489:                         $changes{$status} = 1;
16490:                     }
16491:                 }
16492:             } else {
16493:                 my @stdfields;
16494:                 foreach my $field (@fields) {
16495:                     if ($field eq 'id') {
16496:                         next if ($status eq 'unpriv');
16497:                         next if (($status eq 'priv') && ($item eq 'community'));
16498:                     }
16499:                     push(@stdfields,$field);
16500:                 }
16501:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
16502:                 if (@diffs > 0) {
16503:                     $changes{$status} = 1;
16504:                 }
16505:             }
16506:         }
16507:     }
16508:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
16509:         my @statuses;
16510:         if (ref($types) eq 'ARRAY') {
16511:             @statuses = @{$types};
16512:         }
16513:         foreach my $type (@statuses,'default') {
16514:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
16515:             my @newvalues;
16516:             foreach my $field (sort(@possfields)) {
16517:                 if (grep(/^\Q$field\E$/,@fields)) {
16518:                     $privacyhash{'othdom'}{$type}{$field} = 1;
16519:                     push(@newvalues,$field);
16520:                 }
16521:             }
16522:             @newvalues = sort(@newvalues);
16523:             if (ref($current{'othdom'}) eq 'HASH') {
16524:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
16525:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
16526:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
16527:                     if (@diffs > 0) {
16528:                         $changes{'othdom'} = 1;
16529:                     }
16530:                 }
16531:             } else {
16532:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
16533:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
16534:                 if (@diffs > 0) {
16535:                     $changes{'othdom'} = 1;
16536:                 }
16537:             }
16538:         }
16539:     }
16540:     my %confighash = (
16541:                         privacy => \%privacyhash,
16542:                      );
16543:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
16544:     if ($putresult eq 'ok') {
16545:         if (keys(%changes) > 0) {
16546:             $resulttext = &mt('Changes made: ').'<ul>';
16547:             foreach my $key ('approval','othdom','priv','unpriv') {
16548:                 if ($changes{$key}) {
16549:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
16550:                     if ($key eq 'approval') {
16551:                         if (keys(%{$privacyhash{$key}{instdom}})) {
16552:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
16553:                             foreach my $item (@items) {
16554:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
16555:                             }
16556:                             $resulttext .= '</ul></li>';
16557:                         }
16558:                         if (keys(%{$privacyhash{$key}{extdom}})) {
16559:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
16560:                             foreach my $item (@items) {
16561:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
16562:                             }
16563:                             $resulttext .= '</ul></li>';
16564:                         }
16565:                     } elsif ($key eq 'othdom') {
16566:                         my @statuses;
16567:                         if (ref($types) eq 'ARRAY') {
16568:                             @statuses = @{$types};
16569:                         }
16570:                         if (ref($privacyhash{$key}) eq 'HASH') {
16571:                             foreach my $status (@statuses,'default') {
16572:                                 if ($status eq 'default') {
16573:                                     $resulttext .= '<li>'.$othertitle.': ';
16574:                                 } elsif (ref($usertypes) eq 'HASH') {
16575:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
16576:                                 } else {
16577:                                     next;
16578:                                 }
16579:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
16580:                                     if (keys(%{$privacyhash{$key}{$status}})) {
16581:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
16582:                                     } else {
16583:                                         $resulttext .= &mt('none');
16584:                                     }
16585:                                 }
16586:                                 $resulttext .= '</li>';
16587:                             }
16588:                         }
16589:                     } else {
16590:                         foreach my $item (@items) {
16591:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
16592:                                 $resulttext .= '<li>'.$names{$item}.': ';
16593:                                 if (keys(%{$privacyhash{$key}{$item}})) {
16594:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
16595:                                 } else {
16596:                                     $resulttext .= &mt('none');
16597:                                 }
16598:                                 $resulttext .= '</li>';
16599:                             }
16600:                         }
16601:                     }
16602:                     $resulttext .= '</ul></li>';
16603:                 }
16604:             }
16605:         } else {
16606:             $resulttext = &mt('No changes made to user information settings');
16607:         }
16608:     } else {
16609:         $resulttext = '<span class="LC_error">'.
16610:             &mt('An error occurred: [_1]',$putresult).'</span>';
16611:     }
16612:     return $resulttext;
16613: }
16614: 
16615: sub modify_passwords {
16616:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
16617:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
16618:         $updatedefaults,$updateconf);
16619:     my $customfn = 'resetpw.html';
16620:     if (ref($domconfig{'passwords'}) eq 'HASH') {
16621:         %current = %{$domconfig{'passwords'}};
16622:     }
16623:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16624:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16625:     if (ref($types) eq 'ARRAY') {
16626:         @oktypes = @{$types};
16627:     }
16628:     push(@oktypes,'default');
16629: 
16630:     my %titles = &Apache::lonlocal::texthash (
16631:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
16632:         intauth_check  => 'Check bcrypt cost if authenticated',
16633:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
16634:         permanent      => 'Permanent e-mail address',
16635:         critical       => 'Critical notification address',
16636:         notify         => 'Notification address',
16637:         min            => 'Minimum password length',
16638:         max            => 'Maximum password length',
16639:         chars          => 'Required characters',
16640:         expire         => 'Password expiration (days)',
16641:         numsaved       => 'Number of previous passwords to save',
16642:         reset          => 'Resetting Forgotten Password',
16643:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
16644:         rules          => 'Rules for LON-CAPA Passwords',
16645:         crsownerchg    => 'Course Owner Changing Student Passwords',
16646:         username       => 'Username',
16647:         email          => 'E-mail address',
16648:     );
16649: 
16650: #
16651: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
16652: #
16653:     my (%curr_defaults,%save_defaults);
16654:     if (ref($domconfig{'defaults'}) eq 'HASH') {
16655:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
16656:             if ($key =~ /^intauth_(cost|check|switch)$/) {
16657:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
16658:             } else {
16659:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
16660:             }
16661:         }
16662:     }
16663:     my %staticdefaults = (
16664:         'resetlink'      => 2,
16665:         'resetcase'      => \@oktypes,
16666:         'resetprelink'   => 'both',
16667:         'resetemail'     => ['critical','notify','permanent'],
16668:         'intauth_cost'   => 10,
16669:         'intauth_check'  => 0,
16670:         'intauth_switch' => 0,
16671:     );
16672:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
16673:     foreach my $type (@oktypes) {
16674:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
16675:     }
16676:     my $linklife = $env{'form.passwords_link'};
16677:     $linklife =~ s/^\s+|\s+$//g;
16678:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
16679:         $newvalues{'resetlink'} = $linklife;
16680:         if ($current{'resetlink'}) {
16681:             if ($current{'resetlink'} ne $linklife) {
16682:                 $changes{'reset'} = 1;
16683:             }
16684:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16685:             if ($staticdefaults{'resetlink'} ne $linklife) {
16686:                 $changes{'reset'} = 1;
16687:             }
16688:         }
16689:     } elsif ($current{'resetlink'}) {
16690:         $changes{'reset'} = 1;
16691:     }
16692:     my @casesens;
16693:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
16694:     foreach my $case (sort(@posscase)) {
16695:         if (grep(/^\Q$case\E$/,@oktypes)) {
16696:             push(@casesens,$case);
16697:         }
16698:     }
16699:     $newvalues{'resetcase'} = \@casesens;
16700:     if (ref($current{'resetcase'}) eq 'ARRAY') {
16701:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
16702:         if (@diffs > 0) {
16703:             $changes{'reset'} = 1;
16704:         }
16705:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16706:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
16707:         if (@diffs > 0) {
16708:             $changes{'reset'} = 1;
16709:         }
16710:     }
16711:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
16712:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
16713:         if (exists($current{'resetprelink'})) {
16714:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
16715:                 $changes{'reset'} = 1;
16716:             }
16717:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16718:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
16719:                 $changes{'reset'} = 1;
16720:             }
16721:         }
16722:     } elsif ($current{'resetprelink'}) {
16723:         $changes{'reset'} = 1;
16724:     }
16725:     foreach my $type (@oktypes) {
16726:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
16727:         my @postlink;
16728:         foreach my $item (sort(@possplink)) {
16729:             if ($item =~ /^(email|username)$/) {
16730:                 push(@postlink,$item);
16731:             }
16732:         }
16733:         $newvalues{'resetpostlink'}{$type} = \@postlink;
16734:         unless ($changes{'reset'}) {
16735:             if (ref($current{'resetpostlink'}) eq 'HASH') {
16736:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
16737:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
16738:                     if (@diffs > 0) {
16739:                         $changes{'reset'} = 1;
16740:                     }
16741:                 } else {
16742:                     $changes{'reset'} = 1;
16743:                 }
16744:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16745:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
16746:                 if (@diffs > 0) {
16747:                     $changes{'reset'} = 1;
16748:                 }
16749:             }
16750:         }
16751:     }
16752:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
16753:     my @resetemail;
16754:     foreach my $item (sort(@possemailsrc)) {
16755:         if ($item =~ /^(permanent|critical|notify)$/) {
16756:             push(@resetemail,$item);
16757:         }
16758:     }
16759:     $newvalues{'resetemail'} = \@resetemail;
16760:     unless ($changes{'reset'}) {
16761:         if (ref($current{'resetemail'}) eq 'ARRAY') {
16762:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
16763:             if (@diffs > 0) {
16764:                 $changes{'reset'} = 1;
16765:             }
16766:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16767:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
16768:             if (@diffs > 0) {
16769:                 $changes{'reset'} = 1;
16770:             }
16771:         }
16772:     }
16773:     if ($env{'form.passwords_stdtext'} == 0) {
16774:         $newvalues{'resetremove'} = 1;
16775:         unless ($current{'resetremove'}) {
16776:             $changes{'reset'} = 1;
16777:         }
16778:     } elsif ($current{'resetremove'}) {
16779:         $changes{'reset'} = 1;
16780:     }
16781:     if ($env{'form.passwords_customfile.filename'} ne '') {
16782:         my $servadm = $r->dir_config('lonAdmEMail');
16783:         my ($configuserok,$author_ok,$switchserver) =
16784:             &config_check($dom,$confname,$servadm);
16785:         my $error;
16786:         if ($configuserok eq 'ok') {
16787:             if ($switchserver) {
16788:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
16789:             } else {
16790:                 if ($author_ok eq 'ok') {
16791:                     my ($result,$customurl) =
16792:                         &publishlogo($r,'upload','passwords_customfile',$dom,
16793:                                      $confname,'customtext/resetpw','','',$customfn);
16794:                     if ($result eq 'ok') {
16795:                         $newvalues{'resetcustom'} = $customurl;
16796:                         $changes{'reset'} = 1;
16797:                     } else {
16798:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
16799:                     }
16800:                 } else {
16801:                     $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);
16802:                 }
16803:             }
16804:         } else {
16805:             $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);
16806:         }
16807:         if ($error) {
16808:             &Apache::lonnet::logthis($error);
16809:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16810:         }
16811:     } elsif ($current{'resetcustom'}) {
16812:         if ($env{'form.passwords_custom_del'}) {
16813:             $changes{'reset'} = 1;
16814:         } else {
16815:             $newvalues{'resetcustom'} = $current{'resetcustom'};
16816:         }
16817:     }
16818:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
16819:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
16820:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
16821:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
16822:             $changes{'intauth'} = 1;
16823:         }
16824:     } else {
16825:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
16826:     }
16827:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
16828:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
16829:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
16830:             $changes{'intauth'} = 1;
16831:         }
16832:     } else {
16833:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
16834:     }
16835:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
16836:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
16837:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
16838:             $changes{'intauth'} = 1;
16839:         }
16840:     } else {
16841:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
16842:     }
16843:     foreach my $item ('cost','check','switch') {
16844:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
16845:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
16846:             $updatedefaults = 1;
16847:         }
16848:     }
16849:     foreach my $rule ('min','max','expire','numsaved') {
16850:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
16851:         my $ruleok;
16852:         if ($rule eq 'expire') {
16853:             if (($env{'form.passwords_'.$rule} =~ /^\d+(|\.\d*)$/) &&
16854:                 ($env{'form.passwords_'.$rule} ne '0')) {
16855:                 $ruleok = 1;
16856:             }
16857:         } elsif ($rule eq 'min') {
16858:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
16859:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
16860:                     $ruleok = 1;
16861:                 }
16862:             }
16863:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
16864:                  ($env{'form.passwords_'.$rule} ne '0')) {
16865:             $ruleok = 1;
16866:         }
16867:         if ($ruleok) {
16868:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
16869:             if (exists($current{$rule})) {
16870:                 if ($newvalues{$rule} ne $current{$rule}) {
16871:                     $changes{'rules'} = 1;
16872:                 }
16873:             } elsif ($rule eq 'min') {
16874:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
16875:                     $changes{'rules'} = 1;
16876:                 }
16877:             } else {
16878:                 $changes{'rules'} = 1;
16879:             }
16880:         } elsif (exists($current{$rule})) {
16881:             $changes{'rules'} = 1;
16882:         }
16883:     }
16884:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
16885:     my @chars;
16886:     foreach my $item (sort(@posschars)) {
16887:         if ($item =~ /^(uc|lc|num|spec)$/) {
16888:             push(@chars,$item);
16889:         }
16890:     }
16891:     $newvalues{'chars'} = \@chars;
16892:     unless ($changes{'rules'}) {
16893:         if (ref($current{'chars'}) eq 'ARRAY') {
16894:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
16895:             if (@diffs > 0) {
16896:                 $changes{'rules'} = 1;
16897:             }
16898:         } else {
16899:             if (@chars > 0) {
16900:                 $changes{'rules'} = 1;
16901:             }
16902:         }
16903:     }
16904:     my %crsownerchg = (
16905:                         by => [],
16906:                         for => [],
16907:                       );
16908:     foreach my $item ('by','for') {
16909:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
16910:         foreach my $type (sort(@posstypes)) {
16911:             if (grep(/^\Q$type\E$/,@oktypes)) {
16912:                 push(@{$crsownerchg{$item}},$type);
16913:             }
16914:         }
16915:     }
16916:     $newvalues{'crsownerchg'} = \%crsownerchg;
16917:     if (ref($current{'crsownerchg'}) eq 'HASH') {
16918:         foreach my $item ('by','for') {
16919:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
16920:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
16921:                 if (@diffs > 0) {
16922:                     $changes{'crsownerchg'} = 1;
16923:                     last;
16924:                 }
16925:             }
16926:         }
16927:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
16928:         foreach my $item ('by','for') {
16929:             if (@{$crsownerchg{$item}} > 0) {
16930:                 $changes{'crsownerchg'} = 1;
16931:                 last;
16932:             }
16933:         }
16934:     }
16935: 
16936:     my %confighash = (
16937:                         defaults  => \%save_defaults,
16938:                         passwords => \%newvalues,
16939:                      );
16940:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
16941: 
16942:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
16943:     if ($putresult eq 'ok') {
16944:         if (keys(%changes) > 0) {
16945:             $resulttext = &mt('Changes made: ').'<ul>';
16946:             foreach my $key ('reset','intauth','rules','crsownerchg') {
16947:                 if ($changes{$key}) {
16948:                     unless ($key eq 'intauth') {
16949:                         $updateconf = 1;
16950:                     }
16951:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
16952:                     if ($key eq 'reset') {
16953:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
16954:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
16955:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
16956:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
16957:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
16958:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
16959:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
16960:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
16961:                             }
16962:                         } else {
16963:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
16964:                         }
16965:                         if ($confighash{'passwords'}{'resetlink'}) {
16966:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
16967:                         } else {
16968:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
16969:                                                   &mt('Will default to 2 hours').'</li>';
16970:                         }
16971:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
16972:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
16973:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
16974:                             } else {
16975:                                 my $casesens;
16976:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
16977:                                     if ($type eq 'default') {
16978:                                         $casesens .= $othertitle.', ';
16979:                                     } elsif ($usertypes->{$type} ne '') {
16980:                                         $casesens .= $usertypes->{$type}.', ';
16981:                                     }
16982:                                 }
16983:                                 $casesens =~ s/\Q, \E$//;
16984:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
16985:                             }
16986:                         } else {
16987:                             $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>';
16988:                         }
16989:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
16990:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
16991:                         } else {
16992:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
16993:                         }
16994:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
16995:                             my $output;
16996:                             if (ref($types) eq 'ARRAY') {
16997:                                 foreach my $type (@{$types}) {
16998:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
16999:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
17000:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
17001:                                         } else {
17002:                                             $output .= $usertypes->{$type}.' -- '.
17003:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
17004:                                         }
17005:                                     }
17006:                                 }
17007:                             }
17008:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
17009:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
17010:                                     $output .= $othertitle.' -- '.&mt('none');
17011:                                 } else {
17012:                                     $output .= $othertitle.' -- '.
17013:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
17014:                                 }
17015:                             }
17016:                             if ($output) {
17017:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
17018:                             } else {
17019:                                 $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>';
17020:                             }
17021:                         } else {
17022:                             $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>';
17023:                         }
17024:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
17025:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
17026:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
17027:                             } else {
17028:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
17029:                             }
17030:                         } else {
17031:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
17032:                         }
17033:                         if ($confighash{'passwords'}{'resetremove'}) {
17034:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
17035:                         } else {
17036:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
17037:                         }
17038:                         if ($confighash{'passwords'}{'resetcustom'}) {
17039:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
17040:                                                                             &mt('custom text'),600,500,undef,undef,
17041:                                                                             undef,undef,'background-color:#ffffff');
17042:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
17043:                         } else {
17044:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
17045:                         }
17046:                     } elsif ($key eq 'intauth') {
17047:                         foreach my $item ('cost','switch','check') {
17048:                             my $value = $save_defaults{$key.'_'.$item};
17049:                             if ($item eq 'switch') {
17050:                                 my %optiondesc = &Apache::lonlocal::texthash (
17051:                                                      0 => 'No',
17052:                                                      1 => 'Yes',
17053:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
17054:                                                  );
17055:                                 if ($value =~ /^(0|1|2)$/) {
17056:                                     $value = $optiondesc{$value};
17057:                                 } else {
17058:                                     $value = &mt('none -- defaults to No');
17059:                                 }
17060:                             } elsif ($item eq 'check') {
17061:                                 my %optiondesc = &Apache::lonlocal::texthash (
17062:                                                      0 => 'No',
17063:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
17064:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
17065:                                                  );
17066:                                 if ($value =~ /^(0|1|2)$/) {
17067:                                     $value = $optiondesc{$value};
17068:                                 } else {
17069:                                     $value = &mt('none -- defaults to No');
17070:                                 }
17071:                             }
17072:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
17073:                         }
17074:                     } elsif ($key eq 'rules') {
17075:                         foreach my $rule ('min','max','expire','numsaved') {
17076:                             if ($confighash{'passwords'}{$rule} eq '') {
17077:                                 if ($rule eq 'min') {
17078:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
17079:                                                    ' '.&mt('Default of [_1] will be used',
17080:                                                            $Apache::lonnet::passwdmin).'</li>';
17081:                                 } else {
17082:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
17083:                                 }
17084:                             } else {
17085:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
17086:                             }
17087:                         }
17088:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
17089:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
17090:                                 my %rulenames = &Apache::lonlocal::texthash(
17091:                                                      uc => 'At least one upper case letter',
17092:                                                      lc => 'At least one lower case letter',
17093:                                                      num => 'At least one number',
17094:                                                      spec => 'At least one non-alphanumeric',
17095:                                                    );
17096:                                 my $needed = '<ul><li>'.
17097:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
17098:                                              '</li></ul>'; 
17099:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
17100:                             } else {
17101:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
17102:                             }
17103:                         } else {
17104:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
17105:                         }
17106:                     } elsif ($key eq 'crsownerchg') {
17107:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
17108:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
17109:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
17110:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
17111:                             } else {
17112:                                 my %crsownerstr;
17113:                                 foreach my $item ('by','for') {
17114:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
17115:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
17116:                                             if ($type eq 'default') {
17117:                                                 $crsownerstr{$item} .= $othertitle.', ';
17118:                                             } elsif ($usertypes->{$type} ne '') {
17119:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
17120:                                             }
17121:                                         }
17122:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
17123:                                     }
17124:                                 }
17125:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
17126:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
17127:                             }
17128:                         } else {
17129:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
17130:                         }
17131:                     }
17132:                     $resulttext .= '</ul></li>';
17133:                 }
17134:             }
17135:             $resulttext .= '</ul>';
17136:         } else {
17137:             $resulttext = &mt('No changes made to password settings');
17138:         }
17139:         my $cachetime = 24*60*60;
17140:         if ($updatedefaults) {
17141:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17142:             if (ref($lastactref) eq 'HASH') {
17143:                 $lastactref->{'domdefaults'} = 1;
17144:             }
17145:         }
17146:         if ($updateconf) {
17147:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
17148:             if (ref($lastactref) eq 'HASH') {
17149:                 $lastactref->{'passwdconf'} = 1;
17150:             }
17151:         }
17152:     } else {
17153:         $resulttext = '<span class="LC_error">'.
17154:             &mt('An error occurred: [_1]',$putresult).'</span>';
17155:     }
17156:     if ($errors) {
17157:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
17158:                        $errors.'</ul></p>';
17159:     }
17160:     return $resulttext;
17161: }
17162: 
17163: sub modify_usercreation {
17164:     my ($dom,%domconfig) = @_;
17165:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
17166:     my $warningmsg;
17167:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
17168:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
17169:             if ($key eq 'cancreate') {
17170:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
17171:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
17172:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
17173:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17174:                         } else {
17175:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17176:                         }
17177:                     }
17178:                 }
17179:             } elsif ($key eq 'email_rule') {
17180:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
17181:             } else {
17182:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
17183:             }
17184:         }
17185:     }
17186:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
17187:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
17188:     my @contexts = ('author','course','requestcrs');
17189:     foreach my $item(@contexts) {
17190:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
17191:     }
17192:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17193:         foreach my $item (@contexts) {
17194:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
17195:                 push(@{$changes{'cancreate'}},$item);
17196:             }
17197:         }
17198:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
17199:         foreach my $item (@contexts) {
17200:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
17201:                 if ($cancreate{$item} ne 'any') {
17202:                     push(@{$changes{'cancreate'}},$item);
17203:                 }
17204:             } else {
17205:                 if ($cancreate{$item} ne 'none') {
17206:                     push(@{$changes{'cancreate'}},$item);
17207:                 }
17208:             }
17209:         }
17210:     } else {
17211:         foreach my $item (@contexts)  {
17212:             push(@{$changes{'cancreate'}},$item);
17213:         }
17214:     }
17215: 
17216:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
17217:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
17218:             if (!grep(/^\Q$type\E$/,@username_rule)) {
17219:                 push(@{$changes{'username_rule'}},$type);
17220:             }
17221:         }
17222:         foreach my $type (@username_rule) {
17223:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
17224:                 push(@{$changes{'username_rule'}},$type);
17225:             }
17226:         }
17227:     } else {
17228:         push(@{$changes{'username_rule'}},@username_rule);
17229:     }
17230: 
17231:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
17232:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
17233:             if (!grep(/^\Q$type\E$/,@id_rule)) {
17234:                 push(@{$changes{'id_rule'}},$type);
17235:             }
17236:         }
17237:         foreach my $type (@id_rule) {
17238:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
17239:                 push(@{$changes{'id_rule'}},$type);
17240:             }
17241:         }
17242:     } else {
17243:         push(@{$changes{'id_rule'}},@id_rule);
17244:     }
17245: 
17246:     my @authen_contexts = ('author','course','domain');
17247:     my @authtypes = ('int','krb4','krb5','loc','lti');
17248:     my %authhash;
17249:     foreach my $item (@authen_contexts) {
17250:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
17251:         foreach my $auth (@authtypes) {
17252:             if (grep(/^\Q$auth\E$/,@authallowed)) {
17253:                 $authhash{$item}{$auth} = 1;
17254:             } else {
17255:                 $authhash{$item}{$auth} = 0;
17256:             }
17257:         }
17258:     }
17259:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
17260:         foreach my $item (@authen_contexts) {
17261:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
17262:                 foreach my $auth (@authtypes) {
17263:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
17264:                         push(@{$changes{'authtypes'}},$item);
17265:                         last;
17266:                     }
17267:                 }
17268:             }
17269:         }
17270:     } else {
17271:         foreach my $item (@authen_contexts) {
17272:             push(@{$changes{'authtypes'}},$item);
17273:         }
17274:     }
17275: 
17276:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
17277:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
17278:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
17279:     $save_usercreate{'id_rule'} = \@id_rule;
17280:     $save_usercreate{'username_rule'} = \@username_rule,
17281:     $save_usercreate{'authtypes'} = \%authhash;
17282: 
17283:     my %usercreation_hash =  (
17284:         usercreation     => \%save_usercreate,
17285:     );
17286: 
17287:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
17288:                                              $dom);
17289: 
17290:     if ($putresult eq 'ok') {
17291:         if (keys(%changes) > 0) {
17292:             $resulttext = &mt('Changes made:').'<ul>';
17293:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
17294:                 my %lt = &usercreation_types();
17295:                 foreach my $type (@{$changes{'cancreate'}}) {
17296:                     my $chgtext = $lt{$type}.', ';
17297:                     if ($cancreate{$type} eq 'none') {
17298:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
17299:                     } elsif ($cancreate{$type} eq 'any') {
17300:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
17301:                     } elsif ($cancreate{$type} eq 'official') {
17302:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
17303:                     } elsif ($cancreate{$type} eq 'unofficial') {
17304:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
17305:                     }
17306:                     $resulttext .= '<li>'.$chgtext.'</li>';
17307:                 }
17308:             }
17309:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
17310:                 my ($rules,$ruleorder) = 
17311:                     &Apache::lonnet::inst_userrules($dom,'username');
17312:                 my $chgtext = '<ul>';
17313:                 foreach my $type (@username_rule) {
17314:                     if (ref($rules->{$type}) eq 'HASH') {
17315:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
17316:                     }
17317:                 }
17318:                 $chgtext .= '</ul>';
17319:                 if (@username_rule > 0) {
17320:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
17321:                 } else {
17322:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
17323:                 }
17324:             }
17325:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
17326:                 my ($idrules,$idruleorder) = 
17327:                     &Apache::lonnet::inst_userrules($dom,'id');
17328:                 my $chgtext = '<ul>';
17329:                 foreach my $type (@id_rule) {
17330:                     if (ref($idrules->{$type}) eq 'HASH') {
17331:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
17332:                     }
17333:                 }
17334:                 $chgtext .= '</ul>';
17335:                 if (@id_rule > 0) {
17336:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
17337:                 } else {
17338:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
17339:                 }
17340:             }
17341:             my %authname = &authtype_names();
17342:             my %context_title = &context_names();
17343:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
17344:                 my $chgtext = '<ul>';
17345:                 foreach my $type (@{$changes{'authtypes'}}) {
17346:                     my @allowed;
17347:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
17348:                     foreach my $auth (@authtypes) {
17349:                         if ($authhash{$type}{$auth}) {
17350:                             push(@allowed,$authname{$auth});
17351:                         }
17352:                     }
17353:                     if (@allowed > 0) {
17354:                         $chgtext .= join(', ',@allowed).'</li>';
17355:                     } else {
17356:                         $chgtext .= &mt('none').'</li>';
17357:                     }
17358:                 }
17359:                 $chgtext .= '</ul>';
17360:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
17361:                 $resulttext .= '</li>';
17362:             }
17363:             $resulttext .= '</ul>';
17364:         } else {
17365:             $resulttext = &mt('No changes made to user creation settings');
17366:         }
17367:     } else {
17368:         $resulttext = '<span class="LC_error">'.
17369:             &mt('An error occurred: [_1]',$putresult).'</span>';
17370:     }
17371:     if ($warningmsg ne '') {
17372:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
17373:     }
17374:     return $resulttext;
17375: }
17376: 
17377: sub modify_selfcreation {
17378:     my ($dom,$lastactref,%domconfig) = @_;
17379:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
17380:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
17381:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17382:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
17383:     if (ref($typesref) eq 'ARRAY') {
17384:         @types = @{$typesref};
17385:     }
17386:     if (ref($usertypesref) eq 'HASH') {
17387:         %usertypes = %{$usertypesref};
17388:     }
17389:     $usertypes{'default'} = $othertitle;
17390: #
17391: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
17392: #
17393:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
17394:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
17395:             if ($key eq 'cancreate') {
17396:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
17397:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
17398:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
17399:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
17400:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
17401:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
17402:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
17403:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
17404:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17405:                         } else {
17406:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17407:                         }
17408:                     }
17409:                 }
17410:             } elsif ($key eq 'email_rule') {
17411:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
17412:             } else {
17413:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
17414:             }
17415:         }
17416:     }
17417: #
17418: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
17419: #
17420:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
17421:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
17422:             if ($key eq 'selfcreate') {
17423:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
17424:             } else {
17425:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
17426:             }
17427:         }
17428:     }
17429: #
17430: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
17431: #
17432:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
17433:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
17434:             if ($key eq 'inststatusguest') {
17435:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
17436:             } else {
17437:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
17438:             }
17439:         }
17440:     }
17441: 
17442:     my @contexts = ('selfcreate');
17443:     @{$cancreate{'selfcreate'}} = ();
17444:     %{$cancreate{'emailusername'}} = ();
17445:     if (@types) {
17446:         @{$cancreate{'statustocreate'}} = ();
17447:     }
17448:     %{$cancreate{'selfcreateprocessing'}} = ();
17449:     %{$cancreate{'shibenv'}} = ();
17450:     %{$cancreate{'emailverified'}} = ();
17451:     %{$cancreate{'emailoptions'}} = ();
17452:     %{$cancreate{'emaildomain'}} = ();
17453:     my %selfcreatetypes = (
17454:                              sso   => 'users authenticated by institutional single sign on',
17455:                              login => 'users authenticated by institutional log-in',
17456:                              email => 'users verified by e-mail',
17457:                           );
17458: #
17459: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
17460: # is permitted.
17461: #
17462:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
17463: 
17464:     my (@statuses,%email_rule);
17465:     foreach my $item ('login','sso','email') {
17466:         if ($item eq 'email') {
17467:             if ($env{'form.cancreate_email'}) {
17468:                 if (@types) {
17469:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
17470:                     foreach my $status (@poss_statuses) {
17471:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
17472:                             push(@statuses,$status);
17473:                         }
17474:                     }
17475:                     $save_inststatus{'inststatusguest'} = \@statuses;
17476:                 } else {
17477:                     push(@statuses,'default');
17478:                 }
17479:                 if (@statuses) {
17480:                     my %curr_rule;
17481:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
17482:                         foreach my $type (@statuses) {
17483:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
17484:                         }
17485:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
17486:                         foreach my $type (@statuses) {
17487:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
17488:                         }
17489:                     }
17490:                     push(@{$cancreate{'selfcreate'}},'email');
17491:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
17492:                     my %curremaildom;
17493:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
17494:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
17495:                     }
17496:                     foreach my $type (@statuses) {
17497:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
17498:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
17499:                         }
17500:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
17501:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
17502:                         }
17503:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
17504: #
17505: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
17506: #
17507:                             my $chosen = $1;
17508:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
17509:                                 my $emaildom;
17510:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
17511:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
17512:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
17513:                                     if (ref($curremaildom{$type}) eq 'HASH') {
17514:                                         if (exists($curremaildom{$type}{$chosen})) {
17515:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
17516:                                                 push(@{$changes{'cancreate'}},'emaildomain');
17517:                                             }
17518:                                         } elsif ($emaildom ne '') {
17519:                                             push(@{$changes{'cancreate'}},'emaildomain');
17520:                                         }
17521:                                     } elsif ($emaildom ne '') {
17522:                                         push(@{$changes{'cancreate'}},'emaildomain');
17523:                                     } 
17524:                                 }
17525:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
17526:                             } elsif ($chosen eq 'custom') {
17527:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
17528:                                 $email_rule{$type} = [];
17529:                                 if (ref($emailrules) eq 'HASH') {
17530:                                     foreach my $rule (@possemail_rules) {
17531:                                         if (exists($emailrules->{$rule})) {
17532:                                             push(@{$email_rule{$type}},$rule);
17533:                                         }
17534:                                     }
17535:                                 }
17536:                                 if (@{$email_rule{$type}}) {
17537:                                     $cancreate{'emailoptions'}{$type} = 'custom';
17538:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
17539:                                         if (@{$curr_rule{$type}} > 0) {
17540:                                             foreach my $rule (@{$curr_rule{$type}}) {
17541:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
17542:                                                     push(@{$changes{'email_rule'}},$type);
17543:                                                 }
17544:                                             }
17545:                                         }
17546:                                         foreach my $type (@{$email_rule{$type}}) {
17547:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
17548:                                                 push(@{$changes{'email_rule'}},$type);
17549:                                             }
17550:                                         }
17551:                                     } else {
17552:                                         push(@{$changes{'email_rule'}},$type);
17553:                                     }
17554:                                 }
17555:                             } else {
17556:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
17557:                             }
17558:                         }
17559:                     }
17560:                     if (@types) {
17561:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17562:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
17563:                             if (@changed) {
17564:                                 push(@{$changes{'inststatus'}},'inststatusguest');
17565:                             }
17566:                         } else {
17567:                             push(@{$changes{'inststatus'}},'inststatusguest');
17568:                         }
17569:                     }
17570:                 } else {
17571:                     delete($env{'form.cancreate_email'});
17572:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17573:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
17574:                             push(@{$changes{'inststatus'}},'inststatusguest');
17575:                         }
17576:                     }
17577:                 }
17578:             } else {
17579:                 $save_inststatus{'inststatusguest'} = [];
17580:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17581:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
17582:                         push(@{$changes{'inststatus'}},'inststatusguest');
17583:                     }
17584:                 }
17585:             }
17586:         } else {
17587:             if ($env{'form.cancreate_'.$item}) {
17588:                 push(@{$cancreate{'selfcreate'}},$item);
17589:             }
17590:         }
17591:     }
17592:     my (%userinfo,%savecaptcha);
17593:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
17594: #
17595: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
17596: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
17597: #
17598: 
17599:     if ($env{'form.cancreate_email'}) {
17600:         push(@contexts,'emailusername');
17601:         if (@statuses) {
17602:             foreach my $type (@statuses) {
17603:                 if (ref($infofields) eq 'ARRAY') {
17604:                     foreach my $field (@{$infofields}) {
17605:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
17606:                             $cancreate{'emailusername'}{$type}{$field} = $1;
17607:                         }
17608:                     }
17609:                 }
17610:             }
17611:         }
17612: #
17613: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
17614: # queued requests for self-creation of account verified by e-mail.
17615: #
17616: 
17617:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
17618:         @approvalnotify = sort(@approvalnotify);
17619:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
17620:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17621:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
17622:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
17623:                     push(@{$changes{'cancreate'}},'notify');
17624:                 }
17625:             } else {
17626:                 if ($cancreate{'notify'}{'approval'}) {
17627:                     push(@{$changes{'cancreate'}},'notify');
17628:                 }
17629:             }
17630:         } elsif ($cancreate{'notify'}{'approval'}) {
17631:             push(@{$changes{'cancreate'}},'notify');
17632:         }
17633: 
17634:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
17635:     }
17636: #  
17637: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
17638: # institutional log-in.
17639: #
17640:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
17641:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
17642:                ($domdefaults{'auth_def'} eq 'localauth'))) {
17643:             $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.').' '.
17644:                           &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.');
17645:         }
17646:     }
17647:     my @fields = ('lastname','firstname','middlename','generation',
17648:                   'permanentemail','id');
17649:     my @shibfields = (@fields,'inststatus');
17650:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
17651: #
17652: # Where usernames may created for institutional log-in and/or institutional single sign on:
17653: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
17654: # may self-create accounts 
17655: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
17656: # which the user may supply, if institutional data is unavailable.
17657: #
17658:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
17659:         if (@types) {
17660:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
17661:             push(@contexts,'statustocreate');
17662:             foreach my $type (@types) {
17663:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
17664:                 foreach my $field (@fields) {
17665:                     if (grep(/^\Q$field\E$/,@modifiable)) {
17666:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
17667:                     } else {
17668:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
17669:                     }
17670:                 }
17671:             }
17672:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
17673:                 foreach my $type (@types) {
17674:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
17675:                         foreach my $field (@fields) {
17676:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
17677:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
17678:                                 push(@{$changes{'selfcreate'}},$type);
17679:                                 last;
17680:                             }
17681:                         }
17682:                     }
17683:                 }
17684:             } else {
17685:                 foreach my $type (@types) {
17686:                     push(@{$changes{'selfcreate'}},$type);
17687:                 }
17688:             }
17689:         }
17690:         foreach my $field (@shibfields) {
17691:             if ($env{'form.shibenv_'.$field} ne '') {
17692:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
17693:             }
17694:         }
17695:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17696:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
17697:                 foreach my $field (@shibfields) {
17698:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
17699:                         push(@{$changes{'cancreate'}},'shibenv');
17700:                     }
17701:                 }
17702:             } else {
17703:                 foreach my $field (@shibfields) {
17704:                     if ($env{'form.shibenv_'.$field}) {
17705:                         push(@{$changes{'cancreate'}},'shibenv');
17706:                         last;
17707:                     }
17708:                 }
17709:             }
17710:         }
17711:     }
17712:     foreach my $item (@contexts) {
17713:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
17714:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
17715:                 if (ref($cancreate{$item}) eq 'ARRAY') {
17716:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
17717:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17718:                             push(@{$changes{'cancreate'}},$item);
17719:                         }
17720:                     }
17721:                 }
17722:             }
17723:             if (ref($cancreate{$item}) eq 'ARRAY') {
17724:                 foreach my $type (@{$cancreate{$item}}) {
17725:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
17726:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17727:                             push(@{$changes{'cancreate'}},$item);
17728:                         }
17729:                     }
17730:                 }
17731:             }
17732:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
17733:             if (ref($cancreate{$item}) eq 'HASH') {
17734:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
17735:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
17736:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
17737:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
17738:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17739:                                     push(@{$changes{'cancreate'}},$item);
17740:                                 }
17741:                             }
17742:                         }
17743:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17744:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
17745:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17746:                                 push(@{$changes{'cancreate'}},$item);
17747:                             }
17748:                         }
17749:                     }
17750:                 }
17751:                 foreach my $type (keys(%{$cancreate{$item}})) {
17752:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
17753:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
17754:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
17755:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
17756:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17757:                                         push(@{$changes{'cancreate'}},$item);
17758:                                     }
17759:                                 }
17760:                             } else {
17761:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17762:                                     push(@{$changes{'cancreate'}},$item);
17763:                                 }
17764:                             }
17765:                         }
17766:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17767:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
17768:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17769:                                 push(@{$changes{'cancreate'}},$item);
17770:                             }
17771:                         }
17772:                     }
17773:                 }
17774:             }
17775:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
17776:             if (ref($cancreate{$item}) eq 'ARRAY') {
17777:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
17778:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17779:                         push(@{$changes{'cancreate'}},$item);
17780:                     }
17781:                 }
17782:             }
17783:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17784:             if (ref($cancreate{$item}) eq 'HASH') {
17785:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17786:                     push(@{$changes{'cancreate'}},$item);
17787:                 }
17788:             }
17789:         } elsif ($item eq 'emailusername') {
17790:             if (ref($cancreate{$item}) eq 'HASH') {
17791:                 foreach my $type (keys(%{$cancreate{$item}})) {
17792:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
17793:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
17794:                             if ($cancreate{$item}{$type}{$field}) {
17795:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17796:                                     push(@{$changes{'cancreate'}},$item);
17797:                                 }
17798:                                 last;
17799:                             }
17800:                         }
17801:                     }
17802:                 }
17803:             }
17804:         }
17805:     }
17806: #
17807: # Populate %save_usercreate hash with updates to self-creation configuration.
17808: #
17809:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
17810:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
17811:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
17812:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
17813:     if (ref($cancreate{'notify'}) eq 'HASH') {
17814:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
17815:     }
17816:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
17817:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
17818:     }
17819:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
17820:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
17821:     }
17822:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
17823:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
17824:     }
17825:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
17826:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
17827:     }
17828:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
17829:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
17830:     }
17831:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
17832:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
17833:     }
17834:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
17835:     $save_usercreate{'email_rule'} = \%email_rule;
17836: 
17837:     my %userconfig_hash = (
17838:             usercreation     => \%save_usercreate,
17839:             usermodification => \%save_usermodify,
17840:             inststatus       => \%save_inststatus,
17841:     );
17842: 
17843:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
17844:                                              $dom);
17845: #
17846: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
17847: #
17848:     if ($putresult eq 'ok') {
17849:         if (keys(%changes) > 0) {
17850:             $resulttext = &mt('Changes made:').'<ul>';
17851:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
17852:                 my %lt = &selfcreation_types();
17853:                 foreach my $type (@{$changes{'cancreate'}}) {
17854:                     my $chgtext = '';
17855:                     if ($type eq 'selfcreate') {
17856:                         if (@{$cancreate{$type}} == 0) {
17857:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
17858:                         } else {
17859:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
17860:                                         '<ul>';
17861:                             foreach my $case (@{$cancreate{$type}}) {
17862:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
17863:                             }
17864:                             $chgtext .= '</ul>';
17865:                             if (ref($cancreate{$type}) eq 'ARRAY') {
17866:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
17867:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
17868:                                         if (@{$cancreate{'statustocreate'}} == 0) {
17869:                                             $chgtext .= '<span class="LC_warning">'.
17870:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
17871:                                                         '</span><br />';
17872:                                         }
17873:                                     }
17874:                                 }
17875:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
17876:                                     if (!@statuses) {
17877:                                         $chgtext .= '<span class="LC_warning">'.
17878:                                                     &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.").
17879:                                                     '</span><br />';
17880: 
17881:                                     }
17882:                                 }
17883:                             }
17884:                         }
17885:                     } elsif ($type eq 'shibenv') {
17886:                         if (keys(%{$cancreate{$type}}) == 0) {
17887:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
17888:                         } else {
17889:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
17890:                                         '<ul>';
17891:                             foreach my $field (@shibfields) {
17892:                                 next if ($cancreate{$type}{$field} eq '');
17893:                                 if ($field eq 'inststatus') {
17894:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
17895:                                 } else {
17896:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
17897:                                 }
17898:                             }
17899:                             $chgtext .= '</ul>';
17900:                         }
17901:                     } elsif ($type eq 'statustocreate') {
17902:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
17903:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
17904:                             if (@{$cancreate{'selfcreate'}} > 0) {
17905:                                 if (@{$cancreate{'statustocreate'}} == 0) {
17906:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
17907:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
17908:                                         $chgtext .= '<br />'.
17909:                                                     '<span class="LC_warning">'.
17910:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
17911:                                                     '</span>';
17912:                                     }
17913:                                 } elsif (keys(%usertypes) > 0) {
17914:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
17915:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
17916:                                     } else {
17917:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
17918:                                     }
17919:                                     $chgtext .= '<ul>';
17920:                                     foreach my $case (@{$cancreate{$type}}) {
17921:                                         if ($case eq 'default') {
17922:                                             $chgtext .= '<li>'.$othertitle.'</li>';
17923:                                         } else {
17924:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
17925:                                         }
17926:                                     }
17927:                                     $chgtext .= '</ul>';
17928:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
17929:                                         $chgtext .= '<span class="LC_warning">'.
17930:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
17931:                                                     '</span>';
17932:                                     }
17933:                                 }
17934:                             } else {
17935:                                 if (@{$cancreate{$type}} == 0) {
17936:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
17937:                                 } else {
17938:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
17939:                                 }
17940:                             }
17941:                             $chgtext .= '<br />';
17942:                         }
17943:                     } elsif ($type eq 'selfcreateprocessing') {
17944:                         my %choices = &Apache::lonlocal::texthash (
17945:                                                                     automatic => 'Automatic approval',
17946:                                                                     approval  => 'Queued for approval',
17947:                                                                   );
17948:                         if (@types) {
17949:                             if (@statuses) {
17950:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
17951:                                             '<ul>';
17952:                                 foreach my $status (@statuses) {
17953:                                     if ($status eq 'default') {
17954:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
17955:                                     } else {
17956:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
17957:                                     }
17958:                                 }
17959:                                 $chgtext .= '</ul>';
17960:                             }
17961:                         } else {
17962:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
17963:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
17964:                         }
17965:                     } elsif ($type eq 'emailverified') {
17966:                         my %options = &Apache::lonlocal::texthash (
17967:                                                                     all   => 'Same as e-mail',
17968:                                                                     first => 'Omit @domain',
17969:                                                                     free  => 'Free to choose',
17970:                                                                   );
17971:                         if (@types) {
17972:                             if (@statuses) {
17973:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
17974:                                             '<ul>';
17975:                                 foreach my $status (@statuses) {
17976:                                     if ($status eq 'default') {
17977:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
17978:                                     } else {
17979:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
17980:                                     }
17981:                                 }
17982:                                 $chgtext .= '</ul>';
17983:                             }
17984:                         } else {
17985:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
17986:                                             $options{$cancreate{'emailverified'}{'default'}});
17987:                         }
17988:                     } elsif ($type eq 'emailoptions') {
17989:                         my %options = &Apache::lonlocal::texthash (
17990:                                                                     any     => 'Any e-mail',
17991:                                                                     inst    => 'Institutional only',
17992:                                                                     noninst => 'Non-institutional only',
17993:                                                                     custom  => 'Custom restrictions',
17994:                                                                   );
17995:                         if (@types) {
17996:                             if (@statuses) {
17997:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
17998:                                             '<ul>';
17999:                                 foreach my $status (@statuses) {
18000:                                     if ($type eq 'default') {
18001:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
18002:                                     } else {
18003:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
18004:                                     }
18005:                                 }
18006:                                 $chgtext .= '</ul>';
18007:                             }
18008:                         } else {
18009:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
18010:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
18011:                             } else {
18012:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
18013:                                                 $options{$cancreate{'emailoptions'}{'default'}});
18014:                             }
18015:                         }
18016:                     } elsif ($type eq 'emaildomain') {
18017:                         my $output;
18018:                         if (@statuses) {
18019:                             foreach my $type (@statuses) {
18020:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
18021:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
18022:                                         if ($type eq 'default') {
18023:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18024:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
18025:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
18026:                                             } else {
18027:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
18028:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
18029:                                             }
18030:                                         } else {
18031:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18032:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
18033:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
18034:                                             } else {
18035:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
18036:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
18037:                                             }
18038:                                         }
18039:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
18040:                                         if ($type eq 'default') {
18041:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18042:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
18043:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
18044:                                             } else {
18045:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
18046:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
18047:                                             }
18048:                                         } else {
18049:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18050:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
18051:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
18052:                                             } else {
18053:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
18054:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
18055:                                             }
18056:                                         }
18057:                                     }
18058:                                 }
18059:                             }
18060:                         }
18061:                         if ($output ne '') {
18062:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
18063:                                         '<ul>'.$output.'</ul>';
18064:                         }
18065:                     } elsif ($type eq 'captcha') {
18066:                         if ($savecaptcha{$type} eq 'notused') {
18067:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
18068:                         } else {
18069:                             my %captchas = &captcha_phrases();
18070:                             if ($captchas{$savecaptcha{$type}}) {
18071:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
18072:                             } else {
18073:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
18074:                             }
18075:                         }
18076:                     } elsif ($type eq 'recaptchakeys') {
18077:                         my ($privkey,$pubkey);
18078:                         if (ref($savecaptcha{$type}) eq 'HASH') {
18079:                             $pubkey = $savecaptcha{$type}{'public'};
18080:                             $privkey = $savecaptcha{$type}{'private'};
18081:                         }
18082:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
18083:                         if (!$pubkey) {
18084:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
18085:                         } else {
18086:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
18087:                         }
18088:                         if (!$privkey) {
18089:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
18090:                         } else {
18091:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
18092:                         }
18093:                         $chgtext .= '</ul>';
18094:                     } elsif ($type eq 'recaptchaversion') {
18095:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
18096:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
18097:                         }
18098:                     } elsif ($type eq 'emailusername') {
18099:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
18100:                             if (@statuses) {
18101:                                 foreach my $type (@statuses) {
18102:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
18103:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
18104:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
18105:                                                     '<ul>';
18106:                                             foreach my $field (@{$infofields}) {
18107:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
18108:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
18109:                                                 }
18110:                                             }
18111:                                             $chgtext .= '</ul>';
18112:                                         } else {
18113:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
18114:                                         }
18115:                                     } else {
18116:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
18117:                                     }
18118:                                 }
18119:                             }
18120:                         }
18121:                     } elsif ($type eq 'notify') {
18122:                         my $numapprove = 0;
18123:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
18124:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
18125:                                 if ($cancreate{'notify'}{'approval'}) {
18126:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
18127:                                     $numapprove ++;
18128:                                 }
18129:                             }
18130:                         }
18131:                         unless ($numapprove) {
18132:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
18133:                         }
18134:                     }
18135:                     if ($chgtext) {
18136:                         $resulttext .= '<li>'.$chgtext.'</li>';
18137:                     }
18138:                 }
18139:             }
18140:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
18141:                 my ($emailrules,$emailruleorder) =
18142:                     &Apache::lonnet::inst_userrules($dom,'email');
18143:                 foreach my $type (@{$changes{'email_rule'}}) {
18144:                     if (ref($email_rule{$type}) eq 'ARRAY') {
18145:                         my $chgtext = '<ul>';
18146:                         foreach my $rule (@{$email_rule{$type}}) {
18147:                             if (ref($emailrules->{$rule}) eq 'HASH') {
18148:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
18149:                             }
18150:                         }
18151:                         $chgtext .= '</ul>';
18152:                         my $typename;
18153:                         if (@types) {
18154:                             if ($type eq 'default') {
18155:                                 $typename = $othertitle;
18156:                             } else {
18157:                                 $typename = $usertypes{$type};
18158:                             } 
18159:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
18160:                         }
18161:                         if (@{$email_rule{$type}} > 0) {
18162:                             $resulttext .= '<li>'.
18163:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
18164:                                                $usertypes{$type}).
18165:                                            $chgtext.
18166:                                            '</li>';
18167:                         } else {
18168:                             $resulttext .= '<li>'.
18169:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
18170:                                            '</li>'.
18171:                                            &mt('(Affiliation: [_1])',$typename);
18172:                         }
18173:                     }
18174:                 }
18175:             }
18176:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
18177:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
18178:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
18179:                         my $chgtext = '<ul>';
18180:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
18181:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
18182:                         }
18183:                         $chgtext .= '</ul>';
18184:                         $resulttext .= '<li>'.
18185:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
18186:                                           $chgtext.
18187:                                        '</li>';
18188:                     } else {
18189:                         $resulttext .= '<li>'.
18190:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
18191:                                        '</li>';
18192:                     }
18193:                 }
18194:             }
18195:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
18196:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
18197:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
18198:                 foreach my $type (@{$changes{'selfcreate'}}) {
18199:                     my $typename = $type;
18200:                     if (keys(%usertypes) > 0) {
18201:                         if ($usertypes{$type} ne '') {
18202:                             $typename = $usertypes{$type};
18203:                         }
18204:                     }
18205:                     my @modifiable;
18206:                     $resulttext .= '<li>'.
18207:                                     &mt('Self-creation of account by users with status: [_1]',
18208:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
18209:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
18210:                     foreach my $field (@fields) {
18211:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
18212:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
18213:                         }
18214:                     }
18215:                     if (@modifiable > 0) {
18216:                         $resulttext .= join(', ',@modifiable);
18217:                     } else {
18218:                         $resulttext .= &mt('none');
18219:                     }
18220:                     $resulttext .= '</li>';
18221:                 }
18222:                 $resulttext .= '</ul></li>';
18223:             }
18224:             $resulttext .= '</ul>';
18225:             my $cachetime = 24*60*60;
18226:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
18227:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18228:             if (ref($lastactref) eq 'HASH') {
18229:                 $lastactref->{'domdefaults'} = 1;
18230:             }
18231:         } else {
18232:             $resulttext = &mt('No changes made to self-creation settings');
18233:         }
18234:     } else {
18235:         $resulttext = '<span class="LC_error">'.
18236:             &mt('An error occurred: [_1]',$putresult).'</span>';
18237:     }
18238:     if ($warningmsg ne '') {
18239:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
18240:     }
18241:     return $resulttext;
18242: }
18243: 
18244: sub process_captcha {
18245:     my ($container,$changes,$newsettings,$currsettings) = @_;
18246:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
18247:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
18248:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
18249:         $newsettings->{'captcha'} = 'original';
18250:     }
18251:     my %current;
18252:     if (ref($currsettings) eq 'HASH') {
18253:         %current = %{$currsettings};
18254:     }
18255:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
18256:         if ($container eq 'cancreate') {
18257:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
18258:                 push(@{$changes->{'cancreate'}},'captcha');
18259:             } elsif (!defined($changes->{'cancreate'})) {
18260:                 $changes->{'cancreate'} = ['captcha'];
18261:             }
18262:         } elsif ($container eq 'passwords') {
18263:             $changes->{'reset'} = 1;
18264:         } else {
18265:             $changes->{'captcha'} = 1;
18266:         }
18267:     }
18268:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
18269:     if ($newsettings->{'captcha'} eq 'recaptcha') {
18270:         $newpub = $env{'form.'.$container.'_recaptchapub'};
18271:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
18272:         $newpub =~ s/[^\w\-]//g;
18273:         $newpriv =~ s/[^\w\-]//g;
18274:         $newsettings->{'recaptchakeys'} = {
18275:                                              public  => $newpub,
18276:                                              private => $newpriv,
18277:                                           };
18278:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
18279:         $newversion =~ s/\D//g;
18280:         if ($newversion ne '2') {
18281:             $newversion = 1;
18282:         }
18283:         $newsettings->{'recaptchaversion'} = $newversion;
18284:     }
18285:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
18286:         $currpub = $current{'recaptchakeys'}{'public'};
18287:         $currpriv = $current{'recaptchakeys'}{'private'};
18288:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
18289:             $newsettings->{'recaptchakeys'} = {
18290:                                                  public  => '',
18291:                                                  private => '',
18292:                                               }
18293:         }
18294:     }
18295:     if ($current{'captcha'} eq 'recaptcha') {
18296:         $currversion = $current{'recaptchaversion'};
18297:         if ($currversion ne '2') {
18298:             $currversion = 1;
18299:         }
18300:     }
18301:     if ($currversion ne $newversion) {
18302:         if ($container eq 'cancreate') {
18303:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
18304:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
18305:             } elsif (!defined($changes->{'cancreate'})) {
18306:                 $changes->{'cancreate'} = ['recaptchaversion'];
18307:             }
18308:         } elsif ($container eq 'passwords') {
18309:             $changes->{'reset'} = 1;
18310:         } else {
18311:             $changes->{'recaptchaversion'} = 1;
18312:         }
18313:     }
18314:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
18315:         if ($container eq 'cancreate') {
18316:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
18317:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
18318:             } elsif (!defined($changes->{'cancreate'})) {
18319:                 $changes->{'cancreate'} = ['recaptchakeys'];
18320:             }
18321:         } elsif ($container eq 'passwords') {
18322:             $changes->{'reset'} = 1;
18323:         } else {
18324:             $changes->{'recaptchakeys'} = 1;
18325:         }
18326:     }
18327:     return;
18328: }
18329: 
18330: sub modify_usermodification {
18331:     my ($dom,%domconfig) = @_;
18332:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
18333:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
18334:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
18335:             if ($key eq 'selfcreate') {
18336:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
18337:             } else {  
18338:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
18339:             }
18340:         }
18341:     }
18342:     my @contexts = ('author','course');
18343:     my %context_title = (
18344:                            author => 'In author context',
18345:                            course => 'In course context',
18346:                         );
18347:     my @fields = ('lastname','firstname','middlename','generation',
18348:                   'permanentemail','id');
18349:     my %roles = (
18350:                   author => ['ca','aa'],
18351:                   course => ['st','ep','ta','in','cr'],
18352:                 );
18353:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
18354:     foreach my $context (@contexts) {
18355:         foreach my $role (@{$roles{$context}}) {
18356:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
18357:             foreach my $item (@fields) {
18358:                 if (grep(/^\Q$item\E$/,@modifiable)) {
18359:                     $modifyhash{$context}{$role}{$item} = 1;
18360:                 } else {
18361:                     $modifyhash{$context}{$role}{$item} = 0;
18362:                 }
18363:             }
18364:         }
18365:         if (ref($curr_usermodification{$context}) eq 'HASH') {
18366:             foreach my $role (@{$roles{$context}}) {
18367:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
18368:                     foreach my $field (@fields) {
18369:                         if ($modifyhash{$context}{$role}{$field} ne 
18370:                                 $curr_usermodification{$context}{$role}{$field}) {
18371:                             push(@{$changes{$context}},$role);
18372:                             last;
18373:                         }
18374:                     }
18375:                 }
18376:             }
18377:         } else {
18378:             foreach my $context (@contexts) {
18379:                 foreach my $role (@{$roles{$context}}) {
18380:                     push(@{$changes{$context}},$role);
18381:                 }
18382:             }
18383:         }
18384:     }
18385:     my %usermodification_hash =  (
18386:                                    usermodification => \%modifyhash,
18387:                                  );
18388:     my $putresult = &Apache::lonnet::put_dom('configuration',
18389:                                              \%usermodification_hash,$dom);
18390:     if ($putresult eq 'ok') {
18391:         if (keys(%changes) > 0) {
18392:             $resulttext = &mt('Changes made: ').'<ul>';
18393:             foreach my $context (@contexts) {
18394:                 if (ref($changes{$context}) eq 'ARRAY') {
18395:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
18396:                     if (ref($changes{$context}) eq 'ARRAY') {
18397:                         foreach my $role (@{$changes{$context}}) {
18398:                             my $rolename;
18399:                             if ($role eq 'cr') {
18400:                                 $rolename = &mt('Custom');
18401:                             } else {
18402:                                 $rolename = &Apache::lonnet::plaintext($role);
18403:                             }
18404:                             my @modifiable;
18405:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
18406:                             foreach my $field (@fields) {
18407:                                 if ($modifyhash{$context}{$role}{$field}) {
18408:                                     push(@modifiable,$fieldtitles{$field});
18409:                                 }
18410:                             }
18411:                             if (@modifiable > 0) {
18412:                                 $resulttext .= join(', ',@modifiable);
18413:                             } else {
18414:                                 $resulttext .= &mt('none'); 
18415:                             }
18416:                             $resulttext .= '</li>';
18417:                         }
18418:                         $resulttext .= '</ul></li>';
18419:                     }
18420:                 }
18421:             }
18422:             $resulttext .= '</ul>';
18423:         } else {
18424:             $resulttext = &mt('No changes made to user modification settings');
18425:         }
18426:     } else {
18427:         $resulttext = '<span class="LC_error">'.
18428:             &mt('An error occurred: [_1]',$putresult).'</span>';
18429:     }
18430:     return $resulttext;
18431: }
18432: 
18433: sub modify_defaults {
18434:     my ($dom,$lastactref,%domconfig) = @_;
18435:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
18436:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18437:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
18438:                  'portal_def');
18439:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
18440:     foreach my $item (@items) {
18441:         $newvalues{$item} = $env{'form.'.$item};
18442:         if ($item eq 'auth_def') {
18443:             if ($newvalues{$item} ne '') {
18444:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
18445:                     push(@errors,$item);
18446:                 }
18447:             }
18448:         } elsif ($item eq 'lang_def') {
18449:             if ($newvalues{$item} ne '') {
18450:                 if ($newvalues{$item} =~ /^(\w+)/) {
18451:                     my $langcode = $1;
18452:                     if ($langcode ne 'x_chef') {
18453:                         if (code2language($langcode) eq '') {
18454:                             push(@errors,$item);
18455:                         }
18456:                     }
18457:                 } else {
18458:                     push(@errors,$item);
18459:                 }
18460:             }
18461:         } elsif ($item eq 'timezone_def') {
18462:             if ($newvalues{$item} ne '') {
18463:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
18464:                     push(@errors,$item);   
18465:                 }
18466:             }
18467:         } elsif ($item eq 'datelocale_def') {
18468:             if ($newvalues{$item} ne '') {
18469:                 my @datelocale_ids = DateTime::Locale->ids();
18470:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
18471:                     push(@errors,$item);
18472:                 }
18473:             }
18474:         } elsif ($item eq 'portal_def') {
18475:             if ($newvalues{$item} ne '') {
18476:                 unless ($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])\/?$/) {
18477:                     push(@errors,$item);
18478:                 }
18479:             }
18480:         }
18481:         if (grep(/^\Q$item\E$/,@errors)) {
18482:             $newvalues{$item} = $domdefaults{$item};
18483:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
18484:             $changes{$item} = 1;
18485:         }
18486:         $domdefaults{$item} = $newvalues{$item};
18487:     }
18488:     my %staticdefaults = (
18489:                            'intauth_cost'   => 10,
18490:                            'intauth_check'  => 0,
18491:                            'intauth_switch' => 0,
18492:                          );
18493:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
18494:         if (exists($domdefaults{$item})) {
18495:             $newvalues{$item} = $domdefaults{$item};
18496:         } else {
18497:             $newvalues{$item} = $staticdefaults{$item};
18498:         }
18499:     }
18500:     my %defaults_hash = (
18501:                          defaults => \%newvalues,
18502:                         );
18503:     my $title = &defaults_titles();
18504: 
18505:     my $currinststatus;
18506:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18507:         $currinststatus = $domconfig{'inststatus'};
18508:     } else {
18509:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18510:         $currinststatus = {
18511:                              inststatustypes => $usertypes,
18512:                              inststatusorder => $types,
18513:                              inststatusguest => [],
18514:                           };
18515:     }
18516:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
18517:     my @allpos;
18518:     my %alltypes;
18519:     my @inststatusguest;
18520:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
18521:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
18522:             unless (grep(/^\Q$type\E$/,@todelete)) {
18523:                 push(@inststatusguest,$type);
18524:             }
18525:         }
18526:     }
18527:     my ($currtitles,$currorder);
18528:     if (ref($currinststatus) eq 'HASH') {
18529:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
18530:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
18531:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
18532:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
18533:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
18534:                     }
18535:                 }
18536:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
18537:                     my $position = $env{'form.inststatus_pos_'.$type};
18538:                     $position =~ s/\D+//g;
18539:                     $allpos[$position] = $type;
18540:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
18541:                     $alltypes{$type} =~ s/`//g;
18542:                 }
18543:             }
18544:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
18545:             $currtitles =~ s/,$//;
18546:         }
18547:     }
18548:     if ($env{'form.addinststatus'}) {
18549:         my $newtype = $env{'form.addinststatus'};
18550:         $newtype =~ s/\W//g;
18551:         unless (exists($alltypes{$newtype})) {
18552:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
18553:             $alltypes{$newtype} =~ s/`//g; 
18554:             my $position = $env{'form.addinststatus_pos'};
18555:             $position =~ s/\D+//g;
18556:             if ($position ne '') {
18557:                 $allpos[$position] = $newtype;
18558:             }
18559:         }
18560:     }
18561:     my @orderedstatus;
18562:     foreach my $type (@allpos) {
18563:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
18564:             push(@orderedstatus,$type);
18565:         }
18566:     }
18567:     foreach my $type (keys(%alltypes)) {
18568:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
18569:             delete($alltypes{$type});
18570:         }
18571:     }
18572:     $defaults_hash{'inststatus'} = {
18573:                                      inststatustypes => \%alltypes,
18574:                                      inststatusorder => \@orderedstatus,
18575:                                      inststatusguest => \@inststatusguest,
18576:                                    };
18577:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
18578:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
18579:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
18580:         }
18581:     }
18582:     if ($currorder ne join(',',@orderedstatus)) {
18583:         $changes{'inststatus'}{'inststatusorder'} = 1;
18584:     }
18585:     my $newtitles;
18586:     foreach my $item (@orderedstatus) {
18587:         $newtitles .= $alltypes{$item}.',';
18588:     }
18589:     $newtitles =~ s/,$//;
18590:     if ($currtitles ne $newtitles) {
18591:         $changes{'inststatus'}{'inststatustypes'} = 1;
18592:     }
18593:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
18594:                                              $dom);
18595:     if ($putresult eq 'ok') {
18596:         if (keys(%changes) > 0) {
18597:             $resulttext = &mt('Changes made:').'<ul>';
18598:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
18599:             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";
18600:             foreach my $item (sort(keys(%changes))) {
18601:                 if ($item eq 'inststatus') {
18602:                     if (ref($changes{'inststatus'}) eq 'HASH') {
18603:                         if (@orderedstatus) {
18604:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
18605:                             foreach my $type (@orderedstatus) { 
18606:                                 $resulttext .= $alltypes{$type}.', ';
18607:                             }
18608:                             $resulttext =~ s/, $//;
18609:                             $resulttext .= '</li>';
18610:                         } else {
18611:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
18612:                         }
18613:                     }
18614:                 } else {
18615:                     my $value = $env{'form.'.$item};
18616:                     if ($value eq '') {
18617:                         $value = &mt('none');
18618:                     } elsif ($item eq 'auth_def') {
18619:                         my %authnames = &authtype_names();
18620:                         my %shortauth = (
18621:                                           internal   => 'int',
18622:                                           krb4       => 'krb4',
18623:                                           krb5       => 'krb5',
18624:                                           localauth  => 'loc',
18625:                                           lti        => 'lti',
18626:                         );
18627:                         $value = $authnames{$shortauth{$value}};
18628:                     }
18629:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
18630:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
18631:                 }
18632:             }
18633:             $resulttext .= '</ul>';
18634:             $mailmsgtext .= "\n";
18635:             my $cachetime = 24*60*60;
18636:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18637:             if (ref($lastactref) eq 'HASH') {
18638:                 $lastactref->{'domdefaults'} = 1;
18639:             }
18640:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
18641:                 my $notify = 1;
18642:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
18643:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
18644:                         $notify = 0;
18645:                     }
18646:                 }
18647:                 if ($notify) {
18648:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
18649:                                                "LON-CAPA Domain Settings Change - $dom",
18650:                                                $mailmsgtext);
18651:                 }
18652:             }
18653:         } else {
18654:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
18655:         }
18656:     } else {
18657:         $resulttext = '<span class="LC_error">'.
18658:             &mt('An error occurred: [_1]',$putresult).'</span>';
18659:     }
18660:     if (@errors > 0) {
18661:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
18662:         foreach my $item (@errors) {
18663:             $resulttext .= ' "'.$title->{$item}.'",';
18664:         }
18665:         $resulttext =~ s/,$//;
18666:     }
18667:     return $resulttext;
18668: }
18669: 
18670: sub modify_scantron {
18671:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18672:     my ($resulttext,%confhash,%changes,$errors);
18673:     my $custom = 'custom.tab';
18674:     my $default = 'default.tab';
18675:     my $servadm = $r->dir_config('lonAdmEMail');
18676:     my ($configuserok,$author_ok,$switchserver) =
18677:         &config_check($dom,$confname,$servadm);
18678:     if ($env{'form.scantronformat.filename'} ne '') {
18679:         my $error;
18680:         if ($configuserok eq 'ok') {
18681:             if ($switchserver) {
18682:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
18683:             } else {
18684:                 if ($author_ok eq 'ok') {
18685:                     my ($result,$scantronurl) =
18686:                         &publishlogo($r,'upload','scantronformat',$dom,
18687:                                      $confname,'scantron','','',$custom);
18688:                     if ($result eq 'ok') {
18689:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
18690:                         $changes{'scantronformat'} = 1;
18691:                     } else {
18692:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
18693:                     }
18694:                 } else {
18695:                     $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);
18696:                 }
18697:             }
18698:         } else {
18699:             $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);
18700:         }
18701:         if ($error) {
18702:             &Apache::lonnet::logthis($error);
18703:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18704:         }
18705:     }
18706:     if (ref($domconfig{'scantron'}) eq 'HASH') {
18707:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
18708:             if ($env{'form.scantronformat_del'}) {
18709:                 $confhash{'scantron'}{'scantronformat'} = '';
18710:                 $changes{'scantronformat'} = 1;
18711:             } else {
18712:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
18713:             }
18714:         }
18715:     }
18716:     my @options = ('hdr','pad','rem');
18717:     my @fields = &scantroncsv_fields();
18718:     my %titles = &scantronconfig_titles();
18719:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
18720:     my ($newdat,$currdat,%newcol,%currcol);
18721:     if (grep(/^dat$/,@formats)) {
18722:         $confhash{'scantron'}{config}{dat} = 1;
18723:         $newdat = 1;
18724:     } else {
18725:         $newdat = 0;
18726:     }
18727:     if (grep(/^csv$/,@formats)) {
18728:         my %bynum;
18729:         foreach my $field (@fields) {
18730:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
18731:                 my $posscol = $1;
18732:                 if (($posscol < 20) && (!$bynum{$posscol})) {
18733:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
18734:                     $bynum{$posscol} = $field;
18735:                     $newcol{$field} = $posscol;
18736:                 }
18737:             }
18738:         }
18739:         if (keys(%newcol)) {
18740:             foreach my $option (@options) {
18741:                 if ($env{'form.scantroncsv_'.$option}) {
18742:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
18743:                 }
18744:             }
18745:         }
18746:     }
18747:     $currdat = 1;
18748:     if (ref($domconfig{'scantron'}) eq 'HASH') {
18749:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
18750:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
18751:                 $currdat = 0;
18752:             }
18753:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
18754:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
18755:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
18756:                 }
18757:             }
18758:         }
18759:     }
18760:     if ($currdat != $newdat) {
18761:         $changes{'config'} = 1;
18762:     } else {
18763:         foreach my $field (@fields) {
18764:             if ($currcol{$field} ne '') {
18765:                 if ($currcol{$field} ne $newcol{$field}) {
18766:                     $changes{'config'} = 1;
18767:                     last;
18768:                 }
18769:             } elsif ($newcol{$field} ne '') {
18770:                 $changes{'config'} = 1;
18771:                 last;
18772:             }
18773:         }
18774:     }
18775:     if (keys(%confhash) > 0) {
18776:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
18777:                                                  $dom);
18778:         if ($putresult eq 'ok') {
18779:             if (keys(%changes) > 0) {
18780:                 if (ref($confhash{'scantron'}) eq 'HASH') {
18781:                     $resulttext = &mt('Changes made:').'<ul>';
18782:                     if ($changes{'scantronformat'}) {
18783:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
18784:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
18785:                         } else {
18786:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
18787:                         }
18788:                     }
18789:                     if ($changes{'config'}) {
18790:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
18791:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
18792:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
18793:                             }
18794:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
18795:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
18796:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
18797:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
18798:                                         foreach my $field (@fields) {
18799:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
18800:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
18801:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
18802:                                             }
18803:                                         }
18804:                                         $resulttext .= '</ul></li>';
18805:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
18806:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
18807:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
18808:                                                 foreach my $option (@options) {
18809:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
18810:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
18811:                                                     }
18812:                                                 }
18813:                                                 $resulttext .= '</ul></li>';
18814:                                             }
18815:                                         }
18816:                                     }
18817:                                 }
18818:                             }
18819:                         } else {
18820:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
18821:                         }
18822:                     }
18823:                     $resulttext .= '</ul>';
18824:                 } else {
18825:                     $resulttext = &mt('Changes made to bubblesheet format file.');
18826:                 }
18827:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
18828:                 if (ref($lastactref) eq 'HASH') {
18829:                     $lastactref->{'domainconfig'} = 1;
18830:                 }
18831:             } else {
18832:                 $resulttext = &mt('No changes made to bubblesheet format settings');
18833:             }
18834:         } else {
18835:             $resulttext = '<span class="LC_error">'.
18836:                 &mt('An error occurred: [_1]',$putresult).'</span>';
18837:         }
18838:     } else {
18839:         $resulttext = &mt('No changes made to bubblesheet format file'); 
18840:     }
18841:     if ($errors) {
18842:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18843:                        $errors.'</ul></p>';
18844:     }
18845:     return $resulttext;
18846: }
18847: 
18848: sub modify_coursecategories {
18849:     my ($dom,$lastactref,%domconfig) = @_;
18850:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
18851:         $cathash);
18852:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
18853:     my @catitems = ('unauth','auth');
18854:     my @cattypes = ('std','domonly','codesrch','none');
18855:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
18856:         $cathash = $domconfig{'coursecategories'}{'cats'};
18857:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
18858:             $changes{'togglecats'} = 1;
18859:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
18860:         }
18861:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
18862:             $changes{'categorize'} = 1;
18863:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
18864:         }
18865:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
18866:             $changes{'togglecatscomm'} = 1;
18867:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
18868:         }
18869:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
18870:             $changes{'categorizecomm'} = 1;
18871:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
18872: 
18873:         }
18874:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
18875:             $changes{'togglecatsplace'} = 1;
18876:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
18877:         }
18878:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
18879:             $changes{'categorizeplace'} = 1;
18880:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
18881:         }
18882:         foreach my $item (@catitems) {
18883:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
18884:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
18885:                     $changes{$item} = 1;
18886:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
18887:                 }
18888:             }
18889:         }
18890:     } else {
18891:         $changes{'togglecats'} = 1;
18892:         $changes{'categorize'} = 1;
18893:         $changes{'togglecatscomm'} = 1;
18894:         $changes{'categorizecomm'} = 1;
18895:         $changes{'togglecatsplace'} = 1;
18896:         $changes{'categorizeplace'} = 1;
18897:         $domconfig{'coursecategories'} = {
18898:                                              togglecats => $env{'form.togglecats'},
18899:                                              categorize => $env{'form.categorize'},
18900:                                              togglecatscomm => $env{'form.togglecatscomm'},
18901:                                              categorizecomm => $env{'form.categorizecomm'},
18902:                                              togglecatsplace => $env{'form.togglecatsplace'},
18903:                                              categorizeplace => $env{'form.categorizeplace'},
18904:                                          };
18905:         foreach my $item (@catitems) {
18906:             if ($env{'form.coursecat_'.$item} ne 'std') {
18907:                 $changes{$item} = 1;
18908:             }
18909:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
18910:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
18911:             }
18912:         }
18913:     }
18914:     if (ref($cathash) eq 'HASH') {
18915:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
18916:             push (@deletecategory,'instcode::0');
18917:         }
18918:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
18919:             push(@deletecategory,'communities::0');
18920:         }
18921:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
18922:             push(@deletecategory,'placement::0');
18923:         }
18924:     }
18925:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
18926:     if (ref($cathash) eq 'HASH') {
18927:         if (@deletecategory > 0) {
18928:             #FIXME Need to remove category from all courses using a deleted category 
18929:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
18930:             foreach my $item (@deletecategory) {
18931:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
18932:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
18933:                     $deletions{$item} = 1;
18934:                     &recurse_cat_deletes($item,$cathash,\%deletions);
18935:                 }
18936:             }
18937:         }
18938:         foreach my $item (keys(%{$cathash})) {
18939:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
18940:             if ($cathash->{$item} ne $env{'form.'.$item}) {
18941:                 $reorderings{$item} = 1;
18942:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
18943:             }
18944:             if ($env{'form.addcategory_name_'.$item} ne '') {
18945:                 my $newcat = $env{'form.addcategory_name_'.$item};
18946:                 my $newdepth = $depth+1;
18947:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
18948:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
18949:                 $adds{$newitem} = 1; 
18950:             }
18951:             if ($env{'form.subcat_'.$item} ne '') {
18952:                 my $newcat = $env{'form.subcat_'.$item};
18953:                 my $newdepth = $depth+1;
18954:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
18955:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
18956:                 $adds{$newitem} = 1;
18957:             }
18958:         }
18959:     }
18960:     if ($env{'form.instcode'} eq '1') {
18961:         if (ref($cathash) eq 'HASH') {
18962:             my $newitem = 'instcode::0';
18963:             if ($cathash->{$newitem} eq '') {  
18964:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
18965:                 $adds{$newitem} = 1;
18966:             }
18967:         } else {
18968:             my $newitem = 'instcode::0';
18969:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
18970:             $adds{$newitem} = 1;
18971:         }
18972:     }
18973:     if ($env{'form.communities'} eq '1') {
18974:         if (ref($cathash) eq 'HASH') {
18975:             my $newitem = 'communities::0';
18976:             if ($cathash->{$newitem} eq '') {
18977:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
18978:                 $adds{$newitem} = 1;
18979:             }
18980:         } else {
18981:             my $newitem = 'communities::0';
18982:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
18983:             $adds{$newitem} = 1;
18984:         }
18985:     }
18986:     if ($env{'form.placement'} eq '1') {
18987:         if (ref($cathash) eq 'HASH') {
18988:             my $newitem = 'placement::0';
18989:             if ($cathash->{$newitem} eq '') {
18990:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
18991:                 $adds{$newitem} = 1;
18992:             }
18993:         } else {
18994:             my $newitem = 'placement::0';
18995:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
18996:             $adds{$newitem} = 1;
18997:         }
18998:     }
18999:     if ($env{'form.addcategory_name'} ne '') {
19000:         if (($env{'form.addcategory_name'} ne 'instcode') &&
19001:             ($env{'form.addcategory_name'} ne 'communities') &&
19002:             ($env{'form.addcategory_name'} ne 'placement')) {
19003:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
19004:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
19005:             $adds{$newitem} = 1;
19006:         }
19007:     }
19008:     my $putresult;
19009:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19010:         if (keys(%deletions) > 0) {
19011:             foreach my $key (keys(%deletions)) {
19012:                 if ($predelallitems{$key} ne '') {
19013:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
19014:                 }
19015:             }
19016:         }
19017:         my (@chkcats,@chktrails,%chkallitems);
19018:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
19019:         if (ref($chkcats[0]) eq 'ARRAY') {
19020:             my $depth = 0;
19021:             my $chg = 0;
19022:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
19023:                 my $name = $chkcats[0][$i];
19024:                 my $item;
19025:                 if ($name eq '') {
19026:                     $chg ++;
19027:                 } else {
19028:                     $item = &escape($name).'::0';
19029:                     if ($chg) {
19030:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
19031:                     }
19032:                     $depth ++; 
19033:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
19034:                     $depth --;
19035:                 }
19036:             }
19037:         }
19038:     }
19039:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19040:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
19041:         if ($putresult eq 'ok') {
19042:             my %title = (
19043:                          togglecats     => 'Show/Hide a course in catalog',
19044:                          categorize     => 'Assign a category to a course',
19045:                          togglecatscomm => 'Show/Hide a community in catalog',
19046:                          categorizecomm => 'Assign a category to a community',
19047:                         );
19048:             my %level = (
19049:                          dom  => 'set in Domain ("Modify Course/Community")',
19050:                          crs  => 'set in Course ("Course Configuration")',
19051:                          comm => 'set in Community ("Community Configuration")',
19052:                          none     => 'No catalog',
19053:                          std      => 'Standard catalog',
19054:                          domonly  => 'Domain-only catalog',
19055:                          codesrch => 'Code search form',
19056:                         );
19057:             $resulttext = &mt('Changes made:').'<ul>';
19058:             if ($changes{'togglecats'}) {
19059:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
19060:             }
19061:             if ($changes{'categorize'}) {
19062:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
19063:             }
19064:             if ($changes{'togglecatscomm'}) {
19065:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
19066:             }
19067:             if ($changes{'categorizecomm'}) {
19068:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
19069:             }
19070:             if ($changes{'unauth'}) {
19071:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
19072:             }
19073:             if ($changes{'auth'}) {
19074:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
19075:             }
19076:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19077:                 my $cathash;
19078:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
19079:                     $cathash = $domconfig{'coursecategories'}{'cats'};
19080:                 } else {
19081:                     $cathash = {};
19082:                 } 
19083:                 my (@cats,@trails,%allitems);
19084:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
19085:                 if (keys(%deletions) > 0) {
19086:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
19087:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
19088:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
19089:                     }
19090:                     $resulttext .= '</ul></li>';
19091:                 }
19092:                 if (keys(%reorderings) > 0) {
19093:                     my %sort_by_trail;
19094:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
19095:                     foreach my $key (keys(%reorderings)) {
19096:                         if ($allitems{$key} ne '') {
19097:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
19098:                         }
19099:                     }
19100:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
19101:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
19102:                     }
19103:                     $resulttext .= '</ul></li>';
19104:                 }
19105:                 if (keys(%adds) > 0) {
19106:                     my %sort_by_trail;
19107:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
19108:                     foreach my $key (keys(%adds)) {
19109:                         if ($allitems{$key} ne '') {
19110:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
19111:                         }
19112:                     }
19113:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
19114:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
19115:                     }
19116:                     $resulttext .= '</ul></li>';
19117:                 }
19118:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
19119:                 if (ref($lastactref) eq 'HASH') {
19120:                     $lastactref->{'cats'} = 1;
19121:                 }
19122:             }
19123:             $resulttext .= '</ul>';
19124:             if ($changes{'unauth'} || $changes{'auth'}) {
19125:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
19126:                 if ($changes{'auth'}) {
19127:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
19128:                 }
19129:                 if ($changes{'unauth'}) {
19130:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
19131:                 }
19132:                 my $cachetime = 24*60*60;
19133:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19134:                 if (ref($lastactref) eq 'HASH') {
19135:                     $lastactref->{'domdefaults'} = 1;
19136:                 }
19137:             }
19138:         } else {
19139:             $resulttext = '<span class="LC_error">'.
19140:                           &mt('An error occurred: [_1]',$putresult).'</span>';
19141:         }
19142:     } else {
19143:         $resulttext = &mt('No changes made to course and community categories');
19144:     }
19145:     return $resulttext;
19146: }
19147: 
19148: sub modify_serverstatuses {
19149:     my ($dom,%domconfig) = @_;
19150:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
19151:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
19152:         %currserverstatus = %{$domconfig{'serverstatuses'}};
19153:     }
19154:     my @pages = &serverstatus_pages();
19155:     foreach my $type (@pages) {
19156:         $newserverstatus{$type}{'namedusers'} = '';
19157:         $newserverstatus{$type}{'machines'} = '';
19158:         if (defined($env{'form.'.$type.'_namedusers'})) {
19159:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
19160:             my @okusers;
19161:             foreach my $user (@users) {
19162:                 my ($uname,$udom) = split(/:/,$user);
19163:                 if (($udom =~ /^$match_domain$/) &&   
19164:                     (&Apache::lonnet::domain($udom)) &&
19165:                     ($uname =~ /^$match_username$/)) {
19166:                     if (!grep(/^\Q$user\E/,@okusers)) {
19167:                         push(@okusers,$user);
19168:                     }
19169:                 }
19170:             }
19171:             if (@okusers > 0) {
19172:                  @okusers = sort(@okusers);
19173:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
19174:             }
19175:         }
19176:         if (defined($env{'form.'.$type.'_machines'})) {
19177:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
19178:             my @okmachines;
19179:             foreach my $ip (@machines) {
19180:                 my @parts = split(/\./,$ip);
19181:                 next if (@parts < 4);
19182:                 my $badip = 0;
19183:                 for (my $i=0; $i<4; $i++) {
19184:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
19185:                         $badip = 1;
19186:                         last;
19187:                     }
19188:                 }
19189:                 if (!$badip) {
19190:                     push(@okmachines,$ip);     
19191:                 }
19192:             }
19193:             @okmachines = sort(@okmachines);
19194:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
19195:         }
19196:     }
19197:     my %serverstatushash =  (
19198:                                 serverstatuses => \%newserverstatus,
19199:                             );
19200:     foreach my $type (@pages) {
19201:         foreach my $setting ('namedusers','machines') {
19202:             my (@current,@new);
19203:             if (ref($currserverstatus{$type}) eq 'HASH') {
19204:                 if ($currserverstatus{$type}{$setting} ne '') { 
19205:                     @current = split(/,/,$currserverstatus{$type}{$setting});
19206:                 }
19207:             }
19208:             if ($newserverstatus{$type}{$setting} ne '') {
19209:                 @new = split(/,/,$newserverstatus{$type}{$setting});
19210:             }
19211:             if (@current > 0) {
19212:                 if (@new > 0) {
19213:                     foreach my $item (@current) {
19214:                         if (!grep(/^\Q$item\E$/,@new)) {
19215:                             $changes{$type}{$setting} = 1;
19216:                             last;
19217:                         }
19218:                     }
19219:                     foreach my $item (@new) {
19220:                         if (!grep(/^\Q$item\E$/,@current)) {
19221:                             $changes{$type}{$setting} = 1;
19222:                             last;
19223:                         }
19224:                     }
19225:                 } else {
19226:                     $changes{$type}{$setting} = 1;
19227:                 }
19228:             } elsif (@new > 0) {
19229:                 $changes{$type}{$setting} = 1;
19230:             }
19231:         }
19232:     }
19233:     if (keys(%changes) > 0) {
19234:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
19235:         my $putresult = &Apache::lonnet::put_dom('configuration',
19236:                                                  \%serverstatushash,$dom);
19237:         if ($putresult eq 'ok') {
19238:             $resulttext .= &mt('Changes made:').'<ul>';
19239:             foreach my $type (@pages) {
19240:                 if (ref($changes{$type}) eq 'HASH') {
19241:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
19242:                     if ($changes{$type}{'namedusers'}) {
19243:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
19244:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
19245:                         } else {
19246:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
19247:                         }
19248:                     }
19249:                     if ($changes{$type}{'machines'}) {
19250:                         if ($newserverstatus{$type}{'machines'} eq '') {
19251:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
19252:                         } else {
19253:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
19254:                         }
19255: 
19256:                     }
19257:                     $resulttext .= '</ul></li>';
19258:                 }
19259:             }
19260:             $resulttext .= '</ul>';
19261:         } else {
19262:             $resulttext = '<span class="LC_error">'.
19263:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
19264: 
19265:         }
19266:     } else {
19267:         $resulttext = &mt('No changes made to access to server status pages');
19268:     }
19269:     return $resulttext;
19270: }
19271: 
19272: sub modify_helpsettings {
19273:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
19274:     my ($resulttext,$errors,%changes,%helphash);
19275:     my %defaultchecked = ('submitbugs' => 'on');
19276:     my @offon = ('off','on');
19277:     my @toggles = ('submitbugs');
19278:     my %current = ('submitbugs' => '',
19279:                    'adhoc'      => {},
19280:                   );
19281:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
19282:         %current = %{$domconfig{'helpsettings'}};
19283:     }
19284:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19285:     foreach my $item (@toggles) {
19286:         if ($defaultchecked{$item} eq 'on') { 
19287:             if ($current{$item} eq '') {
19288:                 if ($env{'form.'.$item} eq '0') {
19289:                     $changes{$item} = 1;
19290:                 }
19291:             } elsif ($current{$item} ne $env{'form.'.$item}) {
19292:                 $changes{$item} = 1;
19293:             }
19294:         } elsif ($defaultchecked{$item} eq 'off') {
19295:             if ($current{$item} eq '') {
19296:                 if ($env{'form.'.$item} eq '1') {
19297:                     $changes{$item} = 1;
19298:                 }
19299:             } elsif ($current{$item} ne $env{'form.'.$item}) {
19300:                 $changes{$item} = 1;
19301:             }
19302:         }
19303:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
19304:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
19305:         }
19306:     }
19307:     my $maxnum = $env{'form.helproles_maxnum'};
19308:     my $confname = $dom.'-domainconfig';
19309:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
19310:     my (@allpos,%newsettings,%changedprivs,$newrole);
19311:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
19312:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
19313:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
19314:     my %lt = &Apache::lonlocal::texthash(
19315:                     s      => 'system',
19316:                     d      => 'domain',
19317:                     order  => 'Display order',
19318:                     access => 'Role usage',
19319:                     all    => 'All with domain helpdesk or helpdesk assistant role',
19320:                     dh     => 'All with domain helpdesk role',
19321:                     da     => 'All with domain helpdesk assistant role',
19322:                     none   => 'None',
19323:                     status => 'Determined based on institutional status',
19324:                     inc    => 'Include all, but exclude specific personnel',
19325:                     exc    => 'Exclude all, but include specific personnel',
19326:     );
19327:     for (my $num=0; $num<=$maxnum; $num++) {
19328:         my ($prefix,$identifier,$rolename,%curr);
19329:         if ($num == $maxnum) {
19330:             next unless ($env{'form.newcusthelp'} == $maxnum);
19331:             $identifier = 'custhelp'.$num;
19332:             $prefix = 'helproles_'.$num;
19333:             $rolename = $env{'form.custhelpname'.$num};
19334:             $rolename=~s/[^A-Za-z0-9]//gs;
19335:             next if ($rolename eq '');
19336:             next if (exists($existing{'rolesdef_'.$rolename}));
19337:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
19338:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
19339:                                                      $newprivs{'c'},$confname,$dom);
19340:             if ($result ne 'ok') {
19341:                 $errors .= '<li><span class="LC_error">'.
19342:                            &mt('An error occurred storing the new custom role: [_1]',
19343:                            $result).'</span></li>';
19344:                 next;
19345:             } else {
19346:                 $changedprivs{$rolename} = \%newprivs;
19347:                 $newrole = $rolename;
19348:             }
19349:         } else {
19350:             $prefix = 'helproles_'.$num;
19351:             $rolename = $env{'form.'.$prefix};
19352:             next if ($rolename eq '');
19353:             next unless (exists($existing{'rolesdef_'.$rolename}));
19354:             $identifier = 'custhelp'.$num;
19355:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
19356:             my %currprivs;
19357:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
19358:                 split(/\_/,$existing{'rolesdef_'.$rolename});
19359:             foreach my $level ('c','d','s') {
19360:                 if ($newprivs{$level} ne $currprivs{$level}) {
19361:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
19362:                                                              $newprivs{'c'},$confname,$dom);
19363:                     if ($result ne 'ok') {
19364:                         $errors .= '<li><span class="LC_error">'.
19365:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
19366:                                        $rolename,$result).'</span></li>';
19367:                     } else {
19368:                         $changedprivs{$rolename} = \%newprivs;
19369:                     }
19370:                     last;
19371:                 }
19372:             }
19373:             if (ref($current{'adhoc'}) eq 'HASH') {
19374:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
19375:                     %curr = %{$current{'adhoc'}{$rolename}};
19376:                 }
19377:             }
19378:         }
19379:         my $newpos = $env{'form.'.$prefix.'_pos'};
19380:         $newpos =~ s/\D+//g;
19381:         $allpos[$newpos] = $rolename;
19382:         my $newdesc = $env{'form.'.$prefix.'_desc'};
19383:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
19384:         if ($curr{'desc'}) {
19385:             if ($curr{'desc'} ne $newdesc) {
19386:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
19387:                 $newsettings{$rolename}{'desc'} = $newdesc;
19388:             }
19389:         } elsif ($newdesc ne '') {
19390:             $changes{'customrole'}{$rolename}{'desc'} = 1;
19391:             $newsettings{$rolename}{'desc'} = $newdesc;
19392:         }
19393:         my $access = $env{'form.'.$prefix.'_access'};
19394:         if (grep(/^\Q$access\E$/,@accesstypes)) {
19395:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
19396:             if ($access eq 'status') {
19397:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
19398:                 if (scalar(@statuses) == 0) {
19399:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
19400:                 } else {
19401:                     my (@shownstatus,$numtypes);
19402:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
19403:                     if (ref($types) eq 'ARRAY') {
19404:                         $numtypes = scalar(@{$types});
19405:                         foreach my $type (sort(@statuses)) {
19406:                             if ($type eq 'default') {
19407:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
19408:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
19409:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
19410:                                 push(@shownstatus,$usertypes->{$type});
19411:                             }
19412:                         }
19413:                     }
19414:                     if (grep(/^default$/,@statuses)) {
19415:                         push(@shownstatus,$othertitle);
19416:                     }
19417:                     if (scalar(@shownstatus) == 1+$numtypes) {
19418:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
19419:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
19420:                     } else {
19421:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
19422:                         if (ref($curr{'status'}) eq 'ARRAY') {
19423:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
19424:                             if (@diffs) {
19425:                                 $changes{'customrole'}{$rolename}{$access} = 1;
19426:                             }
19427:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19428:                             $changes{'customrole'}{$rolename}{$access} = 1;
19429:                         }
19430:                     }
19431:                 }
19432:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
19433:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
19434:                 my @newspecstaff;
19435:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
19436:                 foreach my $person (sort(@personnel)) {
19437:                     if ($domhelpdesk{$person}) {
19438:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
19439:                     }
19440:                 }
19441:                 if (ref($curr{$access}) eq 'ARRAY') {
19442:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
19443:                     if (@diffs) {
19444:                         $changes{'customrole'}{$rolename}{$access} = 1;
19445:                     }
19446:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19447:                     $changes{'customrole'}{$rolename}{$access} = 1;
19448:                 }
19449:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19450:                     my ($uname,$udom) = split(/:/,$person);
19451:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
19452:                 }
19453:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
19454:             }
19455:         } else {
19456:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
19457:         }
19458:         unless ($curr{'access'} eq $access) {
19459:             $changes{'customrole'}{$rolename}{'access'} = 1;
19460:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
19461:         }
19462:     }
19463:     if (@allpos > 0) {
19464:         my $idx = 0;
19465:         foreach my $rolename (@allpos) {
19466:             if ($rolename ne '') {
19467:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
19468:                 if (ref($current{'adhoc'}) eq 'HASH') {
19469:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
19470:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
19471:                             $changes{'customrole'}{$rolename}{'order'} = 1;
19472:                             $newsettings{$rolename}{'order'} = $idx+1;
19473:                         }
19474:                     }
19475:                 }
19476:                 $idx ++;
19477:             }
19478:         }
19479:     }
19480:     my $putresult;
19481:     if (keys(%changes) > 0) {
19482:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
19483:         if ($putresult eq 'ok') {
19484:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
19485:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
19486:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
19487:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
19488:                 }
19489:             }
19490:             my $cachetime = 24*60*60;
19491:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19492:             if (ref($lastactref) eq 'HASH') {
19493:                 $lastactref->{'domdefaults'} = 1;
19494:             }
19495:         } else {
19496:             $errors .= '<li><span class="LC_error">'.
19497:                        &mt('An error occurred storing the settings: [_1]',
19498:                            $putresult).'</span></li>';
19499:         }
19500:     }
19501:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
19502:         $resulttext = &mt('Changes made:').'<ul>';
19503:         my (%shownprivs,@levelorder);
19504:         @levelorder = ('c','d','s');
19505:         if ((keys(%changes)) && ($putresult eq 'ok')) {
19506:             foreach my $item (sort(keys(%changes))) {
19507:                 if ($item eq 'submitbugs') {
19508:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
19509:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
19510:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
19511:                 } elsif ($item eq 'customrole') {
19512:                     if (ref($changes{'customrole'}) eq 'HASH') {
19513:                         my @keyorder = ('order','desc','access','status','exc','inc');
19514:                         my %keytext = &Apache::lonlocal::texthash(
19515:                                                                    order  => 'Order',
19516:                                                                    desc   => 'Role description',
19517:                                                                    access => 'Role usage',
19518:                                                                    status => 'Allowed institutional types',
19519:                                                                    exc    => 'Allowed personnel',
19520:                                                                    inc    => 'Disallowed personnel',
19521:                         );
19522:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
19523:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
19524:                                 if ($role eq $newrole) {
19525:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
19526:                                                               $role).'<ul>';
19527:                                 } else {
19528:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
19529:                                                               $role).'<ul>';
19530:                                 }
19531:                                 foreach my $key (@keyorder) {
19532:                                     if ($changes{'customrole'}{$role}{$key}) {
19533:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
19534:                                                                   $keytext{$key},$newsettings{$role}{$key}).
19535:                                                        '</li>';
19536:                                     }
19537:                                 }
19538:                                 if (ref($changedprivs{$role}) eq 'HASH') {
19539:                                     $shownprivs{$role} = 1;
19540:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
19541:                                     foreach my $level (@levelorder) {
19542:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
19543:                                             next if ($item eq '');
19544:                                             my ($priv) = split(/\&/,$item,2);
19545:                                             if (&Apache::lonnet::plaintext($priv)) {
19546:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
19547:                                                 unless ($level eq 'c') {
19548:                                                     $resulttext .= ' ('.$lt{$level}.')';
19549:                                                 }
19550:                                                 $resulttext .= '</li>';
19551:                                             }
19552:                                         }
19553:                                     }
19554:                                     $resulttext .= '</ul>';
19555:                                 }
19556:                                 $resulttext .= '</ul></li>';
19557:                             }
19558:                         }
19559:                     }
19560:                 }
19561:             }
19562:         }
19563:         if (keys(%changedprivs)) {
19564:             foreach my $role (sort(keys(%changedprivs))) {
19565:                 unless ($shownprivs{$role}) {
19566:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
19567:                                               $role).'<ul>'.
19568:                                    '<li>'.&mt('Privileges set to :').'<ul>';
19569:                     foreach my $level (@levelorder) {
19570:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
19571:                             next if ($item eq '');
19572:                             my ($priv) = split(/\&/,$item,2);
19573:                             if (&Apache::lonnet::plaintext($priv)) {
19574:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
19575:                                 unless ($level eq 'c') {
19576:                                     $resulttext .= ' ('.$lt{$level}.')';
19577:                                 }
19578:                                 $resulttext .= '</li>';
19579:                             }
19580:                         }
19581:                     }
19582:                     $resulttext .= '</ul></li></ul></li>';
19583:                 }
19584:             }
19585:         }
19586:         $resulttext .= '</ul>';
19587:     } else {
19588:         $resulttext = &mt('No changes made to help settings');
19589:     }
19590:     if ($errors) {
19591:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
19592:                                     $errors.'</ul>';
19593:     }
19594:     return $resulttext;
19595: }
19596: 
19597: sub modify_coursedefaults {
19598:     my ($dom,$lastactref,%domconfig) = @_;
19599:     my ($resulttext,$errors,%changes,%defaultshash);
19600:     my %defaultchecked = (
19601:                            'canuse_pdfforms' => 'off',
19602:                            'uselcmath'       => 'on',
19603:                            'usejsme'         => 'on'
19604:                          );
19605:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme');
19606:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
19607:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
19608:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
19609:                    'mysqltables_textbook','mysqltables_placement');
19610:     my @types = ('official','unofficial','community','textbook','placement');
19611:     my %staticdefaults = (
19612:                            anonsurvey_threshold => 10,
19613:                            uploadquota          => 500,
19614:                            postsubmit           => 60,
19615:                            mysqltables          => 172800,
19616:                          );
19617:     my %texoptions = (
19618:                         MathJax  => 'MathJax',
19619:                         mimetex  => &mt('Convert to Images'),
19620:                         tth      => &mt('TeX to HTML'),
19621:                      );
19622:     $defaultshash{'coursedefaults'} = {};
19623: 
19624:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
19625:         if ($domconfig{'coursedefaults'} eq '') {
19626:             $domconfig{'coursedefaults'} = {};
19627:         }
19628:     }
19629: 
19630:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
19631:         foreach my $item (@toggles) {
19632:             if ($defaultchecked{$item} eq 'on') {
19633:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
19634:                     ($env{'form.'.$item} eq '0')) {
19635:                     $changes{$item} = 1;
19636:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
19637:                     $changes{$item} = 1;
19638:                 }
19639:             } elsif ($defaultchecked{$item} eq 'off') {
19640:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
19641:                     ($env{'form.'.$item} eq '1')) {
19642:                     $changes{$item} = 1;
19643:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
19644:                     $changes{$item} = 1;
19645:                 }
19646:             }
19647:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
19648:         }
19649:         foreach my $item (@numbers) {
19650:             my ($currdef,$newdef);
19651:             $newdef = $env{'form.'.$item};
19652:             if ($item eq 'anonsurvey_threshold') {
19653:                 $currdef = $domconfig{'coursedefaults'}{$item};
19654:                 $newdef =~ s/\D//g;
19655:                 if ($newdef eq '' || $newdef < 1) {
19656:                     $newdef = 1;
19657:                 }
19658:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
19659:             } else {
19660:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
19661:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
19662:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
19663:                 }
19664:                 $newdef =~ s/[^\w.\-]//g;
19665:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
19666:             }
19667:             if ($currdef ne $newdef) {
19668:                 if ($item eq 'anonsurvey_threshold') {
19669:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
19670:                         $changes{$item} = 1;
19671:                     }
19672:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
19673:                     my $setting = $1;
19674:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
19675:                         $changes{$setting} = 1;
19676:                     }
19677:                 }
19678:             }
19679:         }
19680:         my $texengine;
19681:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
19682:             $texengine = $env{'form.texengine'};
19683:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
19684:             if ($currdef eq '') {
19685:                 unless ($texengine eq $Apache::lonnet::deftex) {
19686:                     $changes{'texengine'} = 1;
19687:                 }
19688:             } elsif ($currdef ne $texengine) {
19689:                 $changes{'texengine'} = 1;
19690:             }
19691:         }
19692:         if ($texengine ne '') {
19693:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
19694:         }
19695:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
19696:         my @currclonecode;
19697:         if (ref($currclone) eq 'HASH') {
19698:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
19699:                 @currclonecode = @{$currclone->{'instcode'}};
19700:             }
19701:         }
19702:         my $newclone;
19703:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
19704:             $newclone = $env{'form.canclone'};
19705:         }
19706:         if ($newclone eq 'instcode') {
19707:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
19708:             my (%codedefaults,@code_order,@clonecode);
19709:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
19710:                                                     \@code_order);
19711:             foreach my $item (@code_order) {
19712:                 if (grep(/^\Q$item\E$/,@newcodes)) {
19713:                     push(@clonecode,$item);
19714:                 }
19715:             }
19716:             if (@clonecode) {
19717:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
19718:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
19719:                 if (@diffs) {
19720:                     $changes{'canclone'} = 1;
19721:                 }
19722:             } else {
19723:                 $newclone eq '';
19724:             }
19725:         } elsif ($newclone ne '') {
19726:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
19727:         }
19728:         if ($newclone ne $currclone) {
19729:             $changes{'canclone'} = 1;
19730:         }
19731:         my %credits;
19732:         foreach my $type (@types) {
19733:             unless ($type eq 'community') {
19734:                 $credits{$type} = $env{'form.'.$type.'_credits'};
19735:                 $credits{$type} =~ s/[^\d.]+//g;
19736:             }
19737:         }
19738:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
19739:             ($env{'form.coursecredits'} eq '1')) {
19740:             $changes{'coursecredits'} = 1;
19741:             foreach my $type (keys(%credits)) {
19742:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
19743:             }
19744:         } else {
19745:             if ($env{'form.coursecredits'} eq '1') {
19746:                 foreach my $type (@types) {
19747:                     unless ($type eq 'community') {
19748:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
19749:                             $changes{'coursecredits'} = 1;
19750:                         }
19751:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
19752:                     }
19753:                 }
19754:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19755:                 foreach my $type (@types) {
19756:                     unless ($type eq 'community') {
19757:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
19758:                             $changes{'coursecredits'} = 1;
19759:                             last;
19760:                         }
19761:                     }
19762:                 }
19763:             }
19764:         }
19765:         if ($env{'form.postsubmit'} eq '1') {
19766:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
19767:             my %currtimeout;
19768:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19769:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
19770:                     $changes{'postsubmit'} = 1;
19771:                 }
19772:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19773:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
19774:                 }
19775:             } else {
19776:                 $changes{'postsubmit'} = 1;
19777:             }
19778:             foreach my $type (@types) {
19779:                 my $timeout = $env{'form.'.$type.'_timeout'};
19780:                 $timeout =~ s/\D//g;
19781:                 if ($timeout == $staticdefaults{'postsubmit'}) {
19782:                     $timeout = '';
19783:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
19784:                     $timeout = '0';
19785:                 }
19786:                 unless ($timeout eq '') {
19787:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
19788:                 }
19789:                 if (exists($currtimeout{$type})) {
19790:                     if ($timeout ne $currtimeout{$type}) {
19791:                         $changes{'postsubmit'} = 1;
19792:                     }
19793:                 } elsif ($timeout ne '') {
19794:                     $changes{'postsubmit'} = 1;
19795:                 }
19796:             }
19797:         } else {
19798:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
19799:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19800:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
19801:                     $changes{'postsubmit'} = 1;
19802:                 }
19803:             } else {
19804:                 $changes{'postsubmit'} = 1;
19805:             }
19806:         }
19807:     }
19808:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
19809:                                              $dom);
19810:     if ($putresult eq 'ok') {
19811:         if (keys(%changes) > 0) {
19812:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19813:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
19814:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
19815:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {
19816:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','texengine') {
19817:                     if ($changes{$item}) {
19818:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
19819:                     }
19820:                 }
19821:                 if ($changes{'coursecredits'}) {
19822:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19823:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
19824:                             $domdefaults{$type.'credits'} =
19825:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
19826:                         }
19827:                     }
19828:                 }
19829:                 if ($changes{'postsubmit'}) {
19830:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19831:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
19832:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19833:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
19834:                                 $domdefaults{$type.'postsubtimeout'} =
19835:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
19836:                             }
19837:                         }
19838:                     }
19839:                 }
19840:                 if ($changes{'uploadquota'}) {
19841:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
19842:                         foreach my $type (@types) {
19843:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
19844:                         }
19845:                     }
19846:                 }
19847:                 if ($changes{'canclone'}) {
19848:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
19849:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
19850:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
19851:                             if (@clonecodes) {
19852:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
19853:                             }
19854:                         }
19855:                     } else {
19856:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
19857:                     }
19858:                 }
19859:                 my $cachetime = 24*60*60;
19860:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19861:                 if (ref($lastactref) eq 'HASH') {
19862:                     $lastactref->{'domdefaults'} = 1;
19863:                 }
19864:             }
19865:             $resulttext = &mt('Changes made:').'<ul>';
19866:             foreach my $item (sort(keys(%changes))) {
19867:                 if ($item eq 'canuse_pdfforms') {
19868:                     if ($env{'form.'.$item} eq '1') {
19869:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
19870:                     } else {
19871:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
19872:                     }
19873:                 } elsif ($item eq 'uselcmath') {
19874:                     if ($env{'form.'.$item} eq '1') {
19875:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
19876:                     } else {
19877:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
19878:                     }
19879:                 } elsif ($item eq 'usejsme') {
19880:                     if ($env{'form.'.$item} eq '1') {
19881:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
19882:                     } else {
19883:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
19884:                     }
19885:                 } elsif ($item eq 'texengine') {
19886:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
19887:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
19888:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
19889:                     }
19890:                 } elsif ($item eq 'anonsurvey_threshold') {
19891:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
19892:                 } elsif ($item eq 'uploadquota') {
19893:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
19894:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
19895:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
19896:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
19897:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
19898:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
19899:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
19900:                                        '</ul>'.
19901:                                        '</li>';
19902:                     } else {
19903:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
19904:                     }
19905:                 } elsif ($item eq 'mysqltables') {
19906:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
19907:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
19908:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
19909:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
19910:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
19911:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
19912:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
19913:                                        '</ul>'.
19914:                                        '</li>';
19915:                     } else {
19916:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
19917:                     }
19918:                 } elsif ($item eq 'postsubmit') {
19919:                     if ($domdefaults{'postsubmit'} eq 'off') {
19920:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
19921:                     } else {
19922:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
19923:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19924:                             $resulttext .= &mt('durations:').'<ul>';
19925:                             foreach my $type (@types) {
19926:                                 $resulttext .= '<li>';
19927:                                 my $timeout;
19928:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19929:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
19930:                                 }
19931:                                 my $display;
19932:                                 if ($timeout eq '0') {
19933:                                     $display = &mt('unlimited');
19934:                                 } elsif ($timeout eq '') {
19935:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
19936:                                 } else {
19937:                                     $display = &mt('[quant,_1,second]',$timeout);
19938:                                 }
19939:                                 if ($type eq 'community') {
19940:                                     $resulttext .= &mt('Communities');
19941:                                 } elsif ($type eq 'official') {
19942:                                     $resulttext .= &mt('Official courses');
19943:                                 } elsif ($type eq 'unofficial') {
19944:                                     $resulttext .= &mt('Unofficial courses');
19945:                                 } elsif ($type eq 'textbook') {
19946:                                     $resulttext .= &mt('Textbook courses');
19947:                                 } elsif ($type eq 'placement') {
19948:                                     $resulttext .= &mt('Placement tests');
19949:                                 }
19950:                                 $resulttext .= ' -- '.$display.'</li>';
19951:                             }
19952:                             $resulttext .= '</ul>';
19953:                         }
19954:                         $resulttext .= '</li>';
19955:                     }
19956:                 } elsif ($item eq 'coursecredits') {
19957:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19958:                         if (($domdefaults{'officialcredits'} eq '') &&
19959:                             ($domdefaults{'unofficialcredits'} eq '') &&
19960:                             ($domdefaults{'textbookcredits'} eq '')) {
19961:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
19962:                         } else {
19963:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
19964:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
19965:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
19966:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
19967:                                            '</ul>'.
19968:                                            '</li>';
19969:                         }
19970:                     } else {
19971:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
19972:                     }
19973:                 } elsif ($item eq 'canclone') {
19974:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
19975:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
19976:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
19977:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
19978:                         }
19979:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
19980:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
19981:                     } else {
19982:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
19983:                     }
19984:                 }
19985:             }
19986:             $resulttext .= '</ul>';
19987:         } else {
19988:             $resulttext = &mt('No changes made to course defaults');
19989:         }
19990:     } else {
19991:         $resulttext = '<span class="LC_error">'.
19992:             &mt('An error occurred: [_1]',$putresult).'</span>';
19993:     }
19994:     return $resulttext;
19995: }
19996: 
19997: sub modify_selfenrollment {
19998:     my ($dom,$lastactref,%domconfig) = @_;
19999:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
20000:     my @types = ('official','unofficial','community','textbook','placement');
20001:     my %titles = &tool_titles();
20002:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
20003:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
20004:     $ordered{'default'} = ['types','registered','approval','limit'];
20005: 
20006:     my (%roles,%shown,%toplevel);
20007:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
20008: 
20009:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
20010:         if ($domconfig{'selfenrollment'} eq '') {
20011:             $domconfig{'selfenrollment'} = {};
20012:         }
20013:     }
20014:     %toplevel = (
20015:                   admin      => 'Configuration Rights',
20016:                   default    => 'Default settings',
20017:                   validation => 'Validation of self-enrollment requests',
20018:                 );
20019:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
20020: 
20021:     if (ref($ordered{'admin'}) eq 'ARRAY') {
20022:         foreach my $item (@{$ordered{'admin'}}) {
20023:             foreach my $type (@types) {
20024:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
20025:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
20026:                 } else {
20027:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
20028:                 }
20029:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
20030:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
20031:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
20032:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
20033:                             push(@{$changes{'admin'}{$type}},$item);
20034:                         }
20035:                     } else {
20036:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
20037:                             push(@{$changes{'admin'}{$type}},$item);
20038:                         }
20039:                     }
20040:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
20041:                     push(@{$changes{'admin'}{$type}},$item);
20042:                 }
20043:             }
20044:         }
20045:     }
20046: 
20047:     foreach my $item (@{$ordered{'default'}}) {
20048:         foreach my $type (@types) {
20049:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
20050:             if ($item eq 'types') {
20051:                 unless (($value eq 'all') || ($value eq 'dom')) {
20052:                     $value = '';
20053:                 }
20054:             } elsif ($item eq 'registered') {
20055:                 unless ($value eq '1') {
20056:                     $value = 0;
20057:                 }
20058:             } elsif ($item eq 'approval') {
20059:                 unless ($value =~ /^[012]$/) {
20060:                     $value = 0;
20061:                 }
20062:             } else {
20063:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
20064:                     $value = 'none';
20065:                 }
20066:             }
20067:             $selfenrollhash{'default'}{$type}{$item} = $value;
20068:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
20069:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
20070:                     if ($selfenrollhash{'default'}{$type}{$item} ne
20071:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
20072:                          push(@{$changes{'default'}{$type}},$item);
20073:                     }
20074:                 } else {
20075:                     push(@{$changes{'default'}{$type}},$item);
20076:                 }
20077:             } else {
20078:                 push(@{$changes{'default'}{$type}},$item);
20079:             }
20080:             if ($item eq 'limit') {
20081:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
20082:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
20083:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
20084:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
20085:                     }
20086:                 } else {
20087:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
20088:                 }
20089:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
20090:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
20091:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
20092:                          push(@{$changes{'default'}{$type}},'cap');
20093:                     }
20094:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
20095:                     push(@{$changes{'default'}{$type}},'cap');
20096:                 }
20097:             }
20098:         }
20099:     }
20100: 
20101:     foreach my $item (@{$itemsref}) {
20102:         if ($item eq 'fields') {
20103:             my @changed;
20104:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
20105:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
20106:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
20107:             }
20108:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
20109:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
20110:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
20111:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
20112:                 } else {
20113:                     @changed = @{$selfenrollhash{'validation'}{$item}};
20114:                 }
20115:             } else {
20116:                 @changed = @{$selfenrollhash{'validation'}{$item}};
20117:             }
20118:             if (@changed) {
20119:                 if ($selfenrollhash{'validation'}{$item}) { 
20120:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
20121:                 } else {
20122:                     $changes{'validation'}{$item} = &mt('None');
20123:                 }
20124:             }
20125:         } else {
20126:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
20127:             if ($item eq 'markup') {
20128:                if ($env{'form.selfenroll_validation_'.$item}) {
20129:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
20130:                }
20131:             }
20132:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
20133:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
20134:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
20135:                 }
20136:             }
20137:         }
20138:     }
20139: 
20140:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
20141:                                              $dom);
20142:     if ($putresult eq 'ok') {
20143:         if (keys(%changes) > 0) {
20144:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20145:             $resulttext = &mt('Changes made:').'<ul>';
20146:             foreach my $key ('admin','default','validation') {
20147:                 if (ref($changes{$key}) eq 'HASH') {
20148:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
20149:                     if ($key eq 'validation') {
20150:                         foreach my $item (@{$itemsref}) {
20151:                             if (exists($changes{$key}{$item})) {
20152:                                 if ($item eq 'markup') {
20153:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
20154:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
20155:                                 } else {  
20156:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
20157:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
20158:                                 }
20159:                             }
20160:                         }
20161:                     } else {
20162:                         foreach my $type (@types) {
20163:                             if ($type eq 'community') {
20164:                                 $roles{'1'} = &mt('Community personnel');
20165:                             } else {
20166:                                 $roles{'1'} = &mt('Course personnel');
20167:                             }
20168:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
20169:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
20170:                                     if ($key eq 'admin') {
20171:                                         my @mgrdc = ();
20172:                                         if (ref($ordered{$key}) eq 'ARRAY') {
20173:                                             foreach my $item (@{$ordered{'admin'}}) {
20174:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
20175:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
20176:                                                         push(@mgrdc,$item);
20177:                                                     }
20178:                                                 }
20179:                                             }
20180:                                             if (@mgrdc) {
20181:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
20182:                                             } else {
20183:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
20184:                                             }
20185:                                         }
20186:                                     } else {
20187:                                         if (ref($ordered{$key}) eq 'ARRAY') {
20188:                                             foreach my $item (@{$ordered{$key}}) {
20189:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
20190:                                                     $domdefaults{$type.'selfenroll'.$item} =
20191:                                                         $selfenrollhash{$key}{$type}{$item};
20192:                                                 }
20193:                                             }
20194:                                         }
20195:                                     }
20196:                                 }
20197:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
20198:                                 foreach my $item (@{$ordered{$key}}) {
20199:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
20200:                                         $resulttext .= '<li>';
20201:                                         if ($key eq 'admin') {
20202:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
20203:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
20204:                                         } else {
20205:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
20206:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
20207:                                         }
20208:                                         $resulttext .= '</li>';
20209:                                     }
20210:                                 }
20211:                                 $resulttext .= '</ul></li>';
20212:                             }
20213:                         }
20214:                         $resulttext .= '</ul></li>'; 
20215:                     }
20216:                 }
20217:             }
20218:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
20219:                 my $cachetime = 24*60*60;
20220:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20221:                 if (ref($lastactref) eq 'HASH') {
20222:                     $lastactref->{'domdefaults'} = 1;
20223:                 }
20224:             }
20225:             $resulttext .= '</ul>';
20226:         } else {
20227:             $resulttext = &mt('No changes made to self-enrollment settings');
20228:         }
20229:     } else {
20230:         $resulttext = '<span class="LC_error">'.
20231:             &mt('An error occurred: [_1]',$putresult).'</span>';
20232:     }
20233:     return $resulttext;
20234: }
20235: 
20236: sub modify_wafproxy {
20237:     my ($dom,$action,$lastactref,%domconfig) = @_;
20238:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20239:     my (%othercontrol,%canset,%values,%curralias,%currvalue,@warnings,%wafproxy,
20240:         %changes,%expirecache);
20241:     foreach my $server (sort(keys(%servers))) {
20242:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
20243:         if ($serverhome eq $server) {
20244:             my $serverdom = &Apache::lonnet::host_domain($server);
20245:             if ($serverdom eq $dom) {
20246:                 $canset{$server} = 1;
20247:             }
20248:         }
20249:     }
20250:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
20251:         %{$values{$dom}} = ();
20252:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
20253:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
20254:         }
20255:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
20256:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
20257:         }
20258:     }
20259:     my $output;
20260:     if (keys(%canset)) {
20261:         %{$wafproxy{'alias'}} = ();
20262:         foreach my $key (sort(keys(%canset))) {
20263:             if ($env{'form.wafproxy_'.$dom}) {
20264:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
20265:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
20266:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
20267:                     $changes{'alias'} = 1;
20268:                 }
20269:             } else {
20270:                 $wafproxy{'alias'}{$key} = '';
20271:                 if ($curralias{$key}) {
20272:                     $changes{'alias'} = 1;
20273:                 }
20274:             }
20275:             if ($wafproxy{'alias'}{$key} eq '') {
20276:                 if ($curralias{$key}) {
20277:                     $expirecache{$key} = 1;
20278:                 }
20279:                 delete($wafproxy{'alias'}{$key});
20280:             }
20281:         }
20282:         unless (keys(%{$wafproxy{'alias'}})) {
20283:             delete($wafproxy{'alias'});
20284:         }
20285:         # Localization for values in %warn occus in &mt() calls separately.
20286:         my %warn = (
20287:                      trusted => 'trusted IP range(s)',
20288:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
20289:                      vpnext => 'IP range(s) for backend WAF connections',
20290:                    );
20291:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
20292:             my $possible = $env{'form.wafproxy_'.$item};
20293:             $possible =~ s/^\s+|\s+$//g;
20294:             if ($possible ne '') {
20295:                 if ($item eq 'remoteip') {
20296:                     if ($possible =~ /^[mhn]$/) {
20297:                         $wafproxy{$item} = $possible;
20298:                     }
20299:                 } elsif ($item eq 'ipheader') {
20300:                     if ($wafproxy{'remoteip'} eq 'h') {
20301:                         $wafproxy{$item} = $possible;
20302:                     }
20303:                 } elsif ($item eq 'sslopt') {
20304:                     if ($possible =~ /^0|1$/) {
20305:                         $wafproxy{$item} = $possible;
20306:                     }
20307:                 } else {
20308:                     my (@ok,$count);
20309:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
20310:                         unless ($env{'form.wafproxy_vpnaccess'}) {
20311:                             $possible = '';
20312:                         }
20313:                     } elsif ($item eq 'trusted') {
20314:                         unless ($wafproxy{'remoteip'} eq 'h') {
20315:                             $possible = '';
20316:                         }
20317:                     }
20318:                     unless ($possible eq '') {
20319:                         $possible =~ s/[\r\n]+/\s/g;
20320:                         $possible =~ s/\s*-\s*/-/g;
20321:                         $possible =~ s/\s+/,/g;
20322:                     }
20323:                     $count = 0;
20324:                     if ($possible ne '') {
20325:                         foreach my $poss (split(/\,/,$possible)) {
20326:                             $count ++;
20327:                             if (&validate_ip_pattern($poss)) {
20328:                                 push(@ok,$poss);
20329:                             }
20330:                         }
20331:                         if (@ok) {
20332:                             $wafproxy{$item} = join(',',@ok);
20333:                         }
20334:                         my $diff = $count - scalar(@ok);
20335:                         if ($diff) {
20336:                             push(@warnings,'<li>'.
20337:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
20338:                                      $diff,$warn{$item}).
20339:                                  '</li>');
20340:                         }
20341:                     }
20342:                 }
20343:                 if ($wafproxy{$item} ne $currvalue{$item}) {
20344:                     $changes{$item} = 1;
20345:                 }
20346:             } elsif ($currvalue{$item}) {
20347:                 $changes{$item} = 1;
20348:             } 
20349:         }
20350:     } else {
20351:         if (keys(%curralias)) {
20352:             $changes{'alias'} = 1;
20353:         } 
20354:         if (keys(%currvalue)) {
20355:             foreach my $key (keys(%currvalue)) {
20356:                 $changes{$key} = 1;
20357:             }
20358:         }
20359:     }
20360:     if (keys(%changes)) {
20361:         my %defaultshash = (
20362:                               wafproxy => \%wafproxy,
20363:                            ); 
20364:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20365:                                                  $dom);
20366:         if ($putresult eq 'ok') {
20367:             my $cachetime = 24*60*60;
20368:             my (%domdefaults,$updatedomdefs);
20369:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
20370:                 if ($changes{$item}) {
20371:                     unless ($updatedomdefs) {
20372:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
20373:                         $updatedomdefs = 1;
20374:                     }
20375:                     if ($wafproxy{$item}) {
20376:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
20377:                     } elsif (exists($domdefaults{'waf_'.$item})) {
20378:                         delete($domdefaults{'waf_'.$item});
20379:                     } 
20380:                 }
20381:             }
20382:             if ($updatedomdefs) {
20383:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20384:                 if (ref($lastactref) eq 'HASH') {
20385:                     $lastactref->{'domdefaults'} = 1;
20386:                 }
20387:             }
20388:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
20389:                 my %updates = %expirecache;
20390:                 foreach my $key (keys(%expirecache)) {
20391:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
20392:                 }
20393:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
20394:                     my $cachetime = 24*60*60;
20395:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
20396:                         $updates{$key} = 1;
20397:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
20398:                                                       $cachetime);
20399:                     }
20400:                 }
20401:                 if (ref($lastactref) eq 'HASH') {
20402:                     $lastactref->{'proxyalias'} = \%updates;
20403:                 }
20404:             }
20405:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
20406:             foreach my $item ('alias','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
20407:                 if ($changes{$item}) {
20408:                     if ($item eq 'alias') {
20409:                         my $numaliased = 0;
20410:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
20411:                             my $shown;
20412:                             if (keys(%{$wafproxy{'alias'}})) {
20413:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
20414:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
20415:                                                          &Apache::lonnet::hostname($server),
20416:                                                          $wafproxy{'alias'}{$server}).'</li>';
20417:                                     $numaliased ++;
20418:                                 }
20419:                                 if ($numaliased) {
20420:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
20421:                                                           '<ul>'.$shown.'</ul>').'</li>';
20422:                                 }
20423:                             }
20424:                         }
20425:                         unless ($numaliased) {
20426:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
20427:                         }
20428:                     } else {
20429:                         if ($item eq 'remoteip') {
20430:                             my %ip_methods = &remoteip_methods();
20431:                             if ($wafproxy{$item} =~ /^[mh]$/) {
20432:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
20433:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
20434:                             } else {
20435:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
20436:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
20437:                                                '</li>';
20438:                                 } else {
20439:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
20440:                                 }
20441:                             }
20442:                         } elsif ($item eq 'ipheader') {
20443:                             if ($wafproxy{$item}) {
20444:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
20445:                                                       $wafproxy{$item}).'</li>';
20446:                             } else {
20447:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
20448:                             }
20449:                         } elsif ($item eq 'trusted') {
20450:                             if ($wafproxy{$item}) {
20451:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
20452:                                                       $wafproxy{$item}).'</li>';
20453:                             } else {
20454:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
20455:                             }
20456:                         } elsif ($item eq 'vpnint') {
20457:                             if ($wafproxy{$item}) {
20458:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
20459:                                                        $wafproxy{$item}).'</li>';
20460:                             } else {
20461:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
20462:                             }
20463:                         } elsif ($item eq 'vpnext') {
20464:                             if ($wafproxy{$item}) {
20465:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
20466:                                                        $wafproxy{$item}).'</li>';
20467:                             } else {
20468:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
20469:                             }
20470:                         } elsif ($item eq 'sslopt') {
20471:                             if ($wafproxy{$item}) {
20472:                                 $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>';
20473:                             } else {
20474:                                 $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>';
20475:                             }
20476:                         }
20477:                     }
20478:                 }
20479:             }
20480:         } else {
20481:             $output = '<span class="LC_error">'.
20482:                       &mt('An error occurred: [_1]',$putresult).'</span>';
20483:         }
20484:     } elsif (keys(%canset)) {
20485:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
20486:     }
20487:     if (@warnings) {
20488:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
20489:                        join("\n",@warnings).'</ul>';
20490:     }
20491:     return $output;
20492: }
20493: 
20494: sub validate_ip_pattern {
20495:     my ($pattern) = @_;
20496:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
20497:         my ($start,$end) = ($1,$2);
20498:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
20499:             return 1;
20500:         }
20501:     } elsif (&Net::CIDR::cidrvalidate($pattern)) {
20502:         return 1;
20503:     }
20504:     return
20505: }
20506: 
20507: sub modify_usersessions {
20508:     my ($dom,$lastactref,%domconfig) = @_;
20509:     my @hostingtypes = ('version','excludedomain','includedomain');
20510:     my @offloadtypes = ('primary','default');
20511:     my %types = (
20512:                   remote => \@hostingtypes,
20513:                   hosted => \@hostingtypes,
20514:                   spares => \@offloadtypes,
20515:                 );
20516:     my @prefixes = ('remote','hosted','spares');
20517:     my @lcversions = &Apache::lonnet::all_loncaparevs();
20518:     my (%by_ip,%by_location,@intdoms,@instdoms);
20519:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20520:     my @locations = sort(keys(%by_location));
20521:     my (%defaultshash,%changes);
20522:     foreach my $prefix (@prefixes) {
20523:         $defaultshash{'usersessions'}{$prefix} = {};
20524:     }
20525:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20526:     my $resulttext;
20527:     my %iphost = &Apache::lonnet::get_iphost();
20528:     foreach my $prefix (@prefixes) {
20529:         next if ($prefix eq 'spares');
20530:         foreach my $type (@{$types{$prefix}}) {
20531:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20532:             if ($type eq 'version') {
20533:                 my $value = $env{'form.'.$prefix.'_'.$type};
20534:                 my $okvalue;
20535:                 if ($value ne '') {
20536:                     if (grep(/^\Q$value\E$/,@lcversions)) {
20537:                         $okvalue = $value;
20538:                     }
20539:                 }
20540:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
20541:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
20542:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
20543:                             if ($inuse == 0) {
20544:                                 $changes{$prefix}{$type} = 1;
20545:                             } else {
20546:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
20547:                                     $changes{$prefix}{$type} = 1;
20548:                                 }
20549:                                 if ($okvalue ne '') {
20550:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20551:                                 } 
20552:                             }
20553:                         } else {
20554:                             if (($inuse == 1) && ($okvalue ne '')) {
20555:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20556:                                 $changes{$prefix}{$type} = 1;
20557:                             }
20558:                         }
20559:                     } else {
20560:                         if (($inuse == 1) && ($okvalue ne '')) {
20561:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20562:                             $changes{$prefix}{$type} = 1;
20563:                         }
20564:                     }
20565:                 } else {
20566:                     if (($inuse == 1) && ($okvalue ne '')) {
20567:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20568:                         $changes{$prefix}{$type} = 1;
20569:                     }
20570:                 }
20571:             } else {
20572:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20573:                 my @okvals;
20574:                 foreach my $val (@vals) {
20575:                     if ($val =~ /:/) {
20576:                         my @items = split(/:/,$val);
20577:                         foreach my $item (@items) {
20578:                             if (ref($by_location{$item}) eq 'ARRAY') {
20579:                                 push(@okvals,$item);
20580:                             }
20581:                         }
20582:                     } else {
20583:                         if (ref($by_location{$val}) eq 'ARRAY') {
20584:                             push(@okvals,$val);
20585:                         }
20586:                     }
20587:                 }
20588:                 @okvals = sort(@okvals);
20589:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
20590:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
20591:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
20592:                             if ($inuse == 0) {
20593:                                 $changes{$prefix}{$type} = 1; 
20594:                             } else {
20595:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20596:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
20597:                                 if (@changed > 0) {
20598:                                     $changes{$prefix}{$type} = 1;
20599:                                 }
20600:                             }
20601:                         } else {
20602:                             if ($inuse == 1) {
20603:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20604:                                 $changes{$prefix}{$type} = 1;
20605:                             }
20606:                         } 
20607:                     } else {
20608:                         if ($inuse == 1) {
20609:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20610:                             $changes{$prefix}{$type} = 1;
20611:                         }
20612:                     }
20613:                 } else {
20614:                     if ($inuse == 1) {
20615:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20616:                         $changes{$prefix}{$type} = 1;
20617:                     }
20618:                 }
20619:             }
20620:         }
20621:     }
20622: 
20623:     my @alldoms = &Apache::lonnet::all_domains();
20624:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20625:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
20626:     my $savespares;
20627: 
20628:     foreach my $lonhost (sort(keys(%servers))) {
20629:         my $serverhomeID =
20630:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
20631:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
20632:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
20633:         my %spareschg;
20634:         foreach my $type (@{$types{'spares'}}) {
20635:             my @okspares;
20636:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
20637:             foreach my $server (@checked) {
20638:                 if (&Apache::lonnet::hostname($server) ne '') {
20639:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
20640:                         unless (grep(/^\Q$server\E$/,@okspares)) {
20641:                             push(@okspares,$server);
20642:                         }
20643:                     }
20644:                 }
20645:             }
20646:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
20647:             my $newspare;
20648:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
20649:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
20650:                     $newspare = $new;
20651:                 }
20652:             }
20653:             my @spares;
20654:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
20655:                 @spares = sort(@okspares,$newspare);
20656:             } else {
20657:                 @spares = sort(@okspares);
20658:             }
20659:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
20660:             if (ref($spareid{$lonhost}) eq 'HASH') {
20661:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
20662:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
20663:                     if (@diffs > 0) {
20664:                         $spareschg{$type} = 1;
20665:                     }
20666:                 }
20667:             }
20668:         }
20669:         if (keys(%spareschg) > 0) {
20670:             $changes{'spares'}{$lonhost} = \%spareschg;
20671:         }
20672:     }
20673:     $defaultshash{'usersessions'}{'offloadnow'} = {};
20674:     $defaultshash{'usersessions'}{'offloadoth'} = {};
20675:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
20676:     my @okoffload;
20677:     if (@offloadnow) {
20678:         foreach my $server (@offloadnow) {
20679:             if (&Apache::lonnet::hostname($server) ne '') {
20680:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
20681:                     push(@okoffload,$server);
20682:                 }
20683:             }
20684:         }
20685:         if (@okoffload) {
20686:             foreach my $lonhost (@okoffload) {
20687:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
20688:             }
20689:         }
20690:     }
20691:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
20692:     my @okoffloadoth;
20693:     if (@offloadoth) {
20694:         foreach my $server (@offloadoth) {
20695:             if (&Apache::lonnet::hostname($server) ne '') {
20696:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
20697:                     push(@okoffloadoth,$server);
20698:                 }
20699:             }
20700:         }
20701:         if (@okoffloadoth) {
20702:             foreach my $lonhost (@okoffloadoth) {
20703:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
20704:             }
20705:         }
20706:     }
20707:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
20708:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
20709:             if (ref($changes{'spares'}) eq 'HASH') {
20710:                 if (keys(%{$changes{'spares'}}) > 0) {
20711:                     $savespares = 1;
20712:                 }
20713:             }
20714:         } else {
20715:             $savespares = 1;
20716:         }
20717:         foreach my $offload ('offloadnow','offloadoth') {
20718:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
20719:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
20720:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
20721:                         $changes{$offload} = 1;
20722:                         last;
20723:                     }
20724:                 }
20725:                 unless ($changes{$offload}) {
20726:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
20727:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
20728:                             $changes{$offload} = 1;
20729:                             last;
20730:                         }
20731:                     }
20732:                 }
20733:             } else {
20734:                 if (($offload eq 'offloadnow') && (@okoffload)) {
20735:                      $changes{'offloadnow'} = 1;
20736:                 }
20737:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
20738:                     $changes{'offloadoth'} = 1;
20739:                 }
20740:             } 
20741:         }
20742:     } else {
20743:         if (@okoffload) {
20744:             $changes{'offloadnow'} = 1;
20745:         }
20746:         if (@okoffloadoth) {
20747:             $changes{'offloadoth'} = 1;
20748:         }
20749:     }
20750:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
20751:     if ((keys(%changes) > 0) || ($savespares)) {
20752:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20753:                                                  $dom);
20754:         if ($putresult eq 'ok') {
20755:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
20756:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
20757:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
20758:                 }
20759:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
20760:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
20761:                 }
20762:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
20763:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
20764:                 }
20765:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
20766:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
20767:                 }
20768:             }
20769:             my $cachetime = 24*60*60;
20770:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20771:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
20772:             if (ref($lastactref) eq 'HASH') {
20773:                 $lastactref->{'domdefaults'} = 1;
20774:                 $lastactref->{'usersessions'} = 1;
20775:             }
20776:             if (keys(%changes) > 0) {
20777:                 my %lt = &usersession_titles();
20778:                 $resulttext = &mt('Changes made:').'<ul>';
20779:                 foreach my $prefix (@prefixes) {
20780:                     if (ref($changes{$prefix}) eq 'HASH') {
20781:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
20782:                         if ($prefix eq 'spares') {
20783:                             if (ref($changes{$prefix}) eq 'HASH') {
20784:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
20785:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
20786:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
20787:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
20788:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
20789:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
20790:                                         foreach my $type (@{$types{$prefix}}) {
20791:                                             if ($changes{$prefix}{$lonhost}{$type}) {
20792:                                                 my $offloadto = &mt('None');
20793:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
20794:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
20795:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
20796:                                                     }
20797:                                                 }
20798:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
20799:                                             }
20800:                                         }
20801:                                     }
20802:                                     $resulttext .= '</li>';
20803:                                 }
20804:                             }
20805:                         } else {
20806:                             foreach my $type (@{$types{$prefix}}) {
20807:                                 if (defined($changes{$prefix}{$type})) {
20808:                                     my ($newvalue,$notinuse);
20809:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
20810:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
20811:                                             if ($type eq 'version') {
20812:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
20813:                                             } else {
20814:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
20815:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
20816:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
20817:                                                     }
20818:                                                 } else {
20819:                                                     $notinuse = 1;
20820:                                                 }
20821:                                             }
20822:                                         }
20823:                                     }
20824:                                     if ($newvalue eq '') {
20825:                                         if ($type eq 'version') {
20826:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
20827:                                         } elsif ($notinuse) {
20828:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
20829:                                         } else {
20830:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
20831:                                         }
20832:                                     } else {
20833:                                         if ($type eq 'version') {
20834:                                             $newvalue .= ' '.&mt('(or later)');
20835:                                         }
20836:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
20837:                                     }
20838:                                 }
20839:                             }
20840:                         }
20841:                         $resulttext .= '</ul>';
20842:                     }
20843:                 }
20844:                 if ($changes{'offloadnow'}) {
20845:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
20846:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
20847:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
20848:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
20849:                                 $resulttext .= '<li>'.$lonhost.'</li>';
20850:                             }
20851:                             $resulttext .= '</ul>';
20852:                         } else {
20853:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
20854:                         }
20855:                     } else {
20856:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
20857:                     }
20858:                 }
20859:                 if ($changes{'offloadoth'}) {
20860:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
20861:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
20862:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
20863:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
20864:                                 $resulttext .= '<li>'.$lonhost.'</li>';
20865:                             }
20866:                             $resulttext .= '</ul>';
20867:                         } else {
20868:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
20869:                         }
20870:                     } else {
20871:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
20872:                     }
20873:                 }
20874:                 $resulttext .= '</ul>';
20875:             } else {
20876:                 $resulttext = $nochgmsg;
20877:             }
20878:         } else {
20879:             $resulttext = '<span class="LC_error">'.
20880:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20881:         }
20882:     } else {
20883:         $resulttext = $nochgmsg;
20884:     }
20885:     return $resulttext;
20886: }
20887: 
20888: sub modify_ssl {
20889:     my ($dom,$lastactref,%domconfig) = @_;
20890:     my (%by_ip,%by_location,@intdoms,@instdoms);
20891:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20892:     my @locations = sort(keys(%by_location));
20893:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20894:     my (%defaultshash,%changes);
20895:     my $action = 'ssl';
20896:     my @prefixes = ('connto','connfrom','replication');
20897:     foreach my $prefix (@prefixes) {
20898:         $defaultshash{$action}{$prefix} = {};
20899:     }
20900:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20901:     my $resulttext;
20902:     my %iphost = &Apache::lonnet::get_iphost();
20903:     my @reptypes = ('certreq','nocertreq');
20904:     my @connecttypes = ('dom','intdom','other');
20905:     my %types = (
20906:                   connto      => \@connecttypes,
20907:                   connfrom    => \@connecttypes,
20908:                   replication => \@reptypes,
20909:                 );
20910:     foreach my $prefix (sort(keys(%types))) {
20911:         foreach my $type (@{$types{$prefix}}) {
20912:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
20913:                 my $value = 'yes';
20914:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
20915:                     $value = $env{'form.'.$prefix.'_'.$type};
20916:                 }
20917:                 if (ref($domconfig{$action}) eq 'HASH') {
20918:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
20919:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
20920:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
20921:                                 $changes{$prefix}{$type} = 1;
20922:                             }
20923:                             $defaultshash{$action}{$prefix}{$type} = $value;
20924:                         } else {
20925:                             $defaultshash{$action}{$prefix}{$type} = $value;
20926:                             $changes{$prefix}{$type} = 1;
20927:                         }
20928:                     } else {
20929:                         $defaultshash{$action}{$prefix}{$type} = $value;
20930:                         $changes{$prefix}{$type} = 1;
20931:                     }
20932:                 } else {
20933:                     $defaultshash{$action}{$prefix}{$type} = $value;
20934:                     $changes{$prefix}{$type} = 1;
20935:                 }
20936:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
20937:                     delete($changes{$prefix}{$type});
20938:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
20939:                     delete($changes{$prefix}{$type});
20940:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
20941:                     delete($changes{$prefix}{$type});
20942:                 }
20943:             } elsif ($prefix eq 'replication') {
20944:                 if (@locations > 0) {
20945:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20946:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20947:                     my @okvals;
20948:                     foreach my $val (@vals) {
20949:                         if ($val =~ /:/) {
20950:                             my @items = split(/:/,$val);
20951:                             foreach my $item (@items) {
20952:                                 if (ref($by_location{$item}) eq 'ARRAY') {
20953:                                     push(@okvals,$item);
20954:                                 }
20955:                             }
20956:                         } else {
20957:                             if (ref($by_location{$val}) eq 'ARRAY') {
20958:                                 push(@okvals,$val);
20959:                             }
20960:                         }
20961:                     }
20962:                     @okvals = sort(@okvals);
20963:                     if (ref($domconfig{$action}) eq 'HASH') {
20964:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
20965:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
20966:                                 if ($inuse == 0) {
20967:                                     $changes{$prefix}{$type} = 1;
20968:                                 } else {
20969:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
20970:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
20971:                                     if (@changed > 0) {
20972:                                         $changes{$prefix}{$type} = 1;
20973:                                     }
20974:                                 }
20975:                             } else {
20976:                                 if ($inuse == 1) {
20977:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
20978:                                     $changes{$prefix}{$type} = 1;
20979:                                 }
20980:                             }
20981:                         } else {
20982:                             if ($inuse == 1) {
20983:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
20984:                                 $changes{$prefix}{$type} = 1;
20985:                             }
20986:                         }
20987:                     } else {
20988:                         if ($inuse == 1) {
20989:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
20990:                             $changes{$prefix}{$type} = 1;
20991:                         }
20992:                     }
20993:                 }
20994:             }
20995:         }
20996:     }
20997:     if (keys(%changes)) {
20998:         foreach my $prefix (keys(%changes)) {
20999:             if (ref($changes{$prefix}) eq 'HASH') {
21000:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
21001:                     delete($changes{$prefix});
21002:                 }
21003:             } else {
21004:                 delete($changes{$prefix});
21005:             }
21006:         }
21007:     }
21008:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
21009:     if (keys(%changes) > 0) {
21010:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21011:                                                  $dom);
21012:         if ($putresult eq 'ok') {
21013:             if (ref($defaultshash{$action}) eq 'HASH') {
21014:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
21015:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
21016:                 }
21017:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
21018:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
21019:                 }
21020:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
21021:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
21022:                 }
21023:             }
21024:             my $cachetime = 24*60*60;
21025:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21026:             if (ref($lastactref) eq 'HASH') {
21027:                 $lastactref->{'domdefaults'} = 1;
21028:             }
21029:             if (keys(%changes) > 0) {
21030:                 my %titles = &ssl_titles();
21031:                 $resulttext = &mt('Changes made:').'<ul>';
21032:                 foreach my $prefix (@prefixes) {
21033:                     if (ref($changes{$prefix}) eq 'HASH') {
21034:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
21035:                         foreach my $type (@{$types{$prefix}}) {
21036:                             if (defined($changes{$prefix}{$type})) {
21037:                                 my ($newvalue,$notinuse);
21038:                                 if (ref($defaultshash{$action}) eq 'HASH') {
21039:                                     if (ref($defaultshash{$action}{$prefix})) {
21040:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
21041:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
21042:                                         } else {
21043:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
21044:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
21045:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
21046:                                                 }
21047:                                             } else {
21048:                                                 $notinuse = 1;
21049:                                             }
21050:                                         }
21051:                                     }
21052:                                     if ($notinuse) {
21053:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
21054:                                     } elsif ($newvalue eq '') {
21055:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
21056:                                     } else {
21057:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
21058:                                     }
21059:                                 }
21060:                             }
21061:                         }
21062:                         $resulttext .= '</ul>';
21063:                     }
21064:                 }
21065:             } else {
21066:                 $resulttext = $nochgmsg;
21067:             }
21068:         } else {
21069:             $resulttext = '<span class="LC_error">'.
21070:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21071:         }
21072:     } else {
21073:         $resulttext = $nochgmsg;
21074:     }
21075:     return $resulttext;
21076: }
21077: 
21078: sub modify_trust {
21079:     my ($dom,$lastactref,%domconfig) = @_;
21080:     my (%by_ip,%by_location,@intdoms,@instdoms);
21081:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
21082:     my @locations = sort(keys(%by_location));
21083:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
21084:     my @types = ('exc','inc');
21085:     my (%defaultshash,%changes);
21086:     foreach my $prefix (@prefixes) {
21087:         $defaultshash{'trust'}{$prefix} = {};
21088:     }
21089:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21090:     my $resulttext;
21091:     foreach my $prefix (@prefixes) {
21092:         foreach my $type (@types) {
21093:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
21094:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
21095:             my @okvals;
21096:             foreach my $val (@vals) {
21097:                 if ($val =~ /:/) {
21098:                     my @items = split(/:/,$val);
21099:                     foreach my $item (@items) {
21100:                         if (ref($by_location{$item}) eq 'ARRAY') {
21101:                             push(@okvals,$item);
21102:                         }
21103:                     }
21104:                 } else {
21105:                     if (ref($by_location{$val}) eq 'ARRAY') {
21106:                         push(@okvals,$val);
21107:                     }
21108:                 }
21109:             }
21110:             @okvals = sort(@okvals);
21111:             if (ref($domconfig{'trust'}) eq 'HASH') {
21112:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
21113:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
21114:                         if ($inuse == 0) {
21115:                             $changes{$prefix}{$type} = 1;
21116:                         } else {
21117:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
21118:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
21119:                             if (@changed > 0) {
21120:                                 $changes{$prefix}{$type} = 1;
21121:                             }
21122:                         }
21123:                     } else {
21124:                         if ($inuse == 1) {
21125:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
21126:                             $changes{$prefix}{$type} = 1;
21127:                         }
21128:                     }
21129:                 } else {
21130:                     if ($inuse == 1) {
21131:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
21132:                         $changes{$prefix}{$type} = 1;
21133:                     }
21134:                 }
21135:             } else {
21136:                 if ($inuse == 1) {
21137:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
21138:                     $changes{$prefix}{$type} = 1;
21139:                 }
21140:             }
21141:         }
21142:     }
21143:     my $nochgmsg = &mt('No changes made to trust settings.');
21144:     if (keys(%changes) > 0) {
21145:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21146:                                                  $dom);
21147:         if ($putresult eq 'ok') {
21148:             if (ref($defaultshash{'trust'}) eq 'HASH') {
21149:                 foreach my $prefix (@prefixes) {
21150:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
21151:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
21152:                     }
21153:                 }
21154:             }
21155:             my $cachetime = 24*60*60;
21156:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21157:             if (ref($lastactref) eq 'HASH') {
21158:                 $lastactref->{'domdefaults'} = 1;
21159:             }
21160:             if (keys(%changes) > 0) {
21161:                 my %lt = &trust_titles();
21162:                 $resulttext = &mt('Changes made:').'<ul>';
21163:                 foreach my $prefix (@prefixes) {
21164:                     if (ref($changes{$prefix}) eq 'HASH') {
21165:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
21166:                         foreach my $type (@types) {
21167:                             if (defined($changes{$prefix}{$type})) {
21168:                                 my ($newvalue,$notinuse);
21169:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
21170:                                     if (ref($defaultshash{'trust'}{$prefix})) {
21171:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
21172:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
21173:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
21174:                                             }
21175:                                         } else {
21176:                                             $notinuse = 1;
21177:                                         }
21178:                                     }
21179:                                 }
21180:                                 if ($notinuse) {
21181:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
21182:                                 } elsif ($newvalue eq '') {
21183:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
21184:                                 } else {
21185:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
21186:                                 }
21187:                             }
21188:                         }
21189:                         $resulttext .= '</ul>';
21190:                     }
21191:                 }
21192:                 $resulttext .= '</ul>';
21193:             } else {
21194:                 $resulttext = $nochgmsg;
21195:             }
21196:         } else {
21197:             $resulttext = '<span class="LC_error">'.
21198:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21199:         }
21200:     } else {
21201:         $resulttext = $nochgmsg;
21202:     }
21203:     return $resulttext;
21204: }
21205: 
21206: sub modify_loadbalancing {
21207:     my ($dom,%domconfig) = @_;
21208:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
21209:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
21210:     my ($othertitle,$usertypes,$types) =
21211:         &Apache::loncommon::sorted_inst_types($dom);
21212:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21213:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
21214:     my @sparestypes = ('primary','default');
21215:     my %typetitles = &sparestype_titles();
21216:     my $resulttext;
21217:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
21218:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
21219:         %existing = %{$domconfig{'loadbalancing'}};
21220:     }
21221:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
21222:                               \%currtargets,\%currrules,\%currcookies);
21223:     my ($saveloadbalancing,%defaultshash,%changes);
21224:     my ($alltypes,$othertypes,$titles) =
21225:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
21226:     my %ruletitles = &offloadtype_text();
21227:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
21228:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
21229:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
21230:         if ($balancer eq '') {
21231:             next;
21232:         }
21233:         if (!exists($servers{$balancer})) {
21234:             if (exists($currbalancer{$balancer})) {
21235:                 push(@{$changes{'delete'}},$balancer);
21236:             }
21237:             next;
21238:         }
21239:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
21240:             push(@{$changes{'delete'}},$balancer);
21241:             next;
21242:         }
21243:         if (!exists($currbalancer{$balancer})) {
21244:             push(@{$changes{'add'}},$balancer);
21245:         }
21246:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
21247:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
21248:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
21249:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
21250:             $saveloadbalancing = 1;
21251:         }
21252:         foreach my $sparetype (@sparestypes) {
21253:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
21254:             my @offloadto;
21255:             foreach my $target (@targets) {
21256:                 if (($servers{$target}) && ($target ne $balancer)) {
21257:                     if ($sparetype eq 'default') {
21258:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
21259:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
21260:                         }
21261:                     }
21262:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
21263:                         push(@offloadto,$target);
21264:                     }
21265:                 }
21266:             }
21267:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
21268:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
21269:                     push(@offloadto,$balancer);
21270:                 }
21271:             }
21272:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
21273:         }
21274:         if ($env{'form.loadbalancing_cookie_'.$i}) {
21275:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
21276:             if (exists($currbalancer{$balancer})) { 
21277:                 unless ($currcookies{$balancer}) {
21278:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
21279:                 }
21280:             }
21281:         } elsif (exists($currbalancer{$balancer})) {
21282:             if ($currcookies{$balancer}) {
21283:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
21284:             }
21285:         }
21286:         if (ref($currtargets{$balancer}) eq 'HASH') {
21287:             foreach my $sparetype (@sparestypes) {
21288:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
21289:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
21290:                     if (@targetdiffs > 0) {
21291:                         $changes{'curr'}{$balancer}{'targets'} = 1;
21292:                     }
21293:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
21294:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
21295:                         $changes{'curr'}{$balancer}{'targets'} = 1;
21296:                     }
21297:                 }
21298:             }
21299:         } else {
21300:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
21301:                 foreach my $sparetype (@sparestypes) {
21302:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
21303:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
21304:                             $changes{'curr'}{$balancer}{'targets'} = 1;
21305:                         }
21306:                     }
21307:                 }
21308:             }
21309:         }
21310:         my $ishomedom;
21311:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
21312:             $ishomedom = 1;
21313:         }
21314:         if (ref($alltypes) eq 'ARRAY') {
21315:             foreach my $type (@{$alltypes}) {
21316:                 my $rule;
21317:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
21318:                          (!$ishomedom)) {
21319:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
21320:                 }
21321:                 if ($rule eq 'specific') {
21322:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
21323:                     if (exists($servers{$specifiedhost})) {
21324:                         $rule = $specifiedhost;
21325:                     }
21326:                 }
21327:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
21328:                 if (ref($currrules{$balancer}) eq 'HASH') {
21329:                     if ($rule ne $currrules{$balancer}{$type}) {
21330:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
21331:                     }
21332:                 } elsif ($rule ne '') {
21333:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
21334:                 }
21335:             }
21336:         }
21337:     }
21338:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
21339:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
21340:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
21341:             $defaultshash{'loadbalancing'} = {};
21342:         }
21343:         my $putresult = &Apache::lonnet::put_dom('configuration',
21344:                                                  \%defaultshash,$dom);
21345:         if ($putresult eq 'ok') {
21346:             if (keys(%changes) > 0) {
21347:                 my %toupdate;
21348:                 if (ref($changes{'delete'}) eq 'ARRAY') {
21349:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
21350:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
21351:                         $toupdate{$balancer} = 1;
21352:                     }
21353:                 }
21354:                 if (ref($changes{'add'}) eq 'ARRAY') {
21355:                     foreach my $balancer (sort(@{$changes{'add'}})) {
21356:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
21357:                         $toupdate{$balancer} = 1;
21358:                     }
21359:                 }
21360:                 if (ref($changes{'curr'}) eq 'HASH') {
21361:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
21362:                         $toupdate{$balancer} = 1;
21363:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
21364:                             if ($changes{'curr'}{$balancer}{'targets'}) {
21365:                                 my %offloadstr;
21366:                                 foreach my $sparetype (@sparestypes) {
21367:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
21368:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
21369:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
21370:                                         }
21371:                                     }
21372:                                 }
21373:                                 if (keys(%offloadstr) == 0) {
21374:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
21375:                                 } else {
21376:                                     my $showoffload;
21377:                                     foreach my $sparetype (@sparestypes) {
21378:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
21379:                                         if (defined($offloadstr{$sparetype})) {
21380:                                             $showoffload .= $offloadstr{$sparetype};
21381:                                         } else {
21382:                                             $showoffload .= &mt('None');
21383:                                         }
21384:                                         $showoffload .= ('&nbsp;'x3);
21385:                                     }
21386:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
21387:                                 }
21388:                             }
21389:                         }
21390:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
21391:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
21392:                                 foreach my $type (@{$alltypes}) {
21393:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
21394:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
21395:                                         my $balancetext;
21396:                                         if ($rule eq '') {
21397:                                             $balancetext =  $ruletitles{'default'};
21398:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
21399:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
21400:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
21401:                                                 foreach my $sparetype (@sparestypes) {
21402:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
21403:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
21404:                                                     }
21405:                                                 }
21406:                                                 foreach my $item (@{$alltypes}) {
21407:                                                     next if ($item =~  /^_LC_ipchange/);
21408:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
21409:                                                     if ($hasrule eq 'homeserver') {
21410:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
21411:                                                     } else {
21412:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
21413:                                                             if ($servers{$hasrule}) {
21414:                                                                 $toupdate{$hasrule} = 1;
21415:                                                             }
21416:                                                         }
21417:                                                     }
21418:                                                 }
21419:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
21420:                                                     $balancetext =  $ruletitles{$rule};
21421:                                                 } else {
21422:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
21423:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
21424:                                                     if ($receiver) {
21425:                                                         $toupdate{$receiver};
21426:                                                     }
21427:                                                 }
21428:                                             } else {
21429:                                                 $balancetext =  $ruletitles{$rule};
21430:                                             }
21431:                                         } else {
21432:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
21433:                                         }
21434:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
21435:                                     }
21436:                                 }
21437:                             }
21438:                         }
21439:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
21440:                             $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
21441:                                                       $balancer).'</li>'; 
21442:                         }
21443:                     }
21444:                 }
21445:                 if (keys(%toupdate)) {
21446:                     my %thismachine;
21447:                     my $updatedhere;
21448:                     my $cachetime = 60*60*24;
21449:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
21450:                     foreach my $lonhost (keys(%toupdate)) {
21451:                         if ($thismachine{$lonhost}) {
21452:                             unless ($updatedhere) {
21453:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
21454:                                                               $defaultshash{'loadbalancing'},
21455:                                                               $cachetime);
21456:                                 $updatedhere = 1;
21457:                             }
21458:                         } else {
21459:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
21460:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
21461:                         }
21462:                     }
21463:                 }
21464:                 if ($resulttext ne '') {
21465:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
21466:                 } else {
21467:                     $resulttext = $nochgmsg;
21468:                 }
21469:             } else {
21470:                 $resulttext = $nochgmsg;
21471:             }
21472:         } else {
21473:             $resulttext = '<span class="LC_error">'.
21474:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21475:         }
21476:     } else {
21477:         $resulttext = $nochgmsg;
21478:     }
21479:     return $resulttext;
21480: }
21481: 
21482: sub recurse_check {
21483:     my ($chkcats,$categories,$depth,$name) = @_;
21484:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
21485:         my $chg = 0;
21486:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
21487:             my $category = $chkcats->[$depth]{$name}[$j];
21488:             my $item;
21489:             if ($category eq '') {
21490:                 $chg ++;
21491:             } else {
21492:                 my $deeper = $depth + 1;
21493:                 $item = &escape($category).':'.&escape($name).':'.$depth;
21494:                 if ($chg) {
21495:                     $categories->{$item} -= $chg;
21496:                 }
21497:                 &recurse_check($chkcats,$categories,$deeper,$category);
21498:                 $deeper --;
21499:             }
21500:         }
21501:     }
21502:     return;
21503: }
21504: 
21505: sub recurse_cat_deletes {
21506:     my ($item,$coursecategories,$deletions) = @_;
21507:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
21508:     my $subdepth = $depth + 1;
21509:     if (ref($coursecategories) eq 'HASH') {
21510:         foreach my $subitem (keys(%{$coursecategories})) {
21511:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
21512:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
21513:                 delete($coursecategories->{$subitem});
21514:                 $deletions->{$subitem} = 1;
21515:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
21516:             }
21517:         }
21518:     }
21519:     return;
21520: }
21521: 
21522: sub active_dc_picker {
21523:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
21524:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
21525:     my @domcoord = keys(%domcoords);
21526:     if (keys(%currhash)) {
21527:         foreach my $dc (keys(%currhash)) {
21528:             unless (exists($domcoords{$dc})) {
21529:                 push(@domcoord,$dc);
21530:             }
21531:         }
21532:     }
21533:     @domcoord = sort(@domcoord);
21534:     my $numdcs = scalar(@domcoord);
21535:     my $rows = 0;
21536:     my $table;
21537:     if ($numdcs > 1) {
21538:         $table = '<table>';
21539:         for (my $i=0; $i<@domcoord; $i++) {
21540:             my $rem = $i%($numinrow);
21541:             if ($rem == 0) {
21542:                 if ($i > 0) {
21543:                     $table .= '</tr>';
21544:                 }
21545:                 $table .= '<tr>';
21546:                 $rows ++;
21547:             }
21548:             my $check = '';
21549:             if ($inputtype eq 'radio') {
21550:                 if (keys(%currhash) == 0) {
21551:                     if (!$i) {
21552:                         $check = ' checked="checked"';
21553:                     }
21554:                 } elsif (exists($currhash{$domcoord[$i]})) {
21555:                     $check = ' checked="checked"';
21556:                 }
21557:             } else {
21558:                 if (exists($currhash{$domcoord[$i]})) {
21559:                     $check = ' checked="checked"';
21560:                 }
21561:             }
21562:             if ($i == @domcoord - 1) {
21563:                 my $colsleft = $numinrow - $rem;
21564:                 if ($colsleft > 1) {
21565:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
21566:                 } else {
21567:                     $table .= '<td class="LC_left_item">';
21568:                 }
21569:             } else {
21570:                 $table .= '<td class="LC_left_item">';
21571:             }
21572:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
21573:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
21574:             $table .= '<span class="LC_nobreak"><label>'.
21575:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
21576:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
21577:             if ($user ne $dcname.':'.$dcdom) {
21578:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21579:             }
21580:             $table .= '</label></span></td>';
21581:         }
21582:         $table .= '</tr></table>';
21583:     } elsif ($numdcs == 1) {
21584:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
21585:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
21586:         if ($inputtype eq 'radio') {
21587:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
21588:             if ($user ne $dcname.':'.$dcdom) {
21589:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21590:             }
21591:         } else {
21592:             my $check;
21593:             if (exists($currhash{$domcoord[0]})) {
21594:                 $check = ' checked="checked"';
21595:             }
21596:             $table = '<span class="LC_nobreak"><label>'.
21597:                      '<input type="checkbox" name="'.$name.'" '.
21598:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
21599:             if ($user ne $dcname.':'.$dcdom) {
21600:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21601:             }
21602:             $table .= '</label></span>';
21603:             $rows ++;
21604:         }
21605:     }
21606:     return ($numdcs,$table,$rows);
21607: }
21608: 
21609: sub usersession_titles {
21610:     return &Apache::lonlocal::texthash(
21611:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
21612:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
21613:                spares => 'Servers offloaded to, when busy',
21614:                version => 'LON-CAPA version requirement',
21615:                excludedomain => 'Allow all, but exclude specific domains',
21616:                includedomain => 'Deny all, but include specific domains',
21617:                primary => 'Primary (checked first)',
21618:                default => 'Default',
21619:            );
21620: }
21621: 
21622: sub id_for_thisdom {
21623:     my (%servers) = @_;
21624:     my %altids;
21625:     foreach my $server (keys(%servers)) {
21626:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21627:         if ($serverhome ne $server) {
21628:             $altids{$serverhome} = $server;
21629:         }
21630:     }
21631:     return %altids;
21632: }
21633: 
21634: sub count_servers {
21635:     my ($currbalancer,%servers) = @_;
21636:     my (@spares,$numspares);
21637:     foreach my $lonhost (sort(keys(%servers))) {
21638:         next if ($currbalancer eq $lonhost);
21639:         push(@spares,$lonhost);
21640:     }
21641:     if ($currbalancer) {
21642:         $numspares = scalar(@spares);
21643:     } else {
21644:         $numspares = scalar(@spares) - 1;
21645:     }
21646:     return ($numspares,@spares);
21647: }
21648: 
21649: sub lonbalance_targets_js {
21650:     my ($dom,$types,$servers,$settings) = @_;
21651:     my $select = &mt('Select');
21652:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
21653:     if (ref($servers) eq 'HASH') {
21654:         $alltargets = join("','",sort(keys(%{$servers})));
21655:         my @homedoms;
21656:         foreach my $server (sort(keys(%{$servers}))) {
21657:             if (&Apache::lonnet::host_domain($server) eq $dom) {
21658:                 push(@homedoms,'1');
21659:             } else {
21660:                 push(@homedoms,'0');
21661:             }
21662:         }
21663:         $allishome = join("','",@homedoms);
21664:     }
21665:     if (ref($types) eq 'ARRAY') {
21666:         if (@{$types} > 0) {
21667:             @alltypes = @{$types};
21668:         }
21669:     }
21670:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
21671:     $allinsttypes = join("','",@alltypes);
21672:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
21673:     if (ref($settings) eq 'HASH') {
21674:         %existing = %{$settings};
21675:     }
21676:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
21677:                               \%currtargets,\%currrules,\%currcookies);
21678:     my $balancers = join("','",sort(keys(%currbalancer)));
21679:     return <<"END";
21680: 
21681: <script type="text/javascript">
21682: // <![CDATA[
21683: 
21684: currBalancers = new Array('$balancers');
21685: 
21686: function toggleTargets(balnum) {
21687:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
21688:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
21689:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
21690:     var prevbalancer = prevhostitem.value;
21691:     var baltotal = document.getElementById('loadbalancing_total').value;
21692:     prevhostitem.value = balancer;
21693:     if (prevbalancer != '') {
21694:         var prevIdx = currBalancers.indexOf(prevbalancer);
21695:         if (prevIdx != -1) {
21696:             currBalancers.splice(prevIdx,1);
21697:         }
21698:     }
21699:     if (balancer == '') {
21700:         hideSpares(balnum);
21701:     } else {
21702:         var currIdx = currBalancers.indexOf(balancer);
21703:         if (currIdx == -1) {
21704:             currBalancers.push(balancer);
21705:         }
21706:         var homedoms = new Array('$allishome');
21707:         var ishomedom = homedoms[lonhostitem.selectedIndex];
21708:         showSpares(balancer,ishomedom,balnum);
21709:     }
21710:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
21711:     return;
21712: }
21713: 
21714: function showSpares(balancer,ishomedom,balnum) {
21715:     var alltargets = new Array('$alltargets');
21716:     var insttypes = new Array('$allinsttypes');
21717:     var offloadtypes = new Array('primary','default');
21718: 
21719:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
21720:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
21721:  
21722:     for (var i=0; i<offloadtypes.length; i++) {
21723:         var count = 0;
21724:         for (var j=0; j<alltargets.length; j++) {
21725:             if (alltargets[j] != balancer) {
21726:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
21727:                 item.value = alltargets[j];
21728:                 item.style.textAlign='left';
21729:                 item.style.textFace='normal';
21730:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
21731:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
21732:                     item.disabled = '';
21733:                 } else {
21734:                     item.disabled = 'disabled';
21735:                     item.checked = false;
21736:                 }
21737:                 count ++;
21738:             }
21739:         }
21740:     }
21741:     for (var k=0; k<insttypes.length; k++) {
21742:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
21743:             if (ishomedom == 1) {
21744:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
21745:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
21746:             } else {
21747:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
21748:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
21749:             }
21750:         } else {
21751:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
21752:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
21753:         }
21754:         if ((insttypes[k] != '_LC_external') && 
21755:             ((insttypes[k] != '_LC_internetdom') ||
21756:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
21757:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
21758:             item.options.length = 0;
21759:             item.options[0] = new Option("","",true,true);
21760:             var idx = 0;
21761:             for (var m=0; m<alltargets.length; m++) {
21762:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
21763:                     idx ++;
21764:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
21765:                 }
21766:             }
21767:         }
21768:     }
21769:     return;
21770: }
21771: 
21772: function hideSpares(balnum) {
21773:     var alltargets = new Array('$alltargets');
21774:     var insttypes = new Array('$allinsttypes');
21775:     var offloadtypes = new Array('primary','default');
21776: 
21777:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
21778:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
21779: 
21780:     var total = alltargets.length - 1;
21781:     for (var i=0; i<offloadtypes; i++) {
21782:         for (var j=0; j<total; j++) {
21783:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
21784:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
21785:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
21786:         }
21787:     }
21788:     for (var k=0; k<insttypes.length; k++) {
21789:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
21790:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
21791:         if (insttypes[k] != '_LC_external') {
21792:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
21793:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
21794:         }
21795:     }
21796:     return;
21797: }
21798: 
21799: function checkOffloads(item,balnum,type) {
21800:     var alltargets = new Array('$alltargets');
21801:     var offloadtypes = new Array('primary','default');
21802:     if (item.checked) {
21803:         var total = alltargets.length - 1;
21804:         var other;
21805:         if (type == offloadtypes[0]) {
21806:             other = offloadtypes[1];
21807:         } else {
21808:             other = offloadtypes[0];
21809:         }
21810:         for (var i=0; i<total; i++) {
21811:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
21812:             if (server == item.value) {
21813:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
21814:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
21815:                 }
21816:             }
21817:         }
21818:     }
21819:     return;
21820: }
21821: 
21822: function singleServerToggle(balnum,type) {
21823:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
21824:     if (offloadtoSelIdx == 0) {
21825:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
21826:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
21827: 
21828:     } else {
21829:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
21830:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
21831:     }
21832:     return;
21833: }
21834: 
21835: function balanceruleChange(formname,balnum,type) {
21836:     if (type == '_LC_external') {
21837:         return;
21838:     }
21839:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
21840:     for (var i=0; i<typesRules.length; i++) {
21841:         if (formname.elements[typesRules[i]].checked) {
21842:             if (formname.elements[typesRules[i]].value != 'specific') {
21843:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
21844:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
21845:             } else {
21846:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
21847:             }
21848:         }
21849:     }
21850:     return;
21851: }
21852: 
21853: function balancerDeleteChange(balnum) {
21854:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
21855:     var baltotal = document.getElementById('loadbalancing_total').value;
21856:     var addtarget;
21857:     var removetarget;
21858:     var action = 'delete';
21859:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
21860:         var lonhost = hostitem.value;
21861:         var currIdx = currBalancers.indexOf(lonhost);
21862:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
21863:             if (currIdx != -1) {
21864:                 currBalancers.splice(currIdx,1);
21865:             }
21866:             addtarget = lonhost;
21867:         } else {
21868:             if (currIdx == -1) {
21869:                 currBalancers.push(lonhost);
21870:             }
21871:             removetarget = lonhost;
21872:             action = 'undelete';
21873:         }
21874:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
21875:     }
21876:     return;
21877: }
21878: 
21879: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
21880:     if (baltotal > 1) {
21881:         var offloadtypes = new Array('primary','default');
21882:         var alltargets = new Array('$alltargets');
21883:         var insttypes = new Array('$allinsttypes');
21884:         for (var i=0; i<baltotal; i++) {
21885:             if (i != balnum) {
21886:                 for (var j=0; j<offloadtypes.length; j++) {
21887:                     var total = alltargets.length - 1;
21888:                     for (var k=0; k<total; k++) {
21889:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
21890:                         var server = serveritem.value;
21891:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
21892:                             if (server == addtarget) {
21893:                                 serveritem.disabled = '';
21894:                             }
21895:                         }
21896:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
21897:                             if (server == removetarget) {
21898:                                 serveritem.disabled = 'disabled';
21899:                                 serveritem.checked = false;
21900:                             }
21901:                         }
21902:                     }
21903:                 }
21904:                 for (var j=0; j<insttypes.length; j++) {
21905:                     if (insttypes[j] != '_LC_external') {
21906:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
21907:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
21908:                             var currSel = singleserver.selectedIndex;
21909:                             var currVal = singleserver.options[currSel].value;
21910:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
21911:                                 var numoptions = singleserver.options.length;
21912:                                 var needsnew = 1;
21913:                                 for (var k=0; k<numoptions; k++) {
21914:                                     if (singleserver.options[k] == addtarget) {
21915:                                         needsnew = 0;
21916:                                         break;
21917:                                     }
21918:                                 }
21919:                                 if (needsnew == 1) {
21920:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
21921:                                 }
21922:                             }
21923:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
21924:                                 singleserver.options.length = 0;
21925:                                 if ((currVal) && (currVal != removetarget)) {
21926:                                     singleserver.options[0] = new Option("","",false,false);
21927:                                 } else {
21928:                                     singleserver.options[0] = new Option("","",true,true);
21929:                                 }
21930:                                 var idx = 0;
21931:                                 for (var m=0; m<alltargets.length; m++) {
21932:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
21933:                                         idx ++;
21934:                                         if (currVal == alltargets[m]) {
21935:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
21936:                                         } else {
21937:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
21938:                                         }
21939:                                     }
21940:                                 }
21941:                             }
21942:                         }
21943:                     }
21944:                 }
21945:             }
21946:         }
21947:     }
21948:     return;
21949: }
21950: 
21951: // ]]>
21952: </script>
21953: 
21954: END
21955: }
21956: 
21957: 
21958: sub new_spares_js {
21959:     my @sparestypes = ('primary','default');
21960:     my $types = join("','",@sparestypes);
21961:     my $select = &mt('Select');
21962:     return <<"END";
21963: 
21964: <script type="text/javascript">
21965: // <![CDATA[
21966: 
21967: function updateNewSpares(formname,lonhost) {
21968:     var types = new Array('$types');
21969:     var include = new Array();
21970:     var exclude = new Array();
21971:     for (var i=0; i<types.length; i++) {
21972:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
21973:         for (var j=0; j<spareboxes.length; j++) {
21974:             if (formname.elements[spareboxes[j]].checked) {
21975:                 exclude.push(formname.elements[spareboxes[j]].value);
21976:             } else {
21977:                 include.push(formname.elements[spareboxes[j]].value);
21978:             }
21979:         }
21980:     }
21981:     for (var i=0; i<types.length; i++) {
21982:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
21983:         var selIdx = newSpare.selectedIndex;
21984:         var currnew = newSpare.options[selIdx].value;
21985:         var okSpares = new Array();
21986:         for (var j=0; j<newSpare.options.length; j++) {
21987:             var possible = newSpare.options[j].value;
21988:             if (possible != '') {
21989:                 if (exclude.indexOf(possible) == -1) {
21990:                     okSpares.push(possible);
21991:                 } else {
21992:                     if (currnew == possible) {
21993:                         selIdx = 0;
21994:                     }
21995:                 }
21996:             }
21997:         }
21998:         for (var k=0; k<include.length; k++) {
21999:             if (okSpares.indexOf(include[k]) == -1) {
22000:                 okSpares.push(include[k]);
22001:             }
22002:         }
22003:         okSpares.sort();
22004:         newSpare.options.length = 0;
22005:         if (selIdx == 0) {
22006:             newSpare.options[0] = new Option("$select","",true,true);
22007:         } else {
22008:             newSpare.options[0] = new Option("$select","",false,false);
22009:         }
22010:         for (var m=0; m<okSpares.length; m++) {
22011:             var idx = m+1;
22012:             var selThis = 0;
22013:             if (selIdx != 0) {
22014:                 if (okSpares[m] == currnew) {
22015:                     selThis = 1;
22016:                 }
22017:             }
22018:             if (selThis == 1) {
22019:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
22020:             } else {
22021:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
22022:             }
22023:         }
22024:     }
22025:     return;
22026: }
22027: 
22028: function checkNewSpares(lonhost,type) {
22029:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
22030:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
22031:     if (chosen != '') {
22032:         var othertype;
22033:         var othernewSpare;
22034:         if (type == 'primary') {
22035:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
22036:         }
22037:         if (type == 'default') {
22038:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
22039:         }
22040:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
22041:             othernewSpare.selectedIndex = 0;
22042:         }
22043:     }
22044:     return;
22045: }
22046: 
22047: // ]]>
22048: </script>
22049: 
22050: END
22051: 
22052: }
22053: 
22054: sub common_domprefs_js {
22055:     return <<"END";
22056: 
22057: <script type="text/javascript">
22058: // <![CDATA[
22059: 
22060: function getIndicesByName(formname,item) {
22061:     var group = new Array();
22062:     for (var i=0;i<formname.elements.length;i++) {
22063:         if (formname.elements[i].name == item) {
22064:             group.push(formname.elements[i].id);
22065:         }
22066:     }
22067:     return group;
22068: }
22069: 
22070: // ]]>
22071: </script>
22072: 
22073: END
22074: 
22075: }
22076: 
22077: sub recaptcha_js {
22078:     my %lt = &captcha_phrases();
22079:     return <<"END";
22080: 
22081: <script type="text/javascript">
22082: // <![CDATA[
22083: 
22084: function updateCaptcha(caller,context) {
22085:     var privitem;
22086:     var pubitem;
22087:     var privtext;
22088:     var pubtext;
22089:     var versionitem;
22090:     var versiontext;
22091:     if (document.getElementById(context+'_recaptchapub')) {
22092:         pubitem = document.getElementById(context+'_recaptchapub');
22093:     } else {
22094:         return;
22095:     }
22096:     if (document.getElementById(context+'_recaptchapriv')) {
22097:         privitem = document.getElementById(context+'_recaptchapriv');
22098:     } else {
22099:         return;
22100:     }
22101:     if (document.getElementById(context+'_recaptchapubtxt')) {
22102:         pubtext = document.getElementById(context+'_recaptchapubtxt');
22103:     } else {
22104:         return;
22105:     }
22106:     if (document.getElementById(context+'_recaptchaprivtxt')) {
22107:         privtext = document.getElementById(context+'_recaptchaprivtxt');
22108:     } else {
22109:         return;
22110:     }
22111:     if (document.getElementById(context+'_recaptchaversion')) {
22112:         versionitem = document.getElementById(context+'_recaptchaversion');
22113:     } else {
22114:         return;
22115:     }
22116:     if (document.getElementById(context+'_recaptchavertxt')) {
22117:         versiontext = document.getElementById(context+'_recaptchavertxt');
22118:     } else {
22119:         return;
22120:     }
22121:     if (caller.checked) {
22122:         if (caller.value == 'recaptcha') {
22123:             pubitem.type = 'text';
22124:             privitem.type = 'text';
22125:             pubitem.size = '40';
22126:             privitem.size = '40';
22127:             pubtext.innerHTML = "$lt{'pub'}";
22128:             privtext.innerHTML = "$lt{'priv'}";
22129:             versionitem.type = 'text';
22130:             versionitem.size = '3';
22131:             versiontext.innerHTML = "$lt{'ver'}";
22132:         } else {
22133:             pubitem.type = 'hidden';
22134:             privitem.type = 'hidden';
22135:             versionitem.type = 'hidden';
22136:             pubtext.innerHTML = '';
22137:             privtext.innerHTML = '';
22138:             versiontext.innerHTML = '';
22139:         }
22140:     }
22141:     return;
22142: }
22143: 
22144: // ]]>
22145: </script>
22146: 
22147: END
22148: 
22149: }
22150: 
22151: sub toggle_display_js {
22152:     return <<"END";
22153: 
22154: <script type="text/javascript">
22155: // <![CDATA[
22156: 
22157: function toggleDisplay(domForm,caller) {
22158:     if (document.getElementById(caller)) {
22159:         var divitem = document.getElementById(caller);
22160:         var optionsElement = domForm.coursecredits;
22161:         var checkval = 1;
22162:         var dispval = 'block';
22163:         var selfcreateRegExp = /^cancreate_emailverified/;
22164:         if (caller == 'emailoptions') {
22165:             optionsElement = domForm.cancreate_email;
22166:         }
22167:         if (caller == 'studentsubmission') {
22168:             optionsElement = domForm.postsubmit;
22169:         }
22170:         if (caller == 'cloneinstcode') {
22171:             optionsElement = domForm.canclone;
22172:             checkval = 'instcode';
22173:         }
22174:         if (selfcreateRegExp.test(caller)) {
22175:             optionsElement = domForm.elements[caller];
22176:             checkval = 'other';
22177:             dispval = 'inline'
22178:         }
22179:         if (optionsElement.length) {
22180:             var currval;
22181:             for (var i=0; i<optionsElement.length; i++) {
22182:                 if (optionsElement[i].checked) {
22183:                    currval = optionsElement[i].value;
22184:                 }
22185:             }
22186:             if (currval == checkval) {
22187:                 divitem.style.display = dispval;
22188:             } else {
22189:                 divitem.style.display = 'none';
22190:             }
22191:         }
22192:     }
22193:     return;
22194: }
22195: 
22196: // ]]>
22197: </script>
22198: 
22199: END
22200: 
22201: }
22202: 
22203: sub captcha_phrases {
22204:     return &Apache::lonlocal::texthash (
22205:                  priv => 'Private key',
22206:                  pub  => 'Public key',
22207:                  original  => 'original (CAPTCHA)',
22208:                  recaptcha => 'successor (ReCAPTCHA)',
22209:                  notused   => 'unused',
22210:                  ver => 'ReCAPTCHA version (1 or 2)',
22211:     );
22212: }
22213: 
22214: sub devalidate_remote_domconfs {
22215:     my ($dom,$cachekeys) = @_;
22216:     return unless (ref($cachekeys) eq 'HASH');
22217:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22218:     my %thismachine;
22219:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
22220:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
22221:                       'directorysrch','passwdconf','cats','proxyalias');
22222:     my %cache_by_lonhost;
22223:     if (exists($cachekeys->{'samllanding'})) {
22224:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
22225:             my %landing = %{$cachekeys->{'samllanding'}};
22226:             my %domservers = &Apache::lonnet::get_servers($dom);
22227:             if (keys(%domservers)) {
22228:                 foreach my $server (keys(%domservers)) {
22229:                     my @cached;
22230:                     next if ($thismachine{$server});
22231:                     if ($landing{$server}) {
22232:                         push(@cached,&escape('samllanding').':'.&escape($server));
22233:                     }
22234:                     if (@cached) {
22235:                         $cache_by_lonhost{$server} = \@cached;
22236:                     }
22237:                 }
22238:             }
22239:         }
22240:     }
22241:     if (keys(%servers)) {
22242:         foreach my $server (keys(%servers)) {
22243:             next if ($thismachine{$server});
22244:             my @cached;
22245:             foreach my $name (@posscached) {
22246:                 if ($cachekeys->{$name}) {
22247:                     if ($name eq 'proxyalias') {
22248:                         if (ref($cachekeys->{$name}) eq 'HASH') {
22249:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
22250:                                 push(@cached,&escape($name).':'.&escape($key));
22251:                             }
22252:                         }
22253:                     } else {
22254:                         push(@cached,&escape($name).':'.&escape($dom));
22255:                     }
22256:                 }
22257:             }
22258:             if ((exists($cache_by_lonhost{$server})) &&
22259:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
22260:                 push(@cached,@{$cache_by_lonhost{$server}});
22261:             }
22262:             if (@cached) {
22263:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
22264:             }
22265:         }
22266:     }
22267:     return;
22268: }
22269: 
22270: 1;

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